@kubohiroya/sb3-toolchain 0.19.0 → 0.19.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +5 -0
- package/README.ja.md +1 -1
- package/README.md +1 -1
- package/dist/cli.d.ts +2 -0
- package/dist/cli.js +16 -1
- package/dist/cli.js.map +1 -1
- package/dist/constants.d.ts +1 -1
- package/dist/constants.js +1 -1
- package/dist/constants.js.map +1 -1
- package/dist/extension-bundle-configuration.d.ts +4 -2
- package/dist/extension-bundle-configuration.js +9 -3
- package/dist/extension-bundle-configuration.js.map +1 -1
- package/dist/extension-bundle-metadata.d.ts +3 -0
- package/dist/extension-bundle-metadata.js +73 -0
- package/dist/extension-bundle-metadata.js.map +1 -0
- package/dist/extension-bundle.js +17 -3
- package/dist/extension-bundle.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/types.d.ts +14 -0
- package/docs/extension-bundles.md +30 -0
- package/docs/index.html +2 -2
- package/docs/ja/extension-bundles.md +30 -0
- package/package.json +3 -3
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.19.1 - 2026-10-29
|
|
4
|
+
|
|
5
|
+
- Preserve explicitly configured bundle presentation metadata in classic and module headers, source configuration, and the CLI.
|
|
6
|
+
- Keep generated bytes unchanged when metadata is omitted, and retain member license notices and sandbox requirements.
|
|
7
|
+
|
|
3
8
|
## 0.19.0 - 2026-10-28
|
|
4
9
|
|
|
5
10
|
- Refresh family dependencies and release registration.
|
package/README.ja.md
CHANGED
|
@@ -31,7 +31,7 @@ Scratch 3およびTurboWarpの`.sb3`プロジェクトを、Gitで差分を確
|
|
|
31
31
|
再現可能なインストールのため、検証済みのnpmバージョンを固定します。
|
|
32
32
|
|
|
33
33
|
```bash
|
|
34
|
-
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.19.
|
|
34
|
+
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.19.1
|
|
35
35
|
```
|
|
36
36
|
|
|
37
37
|
## クイックスタート
|
package/README.md
CHANGED
|
@@ -32,7 +32,7 @@ expanded sources and rebuilding bit-for-bit identical SB3 files from the same in
|
|
|
32
32
|
Pin the verified npm version for reproducible installation.
|
|
33
33
|
|
|
34
34
|
```bash
|
|
35
|
-
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.19.
|
|
35
|
+
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.19.1
|
|
36
36
|
```
|
|
37
37
|
|
|
38
38
|
## Quick start
|
package/dist/cli.d.ts
CHANGED
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { ExtensionBundleMetadata } from './types';
|
|
1
2
|
import { FetchImplementation } from './extension-sync';
|
|
2
3
|
export interface HelpCliOptions {
|
|
3
4
|
command: 'help';
|
|
@@ -55,6 +56,7 @@ export interface ExtensionsBundleCliOptions {
|
|
|
55
56
|
action: 'bundle';
|
|
56
57
|
bundleId: string;
|
|
57
58
|
bundleName: string;
|
|
59
|
+
metadata?: ExtensionBundleMetadata;
|
|
58
60
|
command: 'extensions';
|
|
59
61
|
extensionIds: string[];
|
|
60
62
|
recoveryCapsule: boolean;
|
package/dist/cli.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { assert } from "./assert.js";
|
|
2
|
+
import { validateExtensionBundleMetadata } from "./extension-bundle-metadata.js";
|
|
2
3
|
import { createDeterministicSb3, validateSb3Source } from "./source.js";
|
|
3
4
|
import { buildSb3 } from "./build.js";
|
|
4
5
|
import { packageVersion } from "./constants.js";
|
|
@@ -20,7 +21,7 @@ function usage() {
|
|
|
20
21
|
sb3-toolchain extensions sync SOURCE_DIR [--yes]
|
|
21
22
|
sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]
|
|
22
23
|
sb3-toolchain extensions migrate-id SOURCE_DIR --from OLD_ID --to NEW_ID [--yes]
|
|
23
|
-
sb3-toolchain extensions bundle SOURCE_DIR --id BUNDLE_ID --name NAME [EXTENSION_ID ...] [--build-mode classic|module] [--share PACKAGE@EXACT_VERSION] [--include-recovery-capsule] [--yes]
|
|
24
|
+
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]
|
|
24
25
|
sb3-toolchain extensions unbundle SOURCE_DIR BUNDLE_ID [--yes]
|
|
25
26
|
sb3-toolchain extensions unbundle INPUT.sb3 BUNDLE_ID --output OUTPUT.sb3 [--yes]
|
|
26
27
|
|
|
@@ -235,6 +236,7 @@ function parseExtensionIdMigrationArguments(arguments_) {
|
|
|
235
236
|
function parseExtensionBundleArguments(arguments_) {
|
|
236
237
|
let bundleId;
|
|
237
238
|
let bundleName;
|
|
239
|
+
let metadata;
|
|
238
240
|
let recoveryCapsule = false;
|
|
239
241
|
let sourceDirectory;
|
|
240
242
|
const extensionIds = [];
|
|
@@ -249,6 +251,17 @@ function parseExtensionBundleArguments(arguments_) {
|
|
|
249
251
|
} else if (argument === "--name") {
|
|
250
252
|
bundleName = takeValue(arguments_, index, "--name");
|
|
251
253
|
index += 1;
|
|
254
|
+
} else if (argument === "--metadata-json") {
|
|
255
|
+
assert(metadata === void 0, "--metadata-json may only be specified once.");
|
|
256
|
+
const value = takeValue(arguments_, index, "--metadata-json");
|
|
257
|
+
let parsed;
|
|
258
|
+
try {
|
|
259
|
+
parsed = JSON.parse(value);
|
|
260
|
+
} catch {
|
|
261
|
+
throw new Error("--metadata-json must contain a JSON object.");
|
|
262
|
+
}
|
|
263
|
+
metadata = validateExtensionBundleMetadata(parsed);
|
|
264
|
+
index += 1;
|
|
252
265
|
} else if (argument === "--yes") yes = true;
|
|
253
266
|
else if (argument === "--include-recovery-capsule") recoveryCapsule = true;
|
|
254
267
|
else if (argument === "--build-mode") {
|
|
@@ -283,6 +296,7 @@ function parseExtensionBundleArguments(arguments_) {
|
|
|
283
296
|
action: "bundle",
|
|
284
297
|
bundleId,
|
|
285
298
|
bundleName,
|
|
299
|
+
...metadata === void 0 ? {} : { metadata },
|
|
286
300
|
command: "extensions",
|
|
287
301
|
extensionIds,
|
|
288
302
|
recoveryCapsule,
|
|
@@ -464,6 +478,7 @@ async function runCli(arguments_, { fetch: fetchImplementation = globalThis.fetc
|
|
|
464
478
|
const result = await bundleExtensions({
|
|
465
479
|
bundleId: options.bundleId,
|
|
466
480
|
bundleName: options.bundleName,
|
|
481
|
+
metadata: options.metadata,
|
|
467
482
|
extensionIds: options.extensionIds,
|
|
468
483
|
recoveryCapsule: options.recoveryCapsule,
|
|
469
484
|
buildMode: options.buildMode,
|
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 {packageVersion} from './constants';\nimport {unbundleSb3} from './extension-bundle-archive';\nimport {bundleExtensions, unbundleExtensions} from './extension-bundle-configuration';\nimport {migrateExtensionId} from './extension-id-migration';\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 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 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 type ExtensionsCliOptions =\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 | 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 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 ...] [--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 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\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 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 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 === '--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 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 parseExtensionsArguments(arguments_: string[]): ExtensionsCliOptions {\n const [action, ...actionArguments] = arguments_;\n assert(\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, sync, update, migrate-id, bundle, or unbundle.',\n );\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 === '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 === 'extensions') {\n if (options.action === 'bundle') {\n const result = await bundleExtensions({\n bundleId: options.bundleId,\n bundleName: options.bundleName,\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 if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n}\n"],"mappings":";;;;;;;;;;;;;AA6IA,SAAgB,QAAQ;CACtB,OAAO;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiCT;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,qBAAqB,YAAwC;CACpE,IAAI;CACJ,IAAI;CACJ,IAAI,sBAAsB;CAC1B,IAAI,MAAM;CAEV,KAAK,IAAI,QAAQ,GAAG,QAAQ,WAAW,QAAQ,SAAS,GAAG;EACzD,MAAM,WAAW,WAAW;EAC5B,IAAI,aAAa,YAAY;GAC3B,kBAAkB,KAAK,QAAQ,UAAU,YAAY,OAAO,UAAU,CAAC;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AU,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 {packageVersion} from './constants';\nimport {unbundleSb3} from './extension-bundle-archive';\nimport {bundleExtensions, unbundleExtensions} from './extension-bundle-configuration';\nimport {validateExtensionBundleMetadata} from './extension-bundle-metadata';\nimport type {ExtensionBundleMetadata} from './types';\nimport {migrateExtensionId} from './extension-id-migration';\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 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 type ExtensionsCliOptions =\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 | 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 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 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\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 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 parseExtensionsArguments(arguments_: string[]): ExtensionsCliOptions {\n const [action, ...actionArguments] = arguments_;\n assert(\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, sync, update, migrate-id, bundle, or unbundle.',\n );\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 === '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 === 'extensions') {\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 if (result.rollbackCleanupWarning) log(result.rollbackCleanupWarning);\n}\n"],"mappings":";;;;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AAS;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"}
|
package/dist/constants.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const packageName = "@kubohiroya/sb3-toolchain";
|
|
2
|
-
export declare const packageVersion = "0.19.
|
|
2
|
+
export declare const packageVersion = "0.19.1";
|
package/dist/constants.js
CHANGED
package/dist/constants.js.map
CHANGED
|
@@ -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.19.
|
|
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.19.1';\n"],"mappings":";AAEA,IAAa,cAAc;AAC3B,IAAa,iBAAiB"}
|
|
@@ -12,6 +12,7 @@ interface ExtensionBundleComponentMetadata {
|
|
|
12
12
|
export interface ExtensionBundleConfigurationInput {
|
|
13
13
|
bundleId: string;
|
|
14
14
|
bundleName: string;
|
|
15
|
+
metadata?: ExtensionBundleConfiguration['metadata'];
|
|
15
16
|
extensionIds?: string[];
|
|
16
17
|
recoveryCapsule?: boolean;
|
|
17
18
|
sourceDirectory: string;
|
|
@@ -23,6 +24,7 @@ export interface ExtensionBundlePlanResult {
|
|
|
23
24
|
applied: boolean;
|
|
24
25
|
bundleId: string;
|
|
25
26
|
bundleName: string;
|
|
27
|
+
metadata?: ExtensionBundleConfiguration['metadata'];
|
|
26
28
|
changed: boolean;
|
|
27
29
|
components: ExtensionBundleComponentMetadata[];
|
|
28
30
|
counts: ExtensionBundlePlan['counts'];
|
|
@@ -46,8 +48,8 @@ export interface ExtensionUnbundleApplyResult extends ExtensionUnbundlePlanResul
|
|
|
46
48
|
comparison?: DirectoryComparison;
|
|
47
49
|
rollbackCleanupWarning: string | null;
|
|
48
50
|
}
|
|
49
|
-
export declare function planExtensionBundle({ bundleId, bundleName, extensionIds, recoveryCapsule, sourceDirectory, buildMode, sharedDependencies, }: ExtensionBundleConfigurationInput): Promise<ExtensionBundlePlanResult>;
|
|
50
|
-
export declare function bundleExtensions({ bundleId, bundleName, extensionIds, recoveryCapsule, sourceDirectory, yes, buildMode, sharedDependencies, }: ExtensionBundleConfigurationInput): Promise<ExtensionBundleApplyResult>;
|
|
51
|
+
export declare function planExtensionBundle({ bundleId, bundleName, extensionIds, recoveryCapsule, sourceDirectory, buildMode, sharedDependencies, metadata, }: ExtensionBundleConfigurationInput): Promise<ExtensionBundlePlanResult>;
|
|
52
|
+
export declare function bundleExtensions({ bundleId, bundleName, extensionIds, recoveryCapsule, sourceDirectory, yes, buildMode, sharedDependencies, metadata, }: ExtensionBundleConfigurationInput): Promise<ExtensionBundleApplyResult>;
|
|
51
53
|
export declare function planExtensionUnbundle({ bundleId, sourceDirectory, }: {
|
|
52
54
|
bundleId: string;
|
|
53
55
|
sourceDirectory: string;
|
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { assert } from "./assert.js";
|
|
2
2
|
import { assertNoInterruptedRollback, compareDirectories, pathExists, replaceDirectoryTransactionally } from "./output-safety.js";
|
|
3
|
+
import { validateExtensionBundleMetadata } from "./extension-bundle-metadata.js";
|
|
3
4
|
import { validateBundleId, validateBundleName, validateExtensionBundleConfigurations } from "./extension-bundle.js";
|
|
4
5
|
import { buildExtensionBundlesWithModules } from "./extension-module-bundle.js";
|
|
5
6
|
import { createDeterministicSb3, inspectSb3SourceForExtensionSync } from "./source.js";
|
|
@@ -21,7 +22,7 @@ async function readExtensionManifest(source) {
|
|
|
21
22
|
const manifestPath = path.join(source.resolvedSourceDirectory, source.sourceManifest.embeddedExtensions);
|
|
22
23
|
return JSON.parse(await readFile(manifestPath, "utf8"));
|
|
23
24
|
}
|
|
24
|
-
async function configurationContext({ bundleId, bundleName, extensionIds, recoveryCapsule, buildMode, sharedDependencies, sourceDirectory, willReplace }) {
|
|
25
|
+
async function configurationContext({ bundleId, bundleName, extensionIds, recoveryCapsule, buildMode, sharedDependencies, metadata, sourceDirectory, willReplace }) {
|
|
25
26
|
validateBundleId(bundleId);
|
|
26
27
|
validateBundleName(bundleName);
|
|
27
28
|
assert(typeof recoveryCapsule === "boolean", "recoveryCapsule must be a boolean.");
|
|
@@ -36,6 +37,7 @@ async function configurationContext({ bundleId, bundleName, extensionIds, recove
|
|
|
36
37
|
id: bundleId,
|
|
37
38
|
members,
|
|
38
39
|
name: bundleName,
|
|
40
|
+
...metadata === void 0 ? {} : { metadata: validateExtensionBundleMetadata(metadata) },
|
|
39
41
|
...buildMode === void 0 ? {} : { buildMode },
|
|
40
42
|
...sharedDependencies === void 0 ? {} : { sharedDependencies },
|
|
41
43
|
...recoveryCapsule === true ? { recoveryCapsule: true } : {}
|
|
@@ -58,7 +60,7 @@ async function configurationContext({ bundleId, bundleName, extensionIds, recove
|
|
|
58
60
|
source
|
|
59
61
|
};
|
|
60
62
|
}
|
|
61
|
-
async function planExtensionBundle({ bundleId, bundleName, extensionIds, recoveryCapsule = false, sourceDirectory, buildMode, sharedDependencies }) {
|
|
63
|
+
async function planExtensionBundle({ bundleId, bundleName, extensionIds, recoveryCapsule = false, sourceDirectory, buildMode, sharedDependencies, metadata }) {
|
|
62
64
|
const context = await configurationContext({
|
|
63
65
|
bundleId,
|
|
64
66
|
bundleName,
|
|
@@ -67,12 +69,14 @@ async function planExtensionBundle({ bundleId, bundleName, extensionIds, recover
|
|
|
67
69
|
sourceDirectory,
|
|
68
70
|
buildMode,
|
|
69
71
|
sharedDependencies,
|
|
72
|
+
metadata,
|
|
70
73
|
willReplace: false
|
|
71
74
|
});
|
|
72
75
|
return {
|
|
73
76
|
applied: false,
|
|
74
77
|
bundleId,
|
|
75
78
|
bundleName,
|
|
79
|
+
...context.configuredBundle.bundle.metadata === void 0 ? {} : { metadata: structuredClone(context.configuredBundle.bundle.metadata) },
|
|
76
80
|
changed: true,
|
|
77
81
|
components: context.configuredBundle.components.map((component) => component.metadata),
|
|
78
82
|
counts: context.configuredBundle.counts,
|
|
@@ -114,7 +118,7 @@ async function installManifestConfiguration(context, operation) {
|
|
|
114
118
|
});
|
|
115
119
|
}
|
|
116
120
|
}
|
|
117
|
-
async function bundleExtensions({ bundleId, bundleName, extensionIds, recoveryCapsule = false, sourceDirectory, yes = false, buildMode, sharedDependencies }) {
|
|
121
|
+
async function bundleExtensions({ bundleId, bundleName, extensionIds, recoveryCapsule = false, sourceDirectory, yes = false, buildMode, sharedDependencies, metadata }) {
|
|
118
122
|
const context = await configurationContext({
|
|
119
123
|
bundleId,
|
|
120
124
|
bundleName,
|
|
@@ -123,11 +127,13 @@ async function bundleExtensions({ bundleId, bundleName, extensionIds, recoveryCa
|
|
|
123
127
|
sourceDirectory,
|
|
124
128
|
buildMode,
|
|
125
129
|
sharedDependencies,
|
|
130
|
+
metadata,
|
|
126
131
|
willReplace: yes
|
|
127
132
|
});
|
|
128
133
|
const plan = {
|
|
129
134
|
bundleId,
|
|
130
135
|
bundleName,
|
|
136
|
+
...context.configuredBundle.bundle.metadata === void 0 ? {} : { metadata: structuredClone(context.configuredBundle.bundle.metadata) },
|
|
131
137
|
components: context.configuredBundle.components.map((component) => component.metadata),
|
|
132
138
|
counts: context.configuredBundle.counts,
|
|
133
139
|
members: [...context.configuredBundle.bundle.members],
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension-bundle-configuration.js","names":[],"sources":["../src/extension-bundle-configuration.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {cp, lstat, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert} from './assert';\nimport {\n validateBundleId,\n validateBundleName,\n validateExtensionBundleConfigurations,\n} from './extension-bundle';\nimport {buildExtensionBundlesWithModules} from './extension-module-bundle';\nimport type {ExtensionModuleBuildReport} from './extension-module-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n assertNoInterruptedRollback,\n compareDirectories,\n pathExists,\n replaceDirectoryTransactionally,\n} from './output-safety';\nimport type {DirectoryComparison} from './output-safety';\nimport {createDeterministicSb3, inspectSb3SourceForExtensionSync} from './source';\nimport type {InspectedSb3Source} from './source';\nimport type {EmbeddedExtensionManifest, ExtensionBundleConfiguration} from './types';\n\ninterface ExtensionBundleComponentMetadata {\n author: string | null;\n description: string | null;\n id: string | null;\n license: string | null;\n name: string | null;\n}\n\ninterface ConfigurationContext {\n buildPlan: Awaited<ReturnType<typeof buildExtensionBundlesWithModules>>;\n candidateManifest: EmbeddedExtensionManifest;\n configuredBundle: ExtensionBundlePlan;\n extensionManifest: EmbeddedExtensionManifest;\n source: InspectedSb3Source;\n}\n\ninterface UnbundleContext {\n candidateManifest: EmbeddedExtensionManifest;\n extensionManifest: EmbeddedExtensionManifest;\n removedBundle: ExtensionBundleConfiguration;\n source: InspectedSb3Source;\n}\n\nexport interface ExtensionBundleConfigurationInput {\n bundleId: string;\n bundleName: string;\n extensionIds?: string[];\n recoveryCapsule?: boolean;\n sourceDirectory: string;\n yes?: boolean;\n buildMode?: ExtensionBundleConfiguration['buildMode'];\n sharedDependencies?: Record<string, string>;\n}\n\nexport interface ExtensionBundlePlanResult {\n applied: boolean;\n bundleId: string;\n bundleName: string;\n changed: boolean;\n components: ExtensionBundleComponentMetadata[];\n counts: ExtensionBundlePlan['counts'];\n members: string[];\n recoveryCapsule: boolean;\n sourceDirectory: string;\n moduleBuild?: ExtensionModuleBuildReport;\n}\n\nexport interface ExtensionBundleApplyResult extends ExtensionBundlePlanResult {\n comparison?: DirectoryComparison;\n rollbackCleanupWarning: string | null;\n}\n\nexport interface ExtensionUnbundlePlanResult {\n applied: boolean;\n bundleId: string;\n changed: boolean;\n members: string[];\n sourceDirectory: string;\n}\n\nexport interface ExtensionUnbundleApplyResult extends ExtensionUnbundlePlanResult {\n comparison?: DirectoryComparison;\n rollbackCleanupWarning: string | null;\n}\n\nasync function inspectConfigurationSource(\n sourceDirectory: string,\n willReplace: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n if (willReplace) {\n assert(\n resolvedSourceDirectory !== path.parse(resolvedSourceDirectory).root,\n 'Refusing to replace a filesystem root while configuring extension bundles.',\n );\n assert(\n !(await pathExists(path.join(resolvedSourceDirectory, '.git'))),\n 'Refusing to replace a Git repository root while configuring extension bundles.',\n );\n }\n const stats = await lstat(resolvedSourceDirectory);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `SB3 source must be a directory, not a file or symbolic link: ${resolvedSourceDirectory}`,\n );\n if (willReplace) await assertNoInterruptedRollback(resolvedSourceDirectory);\n return inspectSb3SourceForExtensionSync(resolvedSourceDirectory);\n}\n\nasync function readExtensionManifest(\n source: InspectedSb3Source,\n): Promise<EmbeddedExtensionManifest> {\n const manifestPath = path.join(\n source.resolvedSourceDirectory,\n source.sourceManifest.embeddedExtensions,\n );\n return JSON.parse(await readFile(manifestPath, 'utf8')) as EmbeddedExtensionManifest;\n}\n\nasync function configurationContext({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule,\n buildMode,\n sharedDependencies,\n sourceDirectory,\n willReplace,\n}: Required<\n Pick<\n ExtensionBundleConfigurationInput,\n 'bundleId' | 'bundleName' | 'recoveryCapsule' | 'sourceDirectory'\n >\n> & {\n extensionIds?: string[];\n willReplace: boolean;\n buildMode?: ExtensionBundleConfiguration['buildMode'];\n sharedDependencies?: Record<string, string>;\n}): Promise<ConfigurationContext> {\n validateBundleId(bundleId);\n validateBundleName(bundleName);\n assert(typeof recoveryCapsule === 'boolean', 'recoveryCapsule must be a boolean.');\n const source = await inspectConfigurationSource(sourceDirectory, willReplace);\n const extensionManifest = await readExtensionManifest(source);\n const existingBundles = validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensionManifest.extensions,\n );\n assert(\n !existingBundles.some((bundle) => bundle.id === bundleId),\n `Extension bundle already exists: ${bundleId}`,\n );\n const alreadyBundled = new Set(existingBundles.flatMap((bundle) => bundle.members));\n const members =\n extensionIds && extensionIds.length > 0\n ? [...extensionIds]\n : source.extensions\n .map((extension) => extension.id)\n .filter((extensionId) => !alreadyBundled.has(extensionId));\n const candidateManifest = structuredClone(extensionManifest);\n candidateManifest.extensionBundles = [\n ...existingBundles,\n {\n id: bundleId,\n members,\n name: bundleName,\n ...(buildMode === undefined ? {} : {buildMode}),\n ...(sharedDependencies === undefined ? {} : {sharedDependencies}),\n ...(recoveryCapsule === true ? {recoveryCapsule: true} : {}),\n },\n ];\n const extensionBundles = validateExtensionBundleConfigurations(\n candidateManifest.extensionBundles,\n candidateManifest.extensions,\n );\n const buildPlan = await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n const configuredBundle = buildPlan.bundlePlans.find((plan) => plan.bundle.id === bundleId);\n assert(configuredBundle, `Extension bundle plan was not produced: ${bundleId}`);\n return {buildPlan, candidateManifest, configuredBundle, extensionManifest, source};\n}\n\nexport async function planExtensionBundle({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule = false,\n sourceDirectory,\n buildMode,\n sharedDependencies,\n}: ExtensionBundleConfigurationInput): Promise<ExtensionBundlePlanResult> {\n const context = await configurationContext({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n buildMode,\n sharedDependencies,\n willReplace: false,\n });\n return {\n applied: false,\n bundleId,\n bundleName,\n changed: true,\n components: context.configuredBundle.components.map((component) => component.metadata),\n counts: context.configuredBundle.counts,\n members: [...context.configuredBundle.bundle.members],\n recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,\n sourceDirectory: context.source.resolvedSourceDirectory,\n ...(context.configuredBundle.moduleBuild\n ? {moduleBuild: context.configuredBundle.moduleBuild}\n : {}),\n };\n}\n\nasync function installManifestConfiguration(\n context: ConfigurationContext | UnbundleContext,\n operation: string,\n): Promise<{comparison: DirectoryComparison; rollbackCleanupWarning: string | null}> {\n const initialComparison = await compareDirectories(\n context.source.resolvedSourceDirectory,\n context.source.resolvedSourceDirectory,\n );\n assert(\n initialComparison.identical &&\n initialComparison.existingFingerprint === initialComparison.candidateFingerprint,\n `SB3 source changed while its initial ${operation} state was inspected.`,\n );\n const parentDirectory = path.dirname(context.source.resolvedSourceDirectory);\n const candidateDirectory = await mkdtemp(\n path.join(parentDirectory, `.${path.basename(context.source.resolvedSourceDirectory)}.bundle-`),\n );\n let installed = false;\n try {\n await cp(context.source.resolvedSourceDirectory, candidateDirectory, {\n preserveTimestamps: true,\n recursive: true,\n verbatimSymlinks: true,\n });\n await writeFile(\n path.join(candidateDirectory, context.source.sourceManifest.embeddedExtensions),\n `${JSON.stringify(context.candidateManifest, null, 2)}\\n`,\n );\n await createDeterministicSb3(candidateDirectory);\n const comparison = await compareDirectories(\n context.source.resolvedSourceDirectory,\n candidateDirectory,\n );\n assert(\n comparison.existingFingerprint === initialComparison.existingFingerprint,\n `SB3 source changed while the ${operation} candidate was prepared; refusing to replace it.`,\n );\n assert(!comparison.identical, `Extension bundle ${operation} produced no source changes.`);\n const latestComparison = await compareDirectories(\n context.source.resolvedSourceDirectory,\n candidateDirectory,\n );\n assert(\n latestComparison.existingFingerprint === comparison.existingFingerprint &&\n latestComparison.candidateFingerprint === comparison.candidateFingerprint,\n `SB3 source or ${operation} candidate changed during the operation; refusing to replace it.`,\n );\n const replacement = await replaceDirectoryTransactionally(\n candidateDirectory,\n context.source.resolvedSourceDirectory,\n );\n installed = true;\n return {comparison, ...replacement};\n } finally {\n if (!installed) await rm(candidateDirectory, {recursive: true, force: true});\n }\n}\n\nexport async function bundleExtensions({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule = false,\n sourceDirectory,\n yes = false,\n buildMode,\n sharedDependencies,\n}: ExtensionBundleConfigurationInput): Promise<ExtensionBundleApplyResult> {\n const context = await configurationContext({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n buildMode,\n sharedDependencies,\n willReplace: yes,\n });\n const plan = {\n bundleId,\n bundleName,\n components: context.configuredBundle.components.map((component) => component.metadata),\n counts: context.configuredBundle.counts,\n members: [...context.configuredBundle.bundle.members],\n recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,\n sourceDirectory: context.source.resolvedSourceDirectory,\n ...(context.configuredBundle.moduleBuild\n ? {moduleBuild: context.configuredBundle.moduleBuild}\n : {}),\n };\n if (!yes) {\n return {applied: false, changed: true, ...plan, rollbackCleanupWarning: null};\n }\n const installation = await installManifestConfiguration(context, 'configuration');\n return {applied: true, changed: true, ...installation, ...plan};\n}\n\nasync function unbundleContext({\n bundleId,\n sourceDirectory,\n willReplace,\n}: {\n bundleId: string;\n sourceDirectory: string;\n willReplace: boolean;\n}): Promise<UnbundleContext> {\n validateBundleId(bundleId);\n const source = await inspectConfigurationSource(sourceDirectory, willReplace);\n const extensionManifest = await readExtensionManifest(source);\n const extensionBundles = validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensionManifest.extensions,\n );\n const removedBundle = extensionBundles.find((bundle) => bundle.id === bundleId);\n assert(removedBundle, `Extension bundle was not found: ${bundleId}`);\n const candidateManifest = structuredClone(extensionManifest);\n const remainingBundles = extensionBundles.filter((bundle) => bundle.id !== bundleId);\n if (remainingBundles.length === 0) {\n delete candidateManifest.extensionBundles;\n } else {\n candidateManifest.extensionBundles = remainingBundles;\n }\n return {candidateManifest, extensionManifest, removedBundle, source};\n}\n\nexport async function planExtensionUnbundle({\n bundleId,\n sourceDirectory,\n}: {\n bundleId: string;\n sourceDirectory: string;\n}): Promise<ExtensionUnbundlePlanResult> {\n const context = await unbundleContext({bundleId, sourceDirectory, willReplace: false});\n return {\n applied: false,\n bundleId,\n changed: true,\n members: [...context.removedBundle.members],\n sourceDirectory: context.source.resolvedSourceDirectory,\n };\n}\n\nexport async function unbundleExtensions({\n bundleId,\n sourceDirectory,\n yes = false,\n}: {\n bundleId: string;\n sourceDirectory: string;\n yes?: boolean;\n}): Promise<ExtensionUnbundleApplyResult> {\n const context = await unbundleContext({bundleId, sourceDirectory, willReplace: yes});\n const plan = {\n bundleId,\n members: [...context.removedBundle.members],\n sourceDirectory: context.source.resolvedSourceDirectory,\n };\n if (!yes) {\n return {applied: false, changed: true, ...plan, rollbackCleanupWarning: null};\n }\n const installation = await installManifestConfiguration(context, 'removal');\n return {applied: true, changed: true, ...installation, ...plan};\n}\n"],"mappings":";;;;;;;;AA0FA,eAAe,2BACb,iBACA,aAC6B;CAC7B,MAAM,0BAA0B,KAAK,QAAQ,eAAe;CAC5D,IAAI,aAAa;EACf,OACE,4BAA4B,KAAK,MAAM,uBAAuB,CAAC,CAAC,MAChE,4EACF;EACA,OACE,CAAE,MAAM,WAAW,KAAK,KAAK,yBAAyB,MAAM,CAAC,GAC7D,gFACF;CACF;CACA,MAAM,QAAQ,MAAM,MAAM,uBAAuB;CACjD,OACE,MAAM,YAAY,KAAK,CAAC,MAAM,eAAe,GAC7C,gEAAgE,yBAClE;CACA,IAAI,aAAa,MAAM,4BAA4B,uBAAuB;CAC1E,OAAO,iCAAiC,uBAAuB;AACjE;AAEA,eAAe,sBACb,QACoC;CACpC,MAAM,eAAe,KAAK,KACxB,OAAO,yBACP,OAAO,eAAe,kBACxB;CACA,OAAO,KAAK,MAAM,MAAM,SAAS,cAAc,MAAM,CAAC;AACxD;AAEA,eAAe,qBAAqB,EAClC,UACA,YACA,cACA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,MAAM,sBAAsB,MAAM;CAC5D,MAAM,mBAAmB,sCACvB,kBAAkB,kBAClB,kBAAkB,UACpB;CACA,MAAM,gBAAgB,iBAAiB,MAAM,WAAW,OAAO,OAAO,QAAQ;CAC9E,OAAO,eAAe,mCAAmC,UAAU;CACnE,MAAM,oBAAoB,gBAAgB,iBAAiB;CAC3D,MAAM,mBAAmB,iBAAiB,QAAQ,WAAW,OAAO,OAAO,QAAQ;CACnF,IAAI,iBAAiB,WAAW,GAC9B,OAAO,kBAAkB;MAEzB,kBAAkB,mBAAmB;CAEvC,OAAO;EAAC;EAAmB;EAAmB;EAAe;CAAM;AACrE;AAEA,eAAsB,sBAAsB,EAC1C,UACA,mBAIuC;CACvC,MAAM,UAAU,MAAM,gBAAgB;EAAC;EAAU;EAAiB,aAAa;CAAK,CAAC;CACrF,OAAO;EACL,SAAS;EACT;EACA,SAAS;EACT,SAAS,CAAC,GAAG,QAAQ,cAAc,OAAO;EAC1C,iBAAiB,QAAQ,OAAO;CAClC;AACF;AAEA,eAAsB,mBAAmB,EACvC,UACA,iBACA,MAAM,SAKkC;CACxC,MAAM,UAAU,MAAM,gBAAgB;EAAC;EAAU;EAAiB,aAAa;CAAG,CAAC;CACnF,MAAM,OAAO;EACX;EACA,SAAS,CAAC,GAAG,QAAQ,cAAc,OAAO;EAC1C,iBAAiB,QAAQ,OAAO;CAClC;CACA,IAAI,CAAC,KACH,OAAO;EAAC,SAAS;EAAO,SAAS;EAAM,GAAG;EAAM,wBAAwB;CAAI;CAG9E,OAAO;EAAC,SAAS;EAAM,SAAS;EAAM,GAAG,MADd,6BAA6B,SAAS,SAAS;EACnB,GAAG;CAAI;AAChE"}
|
|
1
|
+
{"version":3,"file":"extension-bundle-configuration.js","names":[],"sources":["../src/extension-bundle-configuration.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {cp, lstat, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert} from './assert';\nimport {\n validateBundleId,\n validateBundleName,\n validateExtensionBundleConfigurations,\n} from './extension-bundle';\nimport {buildExtensionBundlesWithModules} from './extension-module-bundle';\nimport {validateExtensionBundleMetadata} from './extension-bundle-metadata';\nimport type {ExtensionModuleBuildReport} from './extension-module-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n assertNoInterruptedRollback,\n compareDirectories,\n pathExists,\n replaceDirectoryTransactionally,\n} from './output-safety';\nimport type {DirectoryComparison} from './output-safety';\nimport {createDeterministicSb3, inspectSb3SourceForExtensionSync} from './source';\nimport type {InspectedSb3Source} from './source';\nimport type {EmbeddedExtensionManifest, ExtensionBundleConfiguration} from './types';\n\ninterface ExtensionBundleComponentMetadata {\n author: string | null;\n description: string | null;\n id: string | null;\n license: string | null;\n name: string | null;\n}\n\ninterface ConfigurationContext {\n buildPlan: Awaited<ReturnType<typeof buildExtensionBundlesWithModules>>;\n candidateManifest: EmbeddedExtensionManifest;\n configuredBundle: ExtensionBundlePlan;\n extensionManifest: EmbeddedExtensionManifest;\n source: InspectedSb3Source;\n}\n\ninterface UnbundleContext {\n candidateManifest: EmbeddedExtensionManifest;\n extensionManifest: EmbeddedExtensionManifest;\n removedBundle: ExtensionBundleConfiguration;\n source: InspectedSb3Source;\n}\n\nexport interface ExtensionBundleConfigurationInput {\n bundleId: string;\n bundleName: string;\n metadata?: ExtensionBundleConfiguration['metadata'];\n extensionIds?: string[];\n recoveryCapsule?: boolean;\n sourceDirectory: string;\n yes?: boolean;\n buildMode?: ExtensionBundleConfiguration['buildMode'];\n sharedDependencies?: Record<string, string>;\n}\n\nexport interface ExtensionBundlePlanResult {\n applied: boolean;\n bundleId: string;\n bundleName: string;\n metadata?: ExtensionBundleConfiguration['metadata'];\n changed: boolean;\n components: ExtensionBundleComponentMetadata[];\n counts: ExtensionBundlePlan['counts'];\n members: string[];\n recoveryCapsule: boolean;\n sourceDirectory: string;\n moduleBuild?: ExtensionModuleBuildReport;\n}\n\nexport interface ExtensionBundleApplyResult extends ExtensionBundlePlanResult {\n comparison?: DirectoryComparison;\n rollbackCleanupWarning: string | null;\n}\n\nexport interface ExtensionUnbundlePlanResult {\n applied: boolean;\n bundleId: string;\n changed: boolean;\n members: string[];\n sourceDirectory: string;\n}\n\nexport interface ExtensionUnbundleApplyResult extends ExtensionUnbundlePlanResult {\n comparison?: DirectoryComparison;\n rollbackCleanupWarning: string | null;\n}\n\nasync function inspectConfigurationSource(\n sourceDirectory: string,\n willReplace: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n if (willReplace) {\n assert(\n resolvedSourceDirectory !== path.parse(resolvedSourceDirectory).root,\n 'Refusing to replace a filesystem root while configuring extension bundles.',\n );\n assert(\n !(await pathExists(path.join(resolvedSourceDirectory, '.git'))),\n 'Refusing to replace a Git repository root while configuring extension bundles.',\n );\n }\n const stats = await lstat(resolvedSourceDirectory);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `SB3 source must be a directory, not a file or symbolic link: ${resolvedSourceDirectory}`,\n );\n if (willReplace) await assertNoInterruptedRollback(resolvedSourceDirectory);\n return inspectSb3SourceForExtensionSync(resolvedSourceDirectory);\n}\n\nasync function readExtensionManifest(\n source: InspectedSb3Source,\n): Promise<EmbeddedExtensionManifest> {\n const manifestPath = path.join(\n source.resolvedSourceDirectory,\n source.sourceManifest.embeddedExtensions,\n );\n return JSON.parse(await readFile(manifestPath, 'utf8')) as EmbeddedExtensionManifest;\n}\n\nasync function configurationContext({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule,\n buildMode,\n sharedDependencies,\n metadata,\n sourceDirectory,\n willReplace,\n}: Required<\n Pick<\n ExtensionBundleConfigurationInput,\n 'bundleId' | 'bundleName' | 'recoveryCapsule' | 'sourceDirectory'\n >\n> & {\n extensionIds?: string[];\n willReplace: boolean;\n buildMode?: ExtensionBundleConfiguration['buildMode'];\n sharedDependencies?: Record<string, string>;\n metadata?: ExtensionBundleConfiguration['metadata'];\n}): Promise<ConfigurationContext> {\n validateBundleId(bundleId);\n validateBundleName(bundleName);\n assert(typeof recoveryCapsule === 'boolean', 'recoveryCapsule must be a boolean.');\n const source = await inspectConfigurationSource(sourceDirectory, willReplace);\n const extensionManifest = await readExtensionManifest(source);\n const existingBundles = validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensionManifest.extensions,\n );\n assert(\n !existingBundles.some((bundle) => bundle.id === bundleId),\n `Extension bundle already exists: ${bundleId}`,\n );\n const alreadyBundled = new Set(existingBundles.flatMap((bundle) => bundle.members));\n const members =\n extensionIds && extensionIds.length > 0\n ? [...extensionIds]\n : source.extensions\n .map((extension) => extension.id)\n .filter((extensionId) => !alreadyBundled.has(extensionId));\n const candidateManifest = structuredClone(extensionManifest);\n candidateManifest.extensionBundles = [\n ...existingBundles,\n {\n id: bundleId,\n members,\n name: bundleName,\n ...(metadata === undefined ? {} : {metadata: validateExtensionBundleMetadata(metadata)}),\n ...(buildMode === undefined ? {} : {buildMode}),\n ...(sharedDependencies === undefined ? {} : {sharedDependencies}),\n ...(recoveryCapsule === true ? {recoveryCapsule: true} : {}),\n },\n ];\n const extensionBundles = validateExtensionBundleConfigurations(\n candidateManifest.extensionBundles,\n candidateManifest.extensions,\n );\n const buildPlan = await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n const configuredBundle = buildPlan.bundlePlans.find((plan) => plan.bundle.id === bundleId);\n assert(configuredBundle, `Extension bundle plan was not produced: ${bundleId}`);\n return {buildPlan, candidateManifest, configuredBundle, extensionManifest, source};\n}\n\nexport async function planExtensionBundle({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule = false,\n sourceDirectory,\n buildMode,\n sharedDependencies,\n metadata,\n}: ExtensionBundleConfigurationInput): Promise<ExtensionBundlePlanResult> {\n const context = await configurationContext({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n buildMode,\n sharedDependencies,\n metadata,\n willReplace: false,\n });\n return {\n applied: false,\n bundleId,\n bundleName,\n ...(context.configuredBundle.bundle.metadata === undefined\n ? {}\n : {metadata: structuredClone(context.configuredBundle.bundle.metadata)}),\n changed: true,\n components: context.configuredBundle.components.map((component) => component.metadata),\n counts: context.configuredBundle.counts,\n members: [...context.configuredBundle.bundle.members],\n recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,\n sourceDirectory: context.source.resolvedSourceDirectory,\n ...(context.configuredBundle.moduleBuild\n ? {moduleBuild: context.configuredBundle.moduleBuild}\n : {}),\n };\n}\n\nasync function installManifestConfiguration(\n context: ConfigurationContext | UnbundleContext,\n operation: string,\n): Promise<{comparison: DirectoryComparison; rollbackCleanupWarning: string | null}> {\n const initialComparison = await compareDirectories(\n context.source.resolvedSourceDirectory,\n context.source.resolvedSourceDirectory,\n );\n assert(\n initialComparison.identical &&\n initialComparison.existingFingerprint === initialComparison.candidateFingerprint,\n `SB3 source changed while its initial ${operation} state was inspected.`,\n );\n const parentDirectory = path.dirname(context.source.resolvedSourceDirectory);\n const candidateDirectory = await mkdtemp(\n path.join(parentDirectory, `.${path.basename(context.source.resolvedSourceDirectory)}.bundle-`),\n );\n let installed = false;\n try {\n await cp(context.source.resolvedSourceDirectory, candidateDirectory, {\n preserveTimestamps: true,\n recursive: true,\n verbatimSymlinks: true,\n });\n await writeFile(\n path.join(candidateDirectory, context.source.sourceManifest.embeddedExtensions),\n `${JSON.stringify(context.candidateManifest, null, 2)}\\n`,\n );\n await createDeterministicSb3(candidateDirectory);\n const comparison = await compareDirectories(\n context.source.resolvedSourceDirectory,\n candidateDirectory,\n );\n assert(\n comparison.existingFingerprint === initialComparison.existingFingerprint,\n `SB3 source changed while the ${operation} candidate was prepared; refusing to replace it.`,\n );\n assert(!comparison.identical, `Extension bundle ${operation} produced no source changes.`);\n const latestComparison = await compareDirectories(\n context.source.resolvedSourceDirectory,\n candidateDirectory,\n );\n assert(\n latestComparison.existingFingerprint === comparison.existingFingerprint &&\n latestComparison.candidateFingerprint === comparison.candidateFingerprint,\n `SB3 source or ${operation} candidate changed during the operation; refusing to replace it.`,\n );\n const replacement = await replaceDirectoryTransactionally(\n candidateDirectory,\n context.source.resolvedSourceDirectory,\n );\n installed = true;\n return {comparison, ...replacement};\n } finally {\n if (!installed) await rm(candidateDirectory, {recursive: true, force: true});\n }\n}\n\nexport async function bundleExtensions({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule = false,\n sourceDirectory,\n yes = false,\n buildMode,\n sharedDependencies,\n metadata,\n}: ExtensionBundleConfigurationInput): Promise<ExtensionBundleApplyResult> {\n const context = await configurationContext({\n bundleId,\n bundleName,\n extensionIds,\n recoveryCapsule,\n sourceDirectory,\n buildMode,\n sharedDependencies,\n metadata,\n willReplace: yes,\n });\n const plan = {\n bundleId,\n bundleName,\n ...(context.configuredBundle.bundle.metadata === undefined\n ? {}\n : {metadata: structuredClone(context.configuredBundle.bundle.metadata)}),\n components: context.configuredBundle.components.map((component) => component.metadata),\n counts: context.configuredBundle.counts,\n members: [...context.configuredBundle.bundle.members],\n recoveryCapsule: context.configuredBundle.bundle.recoveryCapsule === true,\n sourceDirectory: context.source.resolvedSourceDirectory,\n ...(context.configuredBundle.moduleBuild\n ? {moduleBuild: context.configuredBundle.moduleBuild}\n : {}),\n };\n if (!yes) {\n return {applied: false, changed: true, ...plan, rollbackCleanupWarning: null};\n }\n const installation = await installManifestConfiguration(context, 'configuration');\n return {applied: true, changed: true, ...installation, ...plan};\n}\n\nasync function unbundleContext({\n bundleId,\n sourceDirectory,\n willReplace,\n}: {\n bundleId: string;\n sourceDirectory: string;\n willReplace: boolean;\n}): Promise<UnbundleContext> {\n validateBundleId(bundleId);\n const source = await inspectConfigurationSource(sourceDirectory, willReplace);\n const extensionManifest = await readExtensionManifest(source);\n const extensionBundles = validateExtensionBundleConfigurations(\n extensionManifest.extensionBundles,\n extensionManifest.extensions,\n );\n const removedBundle = extensionBundles.find((bundle) => bundle.id === bundleId);\n assert(removedBundle, `Extension bundle was not found: ${bundleId}`);\n const candidateManifest = structuredClone(extensionManifest);\n const remainingBundles = extensionBundles.filter((bundle) => bundle.id !== bundleId);\n if (remainingBundles.length === 0) {\n delete candidateManifest.extensionBundles;\n } else {\n candidateManifest.extensionBundles = remainingBundles;\n }\n return {candidateManifest, extensionManifest, removedBundle, source};\n}\n\nexport async function planExtensionUnbundle({\n bundleId,\n sourceDirectory,\n}: {\n bundleId: string;\n sourceDirectory: string;\n}): Promise<ExtensionUnbundlePlanResult> {\n const context = await unbundleContext({bundleId, sourceDirectory, willReplace: false});\n return {\n applied: false,\n bundleId,\n changed: true,\n members: [...context.removedBundle.members],\n sourceDirectory: context.source.resolvedSourceDirectory,\n };\n}\n\nexport async function unbundleExtensions({\n bundleId,\n sourceDirectory,\n yes = false,\n}: {\n bundleId: string;\n sourceDirectory: string;\n yes?: boolean;\n}): Promise<ExtensionUnbundleApplyResult> {\n const context = await unbundleContext({bundleId, sourceDirectory, willReplace: yes});\n const plan = {\n bundleId,\n members: [...context.removedBundle.members],\n sourceDirectory: context.source.resolvedSourceDirectory,\n };\n if (!yes) {\n return {applied: false, changed: true, ...plan, rollbackCleanupWarning: null};\n }\n const installation = await installManifestConfiguration(context, 'removal');\n return {applied: true, changed: true, ...installation, ...plan};\n}\n"],"mappings":";;;;;;;;;AA6FA,eAAe,2BACb,iBACA,aAC6B;CAC7B,MAAM,0BAA0B,KAAK,QAAQ,eAAe;CAC5D,IAAI,aAAa;EACf,OACE,4BAA4B,KAAK,MAAM,uBAAuB,CAAC,CAAC,MAChE,4EACF;EACA,OACE,CAAE,MAAM,WAAW,KAAK,KAAK,yBAAyB,MAAM,CAAC,GAC7D,gFACF;CACF;CACA,MAAM,QAAQ,MAAM,MAAM,uBAAuB;CACjD,OACE,MAAM,YAAY,KAAK,CAAC,MAAM,eAAe,GAC7C,gEAAgE,yBAClE;CACA,IAAI,aAAa,MAAM,4BAA4B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ACA,MAAM,SAKkC;CACxC,MAAM,UAAU,MAAM,gBAAgB;EAAC;EAAU;EAAiB,aAAa;CAAG,CAAC;CACnF,MAAM,OAAO;EACX;EACA,SAAS,CAAC,GAAG,QAAQ,cAAc,OAAO;EAC1C,iBAAiB,QAAQ,OAAO;CAClC;CACA,IAAI,CAAC,KACH,OAAO;EAAC,SAAS;EAAO,SAAS;EAAM,GAAG;EAAM,wBAAwB;CAAI;CAG9E,OAAO;EAAC,SAAS;EAAM,SAAS;EAAM,GAAG,MADd,6BAA6B,SAAS,SAAS;EACnB,GAAG;CAAI;AAChE"}
|
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
import { assert } from "./assert.js";
|
|
2
|
+
//#region src/extension-bundle-metadata.ts
|
|
3
|
+
var textFields = [
|
|
4
|
+
"description",
|
|
5
|
+
"author",
|
|
6
|
+
"authorURL",
|
|
7
|
+
"version",
|
|
8
|
+
"updatedAt",
|
|
9
|
+
"repository",
|
|
10
|
+
"docsURL",
|
|
11
|
+
"banner",
|
|
12
|
+
"package"
|
|
13
|
+
];
|
|
14
|
+
function singleLine(value, field) {
|
|
15
|
+
assert(typeof value === "string" && value.length > 0 && value.length <= 1e3 && value === value.trim() && !/[\u0000-\u001f\u007f\u2028\u2029]/u.test(value), `Bundle metadata ${field} must be a non-empty single line of at most 1000 characters.`);
|
|
16
|
+
return value;
|
|
17
|
+
}
|
|
18
|
+
function externalUrl(value, field, protocols = ["https:"]) {
|
|
19
|
+
let url;
|
|
20
|
+
try {
|
|
21
|
+
url = new URL(value);
|
|
22
|
+
} catch {
|
|
23
|
+
throw new Error(`Bundle metadata ${field} must be an absolute URL.`);
|
|
24
|
+
}
|
|
25
|
+
assert(protocols.includes(url.protocol) && url.hostname && !url.username && !url.password, `Bundle metadata ${field} must use ${protocols.join(" or ")} without credentials.`);
|
|
26
|
+
return value;
|
|
27
|
+
}
|
|
28
|
+
function bannerUrl(value) {
|
|
29
|
+
if (!/^data:/iu.test(value)) return externalUrl(value, "banner");
|
|
30
|
+
const match = /^data:image\/(?:png|jpeg|gif|webp|svg\+xml)(?:;charset=utf-8)?(;base64)?,(.+)$/iu.exec(value);
|
|
31
|
+
assert(match && !/%(?![\da-f]{2})/iu.test(match[2]), "Invalid bundle metadata banner image data URL.");
|
|
32
|
+
if (match[1]) {
|
|
33
|
+
let payload;
|
|
34
|
+
try {
|
|
35
|
+
payload = decodeURIComponent(match[2]);
|
|
36
|
+
} catch {
|
|
37
|
+
throw new Error("Invalid bundle metadata banner base64 data URL.");
|
|
38
|
+
}
|
|
39
|
+
assert(/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(payload) && Buffer.from(payload, "base64").length > 0, "Invalid bundle metadata banner base64 data URL.");
|
|
40
|
+
}
|
|
41
|
+
const comma = value.indexOf(",");
|
|
42
|
+
return value.slice(0, comma).toLowerCase() + value.slice(comma);
|
|
43
|
+
}
|
|
44
|
+
/** No owner, package, link, license, or permission is inferred from the first bundle member. */
|
|
45
|
+
function validateExtensionBundleMetadata(value) {
|
|
46
|
+
assert(value && typeof value === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(value)), "Bundle metadata must be an object.");
|
|
47
|
+
const record = value;
|
|
48
|
+
const metadata = {};
|
|
49
|
+
for (const key of Object.keys(record)) assert(key === "descriptions" || textFields.includes(key), `Unknown bundle metadata field: ${key}`);
|
|
50
|
+
for (const field of textFields) {
|
|
51
|
+
if (record[field] === void 0) continue;
|
|
52
|
+
let text = singleLine(record[field], field);
|
|
53
|
+
if (field === "authorURL") text = externalUrl(text, field, ["https:", "http:"]);
|
|
54
|
+
if (field === "repository" || field === "docsURL") text = externalUrl(text, field);
|
|
55
|
+
if (field === "banner") text = bannerUrl(text);
|
|
56
|
+
if (field === "package") assert(text.length <= 214 && /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/u.test(text) && !["node_modules", "favicon.ico"].includes(text), "Invalid bundle metadata npm package name.");
|
|
57
|
+
metadata[field] = text;
|
|
58
|
+
}
|
|
59
|
+
assert(!metadata.authorURL || metadata.author, "Bundle metadata authorURL requires an explicit author.");
|
|
60
|
+
if (record.descriptions !== void 0) {
|
|
61
|
+
assert(record.descriptions && typeof record.descriptions === "object" && [Object.prototype, null].includes(Object.getPrototypeOf(record.descriptions)), "Bundle metadata descriptions must be an object.");
|
|
62
|
+
metadata.descriptions = {};
|
|
63
|
+
for (const [locale, text] of Object.entries(record.descriptions).sort(([a], [b]) => a.localeCompare(b, "en"))) {
|
|
64
|
+
assert(/^[a-z]{2,8}(?:-[a-z0-9]{1,8})*$/u.test(locale), `Invalid bundle metadata locale: ${locale}`);
|
|
65
|
+
metadata.descriptions[locale] = singleLine(text, `descriptions.${locale}`);
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
return metadata;
|
|
69
|
+
}
|
|
70
|
+
//#endregion
|
|
71
|
+
export { validateExtensionBundleMetadata };
|
|
72
|
+
|
|
73
|
+
//# sourceMappingURL=extension-bundle-metadata.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"extension-bundle-metadata.js","names":[],"sources":["../src/extension-bundle-metadata.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {assert} from './assert';\nimport type {ExtensionBundleMetadata} from './types';\n\nconst textFields = [\n 'description',\n 'author',\n 'authorURL',\n 'version',\n 'updatedAt',\n 'repository',\n 'docsURL',\n 'banner',\n 'package',\n] as const;\n\nfunction singleLine(value: unknown, field: string): string {\n assert(\n typeof value === 'string' &&\n value.length > 0 &&\n value.length <= 1000 &&\n value === value.trim() &&\n !/[\\u0000-\\u001f\\u007f\\u2028\\u2029]/u.test(value),\n `Bundle metadata ${field} must be a non-empty single line of at most 1000 characters.`,\n );\n return value;\n}\n\nfunction externalUrl(value: string, field: string, protocols = ['https:']): string {\n let url: URL;\n try {\n url = new URL(value);\n } catch {\n throw new Error(`Bundle metadata ${field} must be an absolute URL.`);\n }\n assert(\n protocols.includes(url.protocol) && url.hostname && !url.username && !url.password,\n `Bundle metadata ${field} must use ${protocols.join(' or ')} without credentials.`,\n );\n return value;\n}\n\nfunction bannerUrl(value: string): string {\n if (!/^data:/iu.test(value)) return externalUrl(value, 'banner');\n const match =\n /^data:image\\/(?:png|jpeg|gif|webp|svg\\+xml)(?:;charset=utf-8)?(;base64)?,(.+)$/iu.exec(value);\n assert(\n match && !/%(?![\\da-f]{2})/iu.test(match[2]),\n 'Invalid bundle metadata banner image data URL.',\n );\n if (match[1]) {\n let payload: string;\n try {\n payload = decodeURIComponent(match[2]);\n } catch {\n throw new Error('Invalid bundle metadata banner base64 data URL.');\n }\n assert(\n /^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/u.test(payload) &&\n Buffer.from(payload, 'base64').length > 0,\n 'Invalid bundle metadata banner base64 data URL.',\n );\n }\n const comma = value.indexOf(',');\n return value.slice(0, comma).toLowerCase() + value.slice(comma);\n}\n\n/** No owner, package, link, license, or permission is inferred from the first bundle member. */\nexport function validateExtensionBundleMetadata(value: unknown): ExtensionBundleMetadata {\n assert(\n value &&\n typeof value === 'object' &&\n [Object.prototype, null].includes(Object.getPrototypeOf(value)),\n 'Bundle metadata must be an object.',\n );\n const record = value as Record<string, unknown>;\n const metadata: ExtensionBundleMetadata = {};\n for (const key of Object.keys(record)) {\n assert(\n key === 'descriptions' || (textFields as readonly string[]).includes(key),\n `Unknown bundle metadata field: ${key}`,\n );\n }\n for (const field of textFields) {\n if (record[field] === undefined) continue;\n let text = singleLine(record[field], field);\n if (field === 'authorURL') text = externalUrl(text, field, ['https:', 'http:']);\n if (field === 'repository' || field === 'docsURL') text = externalUrl(text, field);\n if (field === 'banner') text = bannerUrl(text);\n if (field === 'package') {\n assert(\n text.length <= 214 &&\n /^(?:@[a-z0-9][a-z0-9._-]*\\/)?[a-z0-9][a-z0-9._-]*$/u.test(text) &&\n !['node_modules', 'favicon.ico'].includes(text),\n 'Invalid bundle metadata npm package name.',\n );\n }\n metadata[field] = text;\n }\n assert(\n !metadata.authorURL || metadata.author,\n 'Bundle metadata authorURL requires an explicit author.',\n );\n if (record.descriptions !== undefined) {\n assert(\n record.descriptions &&\n typeof record.descriptions === 'object' &&\n [Object.prototype, null].includes(Object.getPrototypeOf(record.descriptions)),\n 'Bundle metadata descriptions must be an object.',\n );\n metadata.descriptions = {};\n for (const [locale, text] of Object.entries(record.descriptions).sort(([a], [b]) =>\n a.localeCompare(b, 'en'),\n )) {\n assert(\n /^[a-z]{2,8}(?:-[a-z0-9]{1,8})*$/u.test(locale),\n `Invalid bundle metadata locale: ${locale}`,\n );\n metadata.descriptions[locale] = singleLine(text, `descriptions.${locale}`);\n }\n }\n return metadata;\n}\n"],"mappings":";;AAKA,IAAM,aAAa;CACjB;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF;AAEA,SAAS,WAAW,OAAgB,OAAuB;CACzD,OACE,OAAO,UAAU,YACf,MAAM,SAAS,KACf,MAAM,UAAU,OAChB,UAAU,MAAM,KAAK,KACrB,CAAC,qCAAqC,KAAK,KAAK,GAClD,mBAAmB,MAAM,6DAC3B;CACA,OAAO;AACT;AAEA,SAAS,YAAY,OAAe,OAAe,YAAY,CAAC,QAAQ,GAAW;CACjF,IAAI;CACJ,IAAI;EACF,MAAM,IAAI,IAAI,KAAK;CACrB,QAAQ;EACN,MAAM,IAAI,MAAM,mBAAmB,MAAM,0BAA0B;CACrE;CACA,OACE,UAAU,SAAS,IAAI,QAAQ,KAAK,IAAI,YAAY,CAAC,IAAI,YAAY,CAAC,IAAI,UAC1E,mBAAmB,MAAM,YAAY,UAAU,KAAK,MAAM,EAAE,sBAC9D;CACA,OAAO;AACT;AAEA,SAAS,UAAU,OAAuB;CACxC,IAAI,CAAC,WAAW,KAAK,KAAK,GAAG,OAAO,YAAY,OAAO,QAAQ;CAC/D,MAAM,QACJ,mFAAmF,KAAK,KAAK;CAC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AAW;EACrC,OACE,OAAO,gBACL,OAAO,OAAO,iBAAiB,YAC/B,CAAC,OAAO,WAAW,IAAI,CAAC,CAAC,SAAS,OAAO,eAAe,OAAO,YAAY,CAAC,GAC9E,iDACF;EACA,SAAS,eAAe,CAAC;EACzB,KAAK,MAAM,CAAC,QAAQ,SAAS,OAAO,QAAQ,OAAO,YAAY,CAAC,CAAC,MAAM,CAAC,IAAI,CAAC,OAC3E,EAAE,cAAc,GAAG,IAAI,CACzB,GAAG;GACD,OACE,mCAAmC,KAAK,MAAM,GAC9C,mCAAmC,QACrC;GACA,SAAS,aAAa,UAAU,WAAW,MAAM,gBAAgB,QAAQ;EAC3E;CACF;CACA,OAAO;AACT"}
|
package/dist/extension-bundle.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { assert } from "./assert.js";
|
|
2
2
|
import { extensionHeaderMetadata, unsandboxedRequirement } from "./extension-dependencies.js";
|
|
3
|
+
import { validateExtensionBundleMetadata } from "./extension-bundle-metadata.js";
|
|
3
4
|
//#region src/extension-bundle.ts
|
|
4
5
|
var extensionBundleRecoveryMarker = "SB3-Toolchain-Reversible-Bundle-v1";
|
|
5
6
|
function isObject(value) {
|
|
@@ -92,6 +93,7 @@ function validateExtensionBundleConfigurations(extensionBundles, extensions) {
|
|
|
92
93
|
id,
|
|
93
94
|
members,
|
|
94
95
|
name,
|
|
96
|
+
...bundle.metadata === void 0 ? {} : { metadata: validateExtensionBundleMetadata(bundle.metadata) },
|
|
95
97
|
...bundle.buildMode === void 0 ? {} : { buildMode: bundle.buildMode },
|
|
96
98
|
...bundle.sharedDependencies === void 0 ? {} : { sharedDependencies: { ...bundle.sharedDependencies } },
|
|
97
99
|
...capsuleFlag === void 0 ? {} : { recoveryCapsule: capsuleFlag },
|
|
@@ -134,15 +136,27 @@ function commentLine(value) {
|
|
|
134
136
|
}
|
|
135
137
|
function bundleHeader(bundle, components) {
|
|
136
138
|
const authors = [...new Set(components.map((component) => component.metadata.author))];
|
|
139
|
+
const metadata = bundle.metadata === void 0 ? void 0 : validateExtensionBundleMetadata(bundle.metadata);
|
|
137
140
|
const lines = [
|
|
138
141
|
`// Name: ${commentLine(bundle.name)}`,
|
|
139
142
|
`// ID: ${bundle.id}`,
|
|
140
|
-
`// Description: Static bundle of ${components.length} TurboWarp extensions
|
|
141
|
-
`// By: ${commentLine(authors.join(", "))}`,
|
|
142
|
-
"// License: See the bundled extension notices below."
|
|
143
|
+
`// Description: ${metadata?.description ?? `Static bundle of ${components.length} TurboWarp extensions.`}`
|
|
143
144
|
];
|
|
145
|
+
for (const [locale, description] of Object.entries(metadata?.descriptions ?? {})) lines.push(`// Description[${locale}]: ${description}`);
|
|
146
|
+
lines.push(`// By: ${metadata?.author ?? commentLine(authors.join(", "))}`);
|
|
147
|
+
for (const [field, label] of [
|
|
148
|
+
["authorURL", "Author URL"],
|
|
149
|
+
["version", "Version"],
|
|
150
|
+
["updatedAt", "Updated"],
|
|
151
|
+
["repository", "Repository"],
|
|
152
|
+
["docsURL", "Docs URL"],
|
|
153
|
+
["banner", "Banner"],
|
|
154
|
+
["package", "Package"]
|
|
155
|
+
]) if (metadata?.[field] !== void 0) lines.push(`// ${label}: ${metadata[field]}`);
|
|
156
|
+
lines.push("// License: See the bundled extension notices below.");
|
|
144
157
|
const requirement = bundleUnsandboxedRequirement(components);
|
|
145
158
|
if (requirement !== null) lines.push(`// Unsandboxed: ${requirement}`);
|
|
159
|
+
if (metadata) assert(lines.join("\n").length < 16384, "Bundle metadata exceeds the security header limit.");
|
|
146
160
|
lines.push("//", "// Bundled extensions:");
|
|
147
161
|
for (const component of components) {
|
|
148
162
|
lines.push(`// - Name: ${commentLine(component.metadata.name)}`, `// ID: ${component.metadata.id}`, `// By: ${commentLine(component.metadata.author)}`, `// Description: ${commentLine(component.metadata.description)}`, `// License: ${commentLine(component.metadata.license)}`);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"extension-bundle.js","names":[],"sources":["../src/extension-bundle.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {assert} from './assert';\nimport {extensionHeaderMetadata, unsandboxedRequirement} from './extension-dependencies';\nimport type {ExtensionHeaderMetadata, UnsandboxedRequirement} from './extension-dependencies';\nimport type {ExtensionModuleBuild, ExtensionModuleBuildReport} from './extension-module-bundle';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectJson,\n UnknownRecord,\n} from './types';\n\nexport const extensionBundleRecoveryMarker = 'SB3-Toolchain-Reversible-Bundle-v1';\n\nexport interface ExtensionBundleComponent {\n contents: string;\n extension: EmbeddedExtension;\n metadata: ExtensionHeaderMetadata;\n originalContents: Buffer;\n}\n\nexport interface ExtensionBundleCounts {\n extensionStorage: number;\n extensionUrls: number;\n opcodes: number;\n projectExtensions: number;\n}\n\nexport interface ExtensionBundlePlan {\n bundle: ExtensionBundleConfiguration;\n components: ExtensionBundleComponent[];\n contents: Buffer;\n counts: ExtensionBundleCounts;\n moduleBuild?: ExtensionModuleBuildReport;\n}\n\nexport interface BuildExtensionBundlesInput {\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n extensions: EmbeddedExtension[];\n project: ProjectJson;\n moduleBuilds?: ReadonlyMap<string, ExtensionModuleBuild>;\n}\n\nexport interface BuildExtensionBundlesResult {\n bundlePlans: ExtensionBundlePlan[];\n extensionContents: Map<string, Uint8Array>;\n extensions: EmbeddedExtension[];\n project: ProjectJson;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction validateBundleId(id: unknown, description = 'Extension bundle ID'): string {\n assert(\n typeof id === 'string' && /^[a-z0-9]+$/u.test(id),\n `${description} must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(id)}`,\n );\n return id;\n}\n\n/**\n * Shown in the palette when a bundle runs sandboxed although a member declared\n * `// Unsandboxed: required` (the members then do not run) or `optional` (they run with less).\n */\nexport const defaultSandboxedNotices: Readonly<\n Record<'required' | 'optional', Readonly<Record<string, string>>>\n> = Object.freeze({\n required: Object.freeze({\n en:\n 'This extension must run without the sandbox.\\n' +\n 'Load the project again and, in the extension\\n' +\n 'security dialog, check \"Run without sandbox\"\\n' +\n 'before allowing it.',\n ja:\n 'この拡張機能はサンドボックスなしで実行する必要があります。\\n' +\n 'プロジェクトを開き直し、拡張機能セキュリティの画面で\\n' +\n '「サンドボックスなしで実行する」にチェックを付けてから\\n' +\n '許可してください。',\n }),\n optional: Object.freeze({\n en:\n 'Running in the sandbox: some features are unavailable.\\n' +\n 'To use them, load the project again and check\\n' +\n '\"Run without sandbox\" in the extension security dialog.',\n ja:\n 'サンドボックス内で実行中のため、一部の機能が使えません。\\n' +\n '使うには、プロジェクトを開き直し、拡張機能セキュリティの画面で\\n' +\n '「サンドボックスなしで実行する」にチェックを付けてください。',\n }),\n});\n\n/**\n * Derives a bundle's requirement from its members' declarations: any `required` member makes the\n * bundle required; otherwise any `optional` member makes it optional; it is `not-needed` only when\n * every member says so. `null` means no member declares anything.\n */\nexport function bundleUnsandboxedRequirement(\n components: readonly Pick<ExtensionBundleComponent, 'metadata'>[],\n): UnsandboxedRequirement | null {\n const declared = components.map((component) => unsandboxedRequirement(component.metadata));\n if (declared.includes('required')) return 'required';\n if (declared.includes('optional')) return 'optional';\n if (declared.length > 0 && declared.every((requirement) => requirement === 'not-needed')) {\n return 'not-needed';\n }\n return null;\n}\n\nfunction validateSandboxedNotice(notice: unknown, bundleId: string): Record<string, string> {\n assert(\n isObject(notice) && Object.keys(notice).length > 0,\n `Extension bundle ${bundleId} sandboxedNotice must be a non-empty object of locale messages.`,\n );\n const validated: Record<string, string> = {};\n for (const [locale, message] of Object.entries(notice)) {\n assert(\n /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/u.test(locale),\n `Extension bundle ${bundleId} sandboxedNotice locale must be a lowercase language tag: ` +\n JSON.stringify(locale),\n );\n assert(\n typeof message === 'string' && message.trim().length > 0,\n `Extension bundle ${bundleId} sandboxedNotice.${locale} must be a non-empty string.`,\n );\n validated[locale] = message;\n }\n return validated;\n}\n\nfunction validateBundleName(name: unknown): string {\n assert(\n typeof name === 'string' && name.trim() === name && name.length > 0 && !/[\\r\\n]/u.test(name),\n `Extension bundle name must be a non-empty single line: ${JSON.stringify(name)}`,\n );\n return name;\n}\n\nexport function validateExtensionBundleConfigurations(\n extensionBundles: unknown,\n extensions: EmbeddedExtension[],\n): ExtensionBundleConfiguration[] {\n if (extensionBundles === undefined) return [];\n assert(\n Array.isArray(extensionBundles),\n 'embedded-extensions.json extensionBundles must be an array.',\n );\n\n const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));\n const bundleIds = new Set<string>();\n const bundledMemberIds = new Set<string>();\n\n return (extensionBundles as unknown[]).map((bundle, bundleIndex) => {\n assert(isObject(bundle), `Extension bundle ${bundleIndex} must be an object.`);\n const id = validateBundleId(bundle.id, `Extension bundle ${bundleIndex} ID`);\n const name = validateBundleName(bundle.name);\n assert(\n bundle.buildMode === undefined ||\n bundle.buildMode === 'classic' ||\n bundle.buildMode === 'module',\n `Invalid buildMode for extension bundle ${id}.`,\n );\n if (bundle.sharedDependencies !== undefined) {\n assert(bundle.buildMode === 'module', `sharedDependencies requires buildMode module: ${id}`);\n assert(isObject(bundle.sharedDependencies), `sharedDependencies must be an object: ${id}`);\n for (const [name, version] of Object.entries(bundle.sharedDependencies)) {\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 typeof version === 'string' && /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version),\n `Shared dependency ${name} requires an exact version.`,\n );\n }\n }\n assert(!extensionsById.has(id), `Extension bundle ID collides with an extension: ${id}`);\n assert(!bundleIds.has(id), `Duplicate extension bundle ID: ${id}`);\n bundleIds.add(id);\n assert(\n Array.isArray(bundle.members) && bundle.members.length >= 2,\n `Extension bundle ${id} must contain at least two members.`,\n );\n assert(\n bundle.recoveryCapsule === undefined || typeof bundle.recoveryCapsule === 'boolean',\n `Extension bundle ${id} recoveryCapsule must be a boolean when present.`,\n );\n assert(\n bundle.blockEditorRegistrations === undefined ||\n typeof bundle.blockEditorRegistrations === 'boolean',\n `Extension bundle ${id} blockEditorRegistrations must be a boolean when present.`,\n );\n const blockEditorRegistrations = bundle.blockEditorRegistrations;\n const capsuleFlag = bundle.recoveryCapsule;\n const sandboxedNotice =\n bundle.sandboxedNotice === undefined\n ? undefined\n : validateSandboxedNotice(bundle.sandboxedNotice, id);\n\n const localMemberIds = new Set<string>();\n const members: string[] = [];\n for (const rawMemberId of bundle.members as unknown[]) {\n const memberId = validateBundleId(rawMemberId, `Extension bundle ${id} member ID`);\n assert(\n extensionsById.has(memberId),\n `Extension bundle ${id} has unknown member: ${memberId}`,\n );\n assert(!localMemberIds.has(memberId), `Extension bundle ${id} repeats member: ${memberId}`);\n assert(\n !bundledMemberIds.has(memberId),\n `Embedded extension belongs to more than one bundle: ${memberId}`,\n );\n localMemberIds.add(memberId);\n bundledMemberIds.add(memberId);\n members.push(memberId);\n }\n return {\n id,\n members,\n name,\n ...(bundle.buildMode === undefined ? {} : {buildMode: bundle.buildMode}),\n ...(bundle.sharedDependencies === undefined\n ? {}\n : {sharedDependencies: {...bundle.sharedDependencies} as Record<string, string>}),\n ...(capsuleFlag === undefined ? {} : {recoveryCapsule: capsuleFlag}),\n ...(sandboxedNotice === undefined ? {} : {sandboxedNotice}),\n ...(blockEditorRegistrations === undefined ? {} : {blockEditorRegistrations}),\n };\n });\n}\n\nexport function readBundleComponents(\n bundle: ExtensionBundleConfiguration,\n extensionsById: Map<string, EmbeddedExtension>,\n extensionContents: Map<string, Uint8Array>,\n): ExtensionBundleComponent[] {\n return bundle.members.map((memberId) => {\n const extension = extensionsById.get(memberId);\n const contents = extensionContents.get(memberId);\n assert(contents, `Extension bundle ${bundle.id} has no contents for member: ${memberId}`);\n assert(\n extension,\n `Extension bundle ${bundle.id} has no manifest entry for member: ${memberId}`,\n );\n assert(\n extension.mediaType === 'text/javascript' || extension.mediaType === 'application/javascript',\n `Extension bundle ${bundle.id} member ${memberId} must be JavaScript, got ${extension.mediaType}.`,\n );\n const metadata = extensionHeaderMetadata(contents);\n assert(\n metadata.id === memberId,\n `Extension bundle ${bundle.id} member header ID mismatch: expected ${memberId}, ` +\n `got ${metadata.id ?? '(missing)'}`,\n );\n for (const [property, label] of [\n ['name', 'Name'],\n ['author', 'By'],\n ['description', 'Description'],\n ['license', 'License'],\n ] as const) {\n assert(\n metadata[property],\n `Extension bundle ${bundle.id} member ${memberId} requires a // ${label}: header.`,\n );\n }\n unsandboxedRequirement(metadata);\n const source = Buffer.from(contents).toString('utf8');\n assert(\n !source.startsWith('#!'),\n `Extension bundle ${bundle.id} member ${memberId} cannot use a shebang.`,\n );\n assert(\n !source.includes(extensionBundleRecoveryMarker),\n `Extension bundle ${bundle.id} member ${memberId} contains the reserved recovery marker.`,\n );\n const registrations = source.match(/\\bScratch\\s*\\.\\s*extensions\\s*\\.\\s*register\\s*\\(/gu) ?? [];\n assert(\n registrations.length === 1,\n `Extension bundle ${bundle.id} member ${memberId} must contain exactly one synchronous ` +\n `Scratch.extensions.register call; found ${registrations.length}.`,\n );\n return {contents: source, extension, metadata, originalContents: Buffer.from(contents)};\n });\n}\n\nfunction commentLine(value: unknown): string {\n return String(value).replaceAll('\\r', ' ').replaceAll('\\n', ' ');\n}\n\nfunction bundleHeader(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n): string {\n const authors = [...new Set(components.map((component) => component.metadata.author))];\n const lines = [\n `// Name: ${commentLine(bundle.name)}`,\n `// ID: ${bundle.id}`,\n `// Description: Static bundle of ${components.length} TurboWarp extensions.`,\n `// By: ${commentLine(authors.join(', '))}`,\n '// License: See the bundled extension notices below.',\n ];\n const requirement = bundleUnsandboxedRequirement(components);\n if (requirement !== null) lines.push(`// Unsandboxed: ${requirement}`);\n lines.push('//', '// Bundled extensions:');\n for (const component of components) {\n lines.push(\n `// - Name: ${commentLine(component.metadata.name)}`,\n `// ID: ${component.metadata.id}`,\n `// By: ${commentLine(component.metadata.author)}`,\n `// Description: ${commentLine(component.metadata.description)}`,\n `// License: ${commentLine(component.metadata.license)}`,\n );\n if (component.metadata.unsandboxed !== null) {\n lines.push(`// Unsandboxed: ${component.metadata.unsandboxed}`);\n }\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction componentLoadSource(component: ExtensionBundleComponent): string {\n const memberId = JSON.stringify(component.metadata.id);\n const source = component.contents.endsWith('\\n') ? component.contents : `${component.contents}\\n`;\n return `loadComponent(${memberId}, function (Scratch) {\\n${source}});\\n`;\n}\n\nfunction percentEncode(contents: Uint8Array | string): string {\n return [...Buffer.from(contents)]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction componentDataUrl(component: ExtensionBundleComponent): string {\n const metadata = [component.extension.mediaType, ...component.extension.parameters].join(';');\n const originalContents = component.originalContents ?? Buffer.from(component.contents);\n if (component.extension.encoding === 'base64') {\n return `data:${metadata};base64,${originalContents.toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(originalContents)}`;\n}\n\nfunction recoveryCapsule(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n originalProject: ProjectJson | undefined,\n): UnknownRecord {\n return {\n formatVersion: 1,\n bundle: {id: bundle.id, name: bundle.name},\n components: components.map((component) => ({\n dataUrl: componentDataUrl(component),\n id: component.metadata.id,\n })),\n originalExtensionIds: Array.isArray(originalProject?.extensions)\n ? [...(originalProject.extensions as unknown[])]\n : null,\n originalExtensionUrlIds: Object.keys(originalProject?.extensionURLs ?? {}),\n };\n}\n\nfunction sandboxedNotice(\n bundle: ExtensionBundleConfiguration,\n requirement: UnsandboxedRequirement | null,\n): Record<string, string> | null {\n if (requirement !== 'required' && requirement !== 'optional') {\n assert(\n bundle.sandboxedNotice === undefined,\n `Extension bundle ${bundle.id} sandboxedNotice needs a member that declares ` +\n '// Unsandboxed: required or optional.',\n );\n return null;\n }\n return {...defaultSandboxedNotices[requirement], ...bundle.sandboxedNotice};\n}\n\n/**\n * Detects a sandboxed load for a bundle whose members declared they need (`required`) or benefit\n * from (`optional`) TurboWarp's unsandboxed API. A required bundle registers a placeholder under\n * the bundle ID instead of running its members, so none can fail on a missing `Scratch.vm` and the\n * project still finishes loading: a sandboxed iframe that throws before registering leaves\n * TurboWarp waiting forever, and a worker reports only a generic failure. An optional bundle runs\n * its members and prefixes the palette with the notice. Bundles without a declaration get nothing.\n */\nfunction sandboxedGuardSource(\n requirement: UnsandboxedRequirement | null,\n notice: Record<string, string> | null,\n): string {\n if (notice === null) return '';\n const required = requirement === 'required';\n return `\n const SANDBOXED = !Scratch.extensions || Scratch.extensions.unsandboxed !== true;\n const SANDBOXED_NOTICE = ${JSON.stringify(notice)};\n const currentLocale = () => {\n try {\n if (Scratch.translate && typeof Scratch.translate.language === 'string') {\n return Scratch.translate.language;\n }\n } catch (_error) {\n // Fall through to the browser language.\n }\n return typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en';\n };\n const sandboxedNoticeText = () => {\n const locale = String(currentLocale()).toLowerCase();\n const language = locale.split('-')[0];\n if (Object.prototype.hasOwnProperty.call(SANDBOXED_NOTICE, locale)) return SANDBOXED_NOTICE[locale];\n if (Object.prototype.hasOwnProperty.call(SANDBOXED_NOTICE, language)) return SANDBOXED_NOTICE[language];\n return SANDBOXED_NOTICE.en;\n };\n const sandboxedNoticeBlocks = () => ['⚠ ' + BUNDLE_NAME, ...sandboxedNoticeText().split('\\\\n')]\n .filter((line) => line.length > 0)\n .map((line) => ({\n blockType: (Scratch.BlockType && Scratch.BlockType.LABEL) || 'label',\n sb3Toolchain: {kind: 'bundle-sandboxed-notice'},\n text: line,\n }));\n if (SANDBOXED && typeof console !== 'undefined') {\n const report = console.${required ? 'error' : 'warn'} || console.log;\n report.call(console, '[' + BUNDLE_ID + '] ' + BUNDLE_NAME + ' ${required ? 'requires' : 'works better with'} unsandboxed loading. ' + sandboxedNoticeText().replace(/\\\\n/gu, ' '));\n }\n${\n required\n ? ` if (SANDBOXED) {\n class SandboxedExtensionBundleNotice {\n getInfo() {\n return {\n id: BUNDLE_ID,\n name: BUNDLE_NAME,\n color1: '#D65C5C',\n color2: '#B64E4E',\n color3: '#964040',\n blocks: sandboxedNoticeBlocks(),\n menus: {},\n };\n }\n }\n Scratch.extensions.register(new SandboxedExtensionBundleNotice());\n return;\n }\n`\n : ''\n}`;\n}\n\n/** Editor callbacks and disposers stay owned by the GUI; only registration identities change. */\nfunction blockEditorBridgeSource(): string {\n return `\n const createComponentGui = (componentId) => {\n const baseGui = Scratch.gui;\n const api = baseGui && baseGui.blockEditors;\n if (!api || api.apiVersion !== 1) return baseGui;\n const registrations = new Set(['registerSchema', 'registerSchemaBundle', 'registerSourceEditor', 'registerFixedInputEditor']);\n const editors = new Proxy({}, {\n get(_target, property) {\n const value = Reflect.get(api, property, api);\n if (typeof value !== 'function') return value;\n if (!registrations.has(property)) return value.bind(api);\n return (definition) => {\n if (!definition || definition.extensionId !== componentId ||\n typeof definition.editorId !== 'string' || !Array.isArray(definition.opcodes)) {\n throw new TypeError('Invalid block editor registration for bundle member ' + componentId + '.');\n }\n const opcodes = definition.opcodes.map((opcode) => {\n if (typeof opcode !== 'string' || !opcode.startsWith(componentId + '_')) {\n throw new TypeError('Invalid block editor opcode for bundle member ' + componentId + '.');\n }\n return rewriteOpcode(componentId, opcode);\n });\n return value.call(api, {\n ...definition, extensionId: BUNDLE_ID,\n editorId: componentId + '__' + definition.editorId, opcodes,\n });\n };\n },\n });\n // Empty proxy targets allow the real host to freeze its API properties.\n return new Proxy({}, {\n get(_target, property) {\n return property === 'blockEditors' ? editors : Reflect.get(baseGui, property, baseGui);\n },\n });\n };\n`;\n}\n\nexport function createStaticExtensionBundle(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n originalProject: ProjectJson | undefined = undefined,\n moduleBindings: readonly string[] | undefined = undefined,\n): Buffer {\n assert(\n bundle.buildMode !== 'module' || moduleBindings?.length === components.length,\n `Module bundle ${bundle.id} requires the asynchronous module builder.`,\n );\n const componentIds = JSON.stringify(components.map((component) => component.metadata.id));\n const header = bundleHeader(bundle, components);\n const requirement = bundleUnsandboxedRequirement(components);\n const notice = sandboxedNotice(bundle, requirement);\n const loaders = moduleBindings\n ? components\n .map(\n (component, index) =>\n `loadModuleComponent(${JSON.stringify(component.extension.id)}, ${moduleBindings[index]});`,\n )\n .join('\\n')\n : components.map(componentLoadSource).join('\\n');\n const moduleValidation = moduleBindings\n ? components\n .map(\n (component, index) => `\n if (!${moduleBindings[index]}.bundleModuleMetadata ||\n ${moduleBindings[index]}.bundleModuleMetadata.formatVersion !== 1 ||\n ${moduleBindings[index]}.bundleModuleMetadata.id !== ${JSON.stringify(component.extension.id)} ||\n ${moduleBindings[index]}.bundleModuleMetadata.unsandboxed !== ${JSON.stringify(component.metadata.unsandboxed)} ||\n typeof ${moduleBindings[index]}.createExtension !== 'function') {\n throw new Error('Module entry contract mismatch: ' + ${JSON.stringify(component.extension.id)});\n }`,\n )\n .join('\\n')\n : '';\n const runtime = `(function (Scratch) {\n 'use strict';\n\n const BUNDLE_ID = ${JSON.stringify(bundle.id)};\n const BUNDLE_NAME = ${JSON.stringify(bundle.name)};\n const COMPONENT_IDS = ${componentIds};\n${moduleBindings ? moduleValidation : sandboxedGuardSource(requirement, notice)} const components = new Map();\n\n const rewriteOpcode = (componentId, opcode) => {\n const prefix = componentId + '_';\n return typeof opcode === 'string' && opcode.startsWith(prefix)\n ? BUNDLE_ID + '_' + componentId + '__' + opcode.slice(prefix.length)\n : opcode;\n };\n\n const rewriteBundleOpcode = (opcode) => {\n for (const componentId of COMPONENT_IDS) {\n const rewritten = rewriteOpcode(componentId, opcode);\n if (rewritten !== opcode) return rewritten;\n }\n return opcode;\n };\n\n const xmlEscape = (value) => String(value).replace(/[<>&'\"]/gu, (character) => ({\n '<': '<',\n '>': '>',\n '&': '&',\n \"'\": ''',\n '\"': '"',\n })[character]);\n\n const installStorageAliases = (storage) => {\n if (!storage || typeof storage !== 'object') return;\n const hasBundleStorage = Object.prototype.hasOwnProperty.call(storage, BUNDLE_ID);\n const hasMemberStorage = COMPONENT_IDS.some((id) => Object.prototype.hasOwnProperty.call(storage, id));\n if (!hasBundleStorage && !hasMemberStorage) return;\n let bundleStorage = storage[BUNDLE_ID];\n if (!bundleStorage || typeof bundleStorage !== 'object' || Array.isArray(bundleStorage)) {\n bundleStorage = {formatVersion: 1, components: {}};\n storage[BUNDLE_ID] = bundleStorage;\n }\n if (!bundleStorage.components || typeof bundleStorage.components !== 'object' || Array.isArray(bundleStorage.components)) {\n throw new Error('Invalid extension storage for static bundle ' + BUNDLE_ID + '.');\n }\n for (const id of COMPONENT_IDS) {\n const descriptor = Object.getOwnPropertyDescriptor(storage, id);\n if (descriptor && !descriptor.get && !Object.prototype.hasOwnProperty.call(bundleStorage.components, id)) {\n bundleStorage.components[id] = storage[id];\n }\n if (!descriptor || !descriptor.get) {\n delete storage[id];\n Object.defineProperty(storage, id, {\n configurable: true,\n enumerable: false,\n get: () => bundleStorage.components[id],\n set: (value) => {\n bundleStorage.components[id] = value;\n },\n });\n }\n }\n };\n\n const installAllStorageAliases = () => {\n const runtime = Scratch.vm && Scratch.vm.runtime;\n if (!runtime) return;\n installStorageAliases(runtime.extensionStorage);\n for (const target of runtime.targets || []) installStorageAliases(target.extensionStorage);\n };\n\n installAllStorageAliases();\n\n${bundle.blockEditorRegistrations === true ? blockEditorBridgeSource() : ''} const createComponentScratch = (componentId, register) => {\n${bundle.blockEditorRegistrations === true ? ' const gui = createComponentGui(componentId);\\n' : ''} const baseRuntime = Scratch.vm && Scratch.vm.runtime;\n const runtime = baseRuntime && new Proxy(baseRuntime, {\n get(target, property) {\n if (property === 'startHats') {\n return (opcode, ...args) => target.startHats(rewriteOpcode(componentId, opcode), ...args);\n }\n if (property === 'getOpcodeFunction') {\n return (opcode, ...args) => target.getOpcodeFunction(rewriteBundleOpcode(opcode), ...args);\n }\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n const baseVm = Scratch.vm;\n const vm = baseVm && new Proxy(baseVm, {\n get(target, property) {\n if (property === 'runtime') return runtime;\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n const extensions = Object.create(Scratch.extensions);\n Object.defineProperty(extensions, 'register', {value: register});\n return new Proxy(Scratch, {\n get(target, property) {\n if (property === 'extensions') return extensions;\n${bundle.blockEditorRegistrations === true ? \" if (property === 'gui') return gui;\\n\" : ''} if (property === 'vm') return vm;\n return Reflect.get(target, property, target);\n },\n });\n };\n\n${\n moduleBindings\n ? ` const loadModuleComponent = (componentId, module) => {\n const host = createComponentScratch(componentId, () => {throw new Error('Module factory must not register: ' + componentId);});\n const instance = module.createExtension(host);\n if (!instance || typeof instance.getInfo !== 'function' || typeof instance.then === 'function') {\n throw new Error('Module factory must synchronously return an extension: ' + componentId);\n }\n components.set(componentId, instance);\n };\n`\n : ` const loadComponent = (componentId, execute) => {\n let registration = null;\n let registrationCount = 0;\n let acceptingRegistration = true;\n const componentScratch = createComponentScratch(componentId, (extension) => {\n if (!acceptingRegistration) {\n throw new Error('Asynchronous registration is unsupported in static bundle member ' + componentId + '.');\n }\n registration = extension;\n registrationCount += 1;\n });\n execute(componentScratch);\n acceptingRegistration = false;\n if (registrationCount !== 1) {\n throw new Error(\n 'Static bundle member ' + componentId + ' must register exactly once synchronously; got ' + registrationCount + '.',\n );\n }\n components.set(componentId, registration);\n };\n`\n}\n${\n moduleBindings\n ? ` try {\\n${loaders}\\n } catch (error) {\n for (const component of [...components.values()].reverse()) {\n try {Promise.resolve(component.dispose?.()).catch(() => {});} catch (_cleanupError) { /* Preserve the activation error. */ }\n }\n throw error;\n }`\n : loaders\n}\n class StaticExtensionBundle {\n constructor() {\n this.delegates = new Map();\n }\n${\n moduleBindings\n ? `\n dispose() {\n if (!this.disposal) this.disposal = (async () => {\n const results = await Promise.allSettled([...components.values()].reverse().map(component => Promise.resolve().then(() => component.dispose?.())));\n const failures = results.filter(result => result.status === 'rejected').map(result => result.reason);\n if (failures.length) throw new AggregateError(failures, 'Bundle component cleanup failed.');\n })();\n return this.disposal;\n }\n`\n : ''\n}\n\n addDelegate(name, component, originalName) {\n if (this.delegates.has(name)) throw new Error('Duplicate static bundle delegate: ' + name);\n if (typeof originalName !== 'string' || typeof component[originalName] !== 'function') {\n throw new Error('Missing static bundle handler: ' + originalName);\n }\n this.delegates.set(name, {component, originalName});\n this[name] = (...args) => {\n installAllStorageAliases();\n return component[originalName](...args);\n };\n }\n\n getInfo() {\n const result = {\n id: BUNDLE_ID,\n name: BUNDLE_NAME,\n color1: '#5B67A5',\n color2: '#4D588C',\n color3: '#404874',\n blocks: [],\n menus: {},\n customFieldTypes: {},\n };${\n requirement === 'optional'\n ? `\n if (SANDBOXED) result.blocks.push(...sandboxedNoticeBlocks(), '---', '---');`\n : ''\n }\n this.delegates.clear();\n const transformedOpcodes = new Set();\n\n for (const [componentIndex, componentId] of COMPONENT_IDS.entries()) {\n const component = components.get(componentId);\n const info = component.getInfo();\n if (!info || info.id !== componentId) {\n throw new Error(\n 'Static bundle member runtime ID mismatch: expected ' + componentId + ', got ' +\n (info && info.id ? info.id : '(missing)') + '.',\n );\n }\n if (typeof info.name !== 'string' || info.name.length === 0) {\n throw new Error('Static bundle member ' + componentId + ' must have a non-empty name.');\n }\n const namespace = componentId + '__';\n const memberBlockIconURI =\n typeof info.blockIconURI === 'string' && info.blockIconURI.length > 0\n ? info.blockIconURI\n : null;\n const customFieldTypes = info.customFieldTypes || {};\n for (const [fieldName, fieldInfo] of Object.entries(customFieldTypes)) {\n result.customFieldTypes[namespace + fieldName] = fieldInfo;\n }\n if (componentIndex > 0) result.blocks.push('---', '---');\n result.blocks.push({\n blockType: Scratch.BlockType.LABEL,\n sb3Toolchain: {kind: 'bundle-member-heading', memberId: componentId},\n text: '◆ ' + info.name + ' [' + componentId + '] ◆',\n });\n if (info.docsURI) {\n const docsURI = String(info.docsURI);\n result.blocks.push({\n blockType: Scratch.BlockType.XML,\n sb3Toolchain: {\n docsURI,\n kind: 'bundle-member-docs',\n memberId: componentId,\n },\n xml: '<button text=\"Open Documentation\" callbackKey=\"OPEN_EXTENSION_DOCS\" callbackData=\"' + xmlEscape(docsURI) + '\"></button>',\n });\n }\n for (const block of info.blocks || []) {\n if (block === '---') {\n result.blocks.push(block);\n continue;\n }\n if (!block || typeof block !== 'object') throw new Error('Invalid block in static bundle member ' + componentId + '.');\n if (block.blockType === Scratch.BlockType.XML) {\n throw new Error('XML blocks are unsupported in static bundle member ' + componentId + '.');\n }\n const transformed = {...block};\n if (\n memberBlockIconURI !== null &&\n !Object.prototype.hasOwnProperty.call(block, 'blockIconURI') &&\n block.blockType !== Scratch.BlockType.LABEL &&\n block.blockType !== Scratch.BlockType.BUTTON\n ) {\n transformed.blockIconURI = memberBlockIconURI;\n }\n if (block.arguments) {\n transformed.arguments = Object.fromEntries(\n Object.entries(block.arguments).map(([argumentName, argument]) => {\n const transformedArgument = {...argument};\n if (typeof transformedArgument.menu === 'string') {\n transformedArgument.menu = namespace + transformedArgument.menu;\n }\n if (typeof transformedArgument.type === 'string' && Object.prototype.hasOwnProperty.call(customFieldTypes, transformedArgument.type)) {\n transformedArgument.type = namespace + transformedArgument.type;\n }\n return [argumentName, transformedArgument];\n }),\n );\n }\n if (block.blockType === Scratch.BlockType.LABEL) {\n result.blocks.push(transformed);\n continue;\n }\n if (block.blockType === Scratch.BlockType.BUTTON) {\n const delegateName = namespace + 'button__' + block.func;\n transformed.func = delegateName;\n this.addDelegate(delegateName, component, block.func);\n result.blocks.push(transformed);\n continue;\n }\n if (typeof block.opcode !== 'string' || block.opcode.length === 0) {\n throw new Error('Missing opcode in static bundle member ' + componentId + '.');\n }\n transformed.opcode = namespace + block.opcode;\n if (transformedOpcodes.has(transformed.opcode)) {\n throw new Error('Duplicate static bundle opcode: ' + transformed.opcode);\n }\n transformedOpcodes.add(transformed.opcode);\n if (block.blockType !== Scratch.BlockType.EVENT) {\n const originalName = block.func || block.opcode;\n transformed.func = transformed.opcode;\n this.addDelegate(transformed.opcode, component, originalName);\n } else {\n delete transformed.func;\n }\n result.blocks.push(transformed);\n }\n for (const [menuName, menu] of Object.entries(info.menus || {})) {\n const transformedMenuName = namespace + menuName;\n if (typeof menu === 'string') {\n const delegateName = namespace + 'menu__' + menuName;\n this.addDelegate(delegateName, component, menu);\n result.menus[transformedMenuName] = {items: delegateName};\n } else if (Array.isArray(menu)) {\n result.menus[transformedMenuName] = [...menu];\n } else if (menu && typeof menu === 'object') {\n const transformedMenu = {...menu};\n if (typeof menu.items === 'string') {\n const delegateName = namespace + 'menu__' + menuName;\n this.addDelegate(delegateName, component, menu.items);\n transformedMenu.items = delegateName;\n }\n result.menus[transformedMenuName] = transformedMenu;\n } else {\n throw new Error('Invalid menu in static bundle member ' + componentId + ': ' + menuName + '.');\n }\n }\n }\n return result;\n }\n }\n\n Scratch.extensions.register(new StaticExtensionBundle());\n})(Scratch);\n`;\n if (bundle.recoveryCapsule !== true) {\n return Buffer.from(`${header}\\n${runtime}`);\n }\n const capsule = Buffer.from(\n JSON.stringify(\n recoveryCapsule(\n bundle,\n components,\n originalProject ?? {\n extensions: bundle.members,\n extensionURLs: Object.fromEntries(bundle.members.map((memberId) => [memberId, true])),\n },\n ),\n ),\n ).toString('base64');\n return Buffer.from(`${header}\\n${runtime}\\n// ${extensionBundleRecoveryMarker}: ${capsule}\\n`);\n}\n\nfunction replaceMemberKeys(\n object: UnknownRecord,\n memberIds: Set<string>,\n bundleId: string,\n bundleValue: (value: unknown) => unknown,\n): {inserted: boolean; replacement: UnknownRecord} {\n const replacement: UnknownRecord = {};\n let inserted = false;\n for (const [key, value] of Object.entries(object)) {\n if (memberIds.has(key)) {\n if (!inserted) {\n replacement[bundleId] = bundleValue(value);\n inserted = true;\n }\n } else {\n replacement[key] = value;\n }\n }\n return {inserted, replacement};\n}\n\nfunction bundleStorage(storage: unknown, bundle: ExtensionBundleConfiguration): unknown {\n if (!isObject(storage)) return storage;\n const memberIds = new Set(bundle.members);\n const componentStorage: UnknownRecord = {};\n for (const memberId of bundle.members) {\n if (Object.hasOwn(storage, memberId)) componentStorage[memberId] = storage[memberId];\n }\n if (Object.keys(componentStorage).length === 0) return storage;\n assert(\n !Object.hasOwn(storage, bundle.id),\n `Extension storage already contains bundle ID: ${bundle.id}`,\n );\n return replaceMemberKeys(storage, memberIds, bundle.id, () => ({\n formatVersion: 1,\n components: componentStorage,\n })).replacement;\n}\n\nfunction rewriteOpcodeValues(\n value: unknown,\n bundle: ExtensionBundleConfiguration,\n counts: ExtensionBundleCounts,\n): void {\n if (!value || typeof value !== 'object') return;\n if (Array.isArray(value)) {\n for (const entry of value as unknown[]) rewriteOpcodeValues(entry, bundle, counts);\n return;\n }\n const record = value as UnknownRecord;\n for (const [key, entry] of Object.entries(record)) {\n if (key === 'opcode' && typeof entry === 'string') {\n for (const memberId of bundle.members) {\n const prefix = `${memberId}_`;\n if (entry.startsWith(prefix)) {\n record[key] = `${bundle.id}_${memberId}__${entry.slice(prefix.length)}`;\n counts.opcodes += 1;\n break;\n }\n }\n } else {\n rewriteOpcodeValues(entry, bundle, counts);\n }\n }\n}\n\nfunction collectRemainingOpcodeReferences(\n value: unknown,\n bundle: ExtensionBundleConfiguration,\n): string[] {\n const references: string[] = [];\n const prefixes = bundle.members.map((memberId) => `${memberId}_`);\n function visit(current: unknown, pointer: string): void {\n if (typeof current === 'string') {\n if (prefixes.some((prefix) => current.startsWith(prefix))) references.push(pointer || '/');\n return;\n }\n if (!current || typeof current !== 'object') return;\n if (Array.isArray(current)) {\n (current as unknown[]).forEach((entry, index) => visit(entry, `${pointer}/${index}`));\n return;\n }\n for (const [key, entry] of Object.entries(current as UnknownRecord)) {\n visit(entry, `${pointer}/${key}`);\n }\n }\n visit(value, '');\n return references;\n}\n\nfunction rewriteProjectForBundle(\n project: ProjectJson,\n bundle: ExtensionBundleConfiguration,\n): {counts: ExtensionBundleCounts; project: ProjectJson} {\n const rewritten = structuredClone(project);\n const memberIds = new Set(bundle.members);\n const counts: ExtensionBundleCounts = {\n extensionStorage: 0,\n extensionUrls: 0,\n opcodes: 0,\n projectExtensions: 0,\n };\n assert(isObject(rewritten.extensionURLs), 'project.source.json extensionURLs must be an object.');\n assert(\n !Object.hasOwn(rewritten.extensionURLs, bundle.id),\n `project.source.json already uses bundle ID: ${bundle.id}`,\n );\n for (const memberId of bundle.members) {\n assert(\n rewritten.extensionURLs[memberId] === `embedded-extension:extensions/${memberId}.js`,\n `Extension bundle ${bundle.id} member URL mismatch: ${memberId}`,\n );\n }\n const extensionUrls = replaceMemberKeys(\n rewritten.extensionURLs,\n memberIds,\n bundle.id,\n () => `embedded-extension:extensions/${bundle.id}.js`,\n );\n assert(\n extensionUrls.inserted,\n `Extension bundle ${bundle.id} did not replace any extension URL.`,\n );\n rewritten.extensionURLs = extensionUrls.replacement;\n counts.extensionUrls = bundle.members.length + 1;\n\n if (rewritten.extensions !== undefined) {\n assert(\n Array.isArray(rewritten.extensions),\n 'project.source.json extensions must be an array when present.',\n );\n const output: unknown[] = [];\n let inserted = false;\n for (const id of rewritten.extensions as unknown[]) {\n if (typeof id === 'string' && memberIds.has(id)) {\n counts.projectExtensions += 1;\n if (!inserted) {\n output.push(bundle.id);\n inserted = true;\n }\n } else {\n output.push(id);\n }\n }\n rewritten.extensions = output;\n }\n\n const originalGlobalStorage = rewritten.extensionStorage;\n rewritten.extensionStorage = bundleStorage(rewritten.extensionStorage, bundle);\n if (rewritten.extensionStorage !== originalGlobalStorage) counts.extensionStorage += 1;\n for (const target of (rewritten.targets as unknown[] | undefined) ?? []) {\n if (!isObject(target)) continue;\n const originalTargetStorage = target.extensionStorage;\n target.extensionStorage = bundleStorage(target.extensionStorage, bundle);\n if (target.extensionStorage !== originalTargetStorage) counts.extensionStorage += 1;\n }\n\n rewriteOpcodeValues(rewritten.targets, bundle, counts);\n rewriteOpcodeValues(rewritten.monitors, bundle, counts);\n const remainingReferences = collectRemainingOpcodeReferences(rewritten, bundle);\n assert(\n remainingReferences.length === 0,\n `Extension bundle ${bundle.id} has unsupported opcode references at: ` +\n remainingReferences.slice(0, 8).join(', '),\n );\n return {counts, project: rewritten};\n}\n\nexport function buildExtensionBundles({\n extensionBundles,\n extensionContents,\n extensions,\n project,\n moduleBuilds,\n}: BuildExtensionBundlesInput): BuildExtensionBundlesResult {\n if (extensionBundles.length === 0) {\n return {bundlePlans: [], extensionContents, extensions, project};\n }\n const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));\n const bundlesByMemberId = new Map<string, ExtensionBundleConfiguration>();\n const bundlePlans: ExtensionBundlePlan[] = [];\n let bundledProject = project;\n const bundledContents = new Map(extensionContents);\n\n for (const bundle of extensionBundles) {\n const components = readBundleComponents(bundle, extensionsById, extensionContents);\n const rewrite = rewriteProjectForBundle(bundledProject, bundle);\n const moduleBuild = moduleBuilds?.get(bundle.id);\n assert(\n bundle.buildMode !== 'module' || moduleBuild,\n `Module bundle ${bundle.id} requires buildExtensionBundlesWithModules.`,\n );\n const contents =\n moduleBuild?.contents ?? createStaticExtensionBundle(bundle, components, project);\n bundledProject = rewrite.project;\n bundledContents.set(bundle.id, contents);\n for (const memberId of bundle.members) {\n bundlesByMemberId.set(memberId, bundle);\n bundledContents.delete(memberId);\n }\n bundlePlans.push({\n bundle,\n components,\n contents,\n counts: rewrite.counts,\n ...(moduleBuild ? {moduleBuild: moduleBuild.report} : {}),\n });\n }\n\n const bundledExtensions: EmbeddedExtension[] = [];\n const emittedBundleIds = new Set<string>();\n for (const extension of extensions) {\n const bundle = bundlesByMemberId.get(extension.id);\n if (!bundle) {\n bundledExtensions.push(extension);\n } else if (!emittedBundleIds.has(bundle.id)) {\n emittedBundleIds.add(bundle.id);\n bundledExtensions.push({\n encoding: 'base64',\n id: bundle.id,\n mediaType: 'text/javascript',\n parameters: [],\n path: `extensions/${bundle.id}.js`,\n });\n }\n }\n return {\n bundlePlans,\n extensionContents: bundledContents,\n extensions: bundledExtensions,\n project: bundledProject,\n };\n}\n\nexport {validateBundleId, validateBundleName, bundleHeader, sandboxedGuardSource, sandboxedNotice};\n"],"mappings":";;;AAaA,IAAa,gCAAgC;AAuC7C,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,iBAAiB,IAAa,cAAc,uBAA+B;CAClF,OACE,OAAO,OAAO,YAAY,eAAe,KAAK,EAAE,GAChD,GAAG,YAAY,0CAA0C,KAAK,UAAU,EAAE,GAC5E;CACA,OAAO;AACT;;;;;AAMA,IAAa,0BAET,OAAO,OAAO;CAChB,UAAU,OAAO,OAAO;EACtB,IACE;EAIF,IACE;CAIJ,CAAC;CACD,UAAU,OAAO,OAAO;EACtB,IACE;EAGF,IACE;CAGJ,CAAC;AACH,CAAC;;;;;;AAOD,SAAgB,6BACd,YAC+B;CAC/B,MAAM,WAAW,WAAW,KAAK,cAAc,uBAAuB,UAAU,QAAQ,CAAC;CACzF,IAAI,SAAS,SAAS,UAAU,GAAG,OAAO;CAC1C,IAAI,SAAS,SAAS,UAAU,GAAG,OAAO;CAC1C,IAAI,SAAS,SAAS,KAAK,SAAS,OAAO,gBAAgB,gBAAgB,YAAY,GACrF,OAAO;CAET,OAAO;AACT;AAEA,SAAS,wBAAwB,QAAiB,UAA0C;CAC1F,OACE,SAAS,MAAM,KAAK,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,GACjD,oBAAoB,SAAS,gEAC/B;CACA,MAAM,YAAoC,CAAC;CAC3C,KAAK,MAAM,CAAC,QAAQ,YAAY,OAAO,QAAQ,MAAM,GAAG;EACtD,OACE,mCAAmC,KAAK,MAAM,GAC9C,oBAAoB,SAAS,8DAC3B,KAAK,UAAU,MAAM,CACzB;EAC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AY,4BAA4B,QAAQ,YAAY,OAAO;EAClF,iBAAiB,QAAQ;EACzB,gBAAgB,IAAI,OAAO,IAAI,QAAQ;EACvC,KAAK,MAAM,YAAY,OAAO,SAAS;GACrC,kBAAkB,IAAI,UAAU,MAAM;GACtC,gBAAgB,OAAO,QAAQ;EACjC;EACA,YAAY,KAAK;GACf;GACA;GACA;GACA,QAAQ,QAAQ;GAChB,GAAI,cAAc,EAAC,aAAa,YAAY,OAAM,IAAI,CAAC;EACzD,CAAC;CACH;CAEA,MAAM,oBAAyC,CAAC;CAChD,MAAM,mCAAmB,IAAI,IAAY;CACzC,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,SAAS,kBAAkB,IAAI,UAAU,EAAE;EACjD,IAAI,CAAC,QACH,kBAAkB,KAAK,SAAS;OAC3B,IAAI,CAAC,iBAAiB,IAAI,OAAO,EAAE,GAAG;GAC3C,iBAAiB,IAAI,OAAO,EAAE;GAC9B,kBAAkB,KAAK;IACrB,UAAU;IACV,IAAI,OAAO;IACX,WAAW;IACX,YAAY,CAAC;IACb,MAAM,cAAc,OAAO,GAAG;GAChC,CAAC;EACH;CACF;CACA,OAAO;EACL;EACA,mBAAmB;EACnB,YAAY;EACZ,SAAS;CACX;AACF"}
|
|
1
|
+
{"version":3,"file":"extension-bundle.js","names":[],"sources":["../src/extension-bundle.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {assert} from './assert';\nimport {extensionHeaderMetadata, unsandboxedRequirement} from './extension-dependencies';\nimport {validateExtensionBundleMetadata} from './extension-bundle-metadata';\nimport type {ExtensionHeaderMetadata, UnsandboxedRequirement} from './extension-dependencies';\nimport type {ExtensionModuleBuild, ExtensionModuleBuildReport} from './extension-module-bundle';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectJson,\n UnknownRecord,\n} from './types';\n\nexport const extensionBundleRecoveryMarker = 'SB3-Toolchain-Reversible-Bundle-v1';\n\nexport interface ExtensionBundleComponent {\n contents: string;\n extension: EmbeddedExtension;\n metadata: ExtensionHeaderMetadata;\n originalContents: Buffer;\n}\n\nexport interface ExtensionBundleCounts {\n extensionStorage: number;\n extensionUrls: number;\n opcodes: number;\n projectExtensions: number;\n}\n\nexport interface ExtensionBundlePlan {\n bundle: ExtensionBundleConfiguration;\n components: ExtensionBundleComponent[];\n contents: Buffer;\n counts: ExtensionBundleCounts;\n moduleBuild?: ExtensionModuleBuildReport;\n}\n\nexport interface BuildExtensionBundlesInput {\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n extensions: EmbeddedExtension[];\n project: ProjectJson;\n moduleBuilds?: ReadonlyMap<string, ExtensionModuleBuild>;\n}\n\nexport interface BuildExtensionBundlesResult {\n bundlePlans: ExtensionBundlePlan[];\n extensionContents: Map<string, Uint8Array>;\n extensions: EmbeddedExtension[];\n project: ProjectJson;\n}\n\nfunction isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nfunction validateBundleId(id: unknown, description = 'Extension bundle ID'): string {\n assert(\n typeof id === 'string' && /^[a-z0-9]+$/u.test(id),\n `${description} must use TurboWarp's [a-z0-9]+ format: ${JSON.stringify(id)}`,\n );\n return id;\n}\n\n/**\n * Shown in the palette when a bundle runs sandboxed although a member declared\n * `// Unsandboxed: required` (the members then do not run) or `optional` (they run with less).\n */\nexport const defaultSandboxedNotices: Readonly<\n Record<'required' | 'optional', Readonly<Record<string, string>>>\n> = Object.freeze({\n required: Object.freeze({\n en:\n 'This extension must run without the sandbox.\\n' +\n 'Load the project again and, in the extension\\n' +\n 'security dialog, check \"Run without sandbox\"\\n' +\n 'before allowing it.',\n ja:\n 'この拡張機能はサンドボックスなしで実行する必要があります。\\n' +\n 'プロジェクトを開き直し、拡張機能セキュリティの画面で\\n' +\n '「サンドボックスなしで実行する」にチェックを付けてから\\n' +\n '許可してください。',\n }),\n optional: Object.freeze({\n en:\n 'Running in the sandbox: some features are unavailable.\\n' +\n 'To use them, load the project again and check\\n' +\n '\"Run without sandbox\" in the extension security dialog.',\n ja:\n 'サンドボックス内で実行中のため、一部の機能が使えません。\\n' +\n '使うには、プロジェクトを開き直し、拡張機能セキュリティの画面で\\n' +\n '「サンドボックスなしで実行する」にチェックを付けてください。',\n }),\n});\n\n/**\n * Derives a bundle's requirement from its members' declarations: any `required` member makes the\n * bundle required; otherwise any `optional` member makes it optional; it is `not-needed` only when\n * every member says so. `null` means no member declares anything.\n */\nexport function bundleUnsandboxedRequirement(\n components: readonly Pick<ExtensionBundleComponent, 'metadata'>[],\n): UnsandboxedRequirement | null {\n const declared = components.map((component) => unsandboxedRequirement(component.metadata));\n if (declared.includes('required')) return 'required';\n if (declared.includes('optional')) return 'optional';\n if (declared.length > 0 && declared.every((requirement) => requirement === 'not-needed')) {\n return 'not-needed';\n }\n return null;\n}\n\nfunction validateSandboxedNotice(notice: unknown, bundleId: string): Record<string, string> {\n assert(\n isObject(notice) && Object.keys(notice).length > 0,\n `Extension bundle ${bundleId} sandboxedNotice must be a non-empty object of locale messages.`,\n );\n const validated: Record<string, string> = {};\n for (const [locale, message] of Object.entries(notice)) {\n assert(\n /^[a-z]{2,3}(?:-[a-z0-9]{2,8})*$/u.test(locale),\n `Extension bundle ${bundleId} sandboxedNotice locale must be a lowercase language tag: ` +\n JSON.stringify(locale),\n );\n assert(\n typeof message === 'string' && message.trim().length > 0,\n `Extension bundle ${bundleId} sandboxedNotice.${locale} must be a non-empty string.`,\n );\n validated[locale] = message;\n }\n return validated;\n}\n\nfunction validateBundleName(name: unknown): string {\n assert(\n typeof name === 'string' && name.trim() === name && name.length > 0 && !/[\\r\\n]/u.test(name),\n `Extension bundle name must be a non-empty single line: ${JSON.stringify(name)}`,\n );\n return name;\n}\n\nexport function validateExtensionBundleConfigurations(\n extensionBundles: unknown,\n extensions: EmbeddedExtension[],\n): ExtensionBundleConfiguration[] {\n if (extensionBundles === undefined) return [];\n assert(\n Array.isArray(extensionBundles),\n 'embedded-extensions.json extensionBundles must be an array.',\n );\n\n const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));\n const bundleIds = new Set<string>();\n const bundledMemberIds = new Set<string>();\n\n return (extensionBundles as unknown[]).map((bundle, bundleIndex) => {\n assert(isObject(bundle), `Extension bundle ${bundleIndex} must be an object.`);\n const id = validateBundleId(bundle.id, `Extension bundle ${bundleIndex} ID`);\n const name = validateBundleName(bundle.name);\n assert(\n bundle.buildMode === undefined ||\n bundle.buildMode === 'classic' ||\n bundle.buildMode === 'module',\n `Invalid buildMode for extension bundle ${id}.`,\n );\n if (bundle.sharedDependencies !== undefined) {\n assert(bundle.buildMode === 'module', `sharedDependencies requires buildMode module: ${id}`);\n assert(isObject(bundle.sharedDependencies), `sharedDependencies must be an object: ${id}`);\n for (const [name, version] of Object.entries(bundle.sharedDependencies)) {\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 typeof version === 'string' && /^\\d+\\.\\d+\\.\\d+(?:-[0-9A-Za-z.-]+)?$/u.test(version),\n `Shared dependency ${name} requires an exact version.`,\n );\n }\n }\n assert(!extensionsById.has(id), `Extension bundle ID collides with an extension: ${id}`);\n assert(!bundleIds.has(id), `Duplicate extension bundle ID: ${id}`);\n bundleIds.add(id);\n assert(\n Array.isArray(bundle.members) && bundle.members.length >= 2,\n `Extension bundle ${id} must contain at least two members.`,\n );\n assert(\n bundle.recoveryCapsule === undefined || typeof bundle.recoveryCapsule === 'boolean',\n `Extension bundle ${id} recoveryCapsule must be a boolean when present.`,\n );\n assert(\n bundle.blockEditorRegistrations === undefined ||\n typeof bundle.blockEditorRegistrations === 'boolean',\n `Extension bundle ${id} blockEditorRegistrations must be a boolean when present.`,\n );\n const blockEditorRegistrations = bundle.blockEditorRegistrations;\n const capsuleFlag = bundle.recoveryCapsule;\n const sandboxedNotice =\n bundle.sandboxedNotice === undefined\n ? undefined\n : validateSandboxedNotice(bundle.sandboxedNotice, id);\n\n const localMemberIds = new Set<string>();\n const members: string[] = [];\n for (const rawMemberId of bundle.members as unknown[]) {\n const memberId = validateBundleId(rawMemberId, `Extension bundle ${id} member ID`);\n assert(\n extensionsById.has(memberId),\n `Extension bundle ${id} has unknown member: ${memberId}`,\n );\n assert(!localMemberIds.has(memberId), `Extension bundle ${id} repeats member: ${memberId}`);\n assert(\n !bundledMemberIds.has(memberId),\n `Embedded extension belongs to more than one bundle: ${memberId}`,\n );\n localMemberIds.add(memberId);\n bundledMemberIds.add(memberId);\n members.push(memberId);\n }\n return {\n id,\n members,\n name,\n ...(bundle.metadata === undefined\n ? {}\n : {metadata: validateExtensionBundleMetadata(bundle.metadata)}),\n ...(bundle.buildMode === undefined ? {} : {buildMode: bundle.buildMode}),\n ...(bundle.sharedDependencies === undefined\n ? {}\n : {sharedDependencies: {...bundle.sharedDependencies} as Record<string, string>}),\n ...(capsuleFlag === undefined ? {} : {recoveryCapsule: capsuleFlag}),\n ...(sandboxedNotice === undefined ? {} : {sandboxedNotice}),\n ...(blockEditorRegistrations === undefined ? {} : {blockEditorRegistrations}),\n };\n });\n}\n\nexport function readBundleComponents(\n bundle: ExtensionBundleConfiguration,\n extensionsById: Map<string, EmbeddedExtension>,\n extensionContents: Map<string, Uint8Array>,\n): ExtensionBundleComponent[] {\n return bundle.members.map((memberId) => {\n const extension = extensionsById.get(memberId);\n const contents = extensionContents.get(memberId);\n assert(contents, `Extension bundle ${bundle.id} has no contents for member: ${memberId}`);\n assert(\n extension,\n `Extension bundle ${bundle.id} has no manifest entry for member: ${memberId}`,\n );\n assert(\n extension.mediaType === 'text/javascript' || extension.mediaType === 'application/javascript',\n `Extension bundle ${bundle.id} member ${memberId} must be JavaScript, got ${extension.mediaType}.`,\n );\n const metadata = extensionHeaderMetadata(contents);\n assert(\n metadata.id === memberId,\n `Extension bundle ${bundle.id} member header ID mismatch: expected ${memberId}, ` +\n `got ${metadata.id ?? '(missing)'}`,\n );\n for (const [property, label] of [\n ['name', 'Name'],\n ['author', 'By'],\n ['description', 'Description'],\n ['license', 'License'],\n ] as const) {\n assert(\n metadata[property],\n `Extension bundle ${bundle.id} member ${memberId} requires a // ${label}: header.`,\n );\n }\n unsandboxedRequirement(metadata);\n const source = Buffer.from(contents).toString('utf8');\n assert(\n !source.startsWith('#!'),\n `Extension bundle ${bundle.id} member ${memberId} cannot use a shebang.`,\n );\n assert(\n !source.includes(extensionBundleRecoveryMarker),\n `Extension bundle ${bundle.id} member ${memberId} contains the reserved recovery marker.`,\n );\n const registrations = source.match(/\\bScratch\\s*\\.\\s*extensions\\s*\\.\\s*register\\s*\\(/gu) ?? [];\n assert(\n registrations.length === 1,\n `Extension bundle ${bundle.id} member ${memberId} must contain exactly one synchronous ` +\n `Scratch.extensions.register call; found ${registrations.length}.`,\n );\n return {contents: source, extension, metadata, originalContents: Buffer.from(contents)};\n });\n}\n\nfunction commentLine(value: unknown): string {\n return String(value).replaceAll('\\r', ' ').replaceAll('\\n', ' ');\n}\n\nfunction bundleHeader(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n): string {\n const authors = [...new Set(components.map((component) => component.metadata.author))];\n const metadata =\n bundle.metadata === undefined ? undefined : validateExtensionBundleMetadata(bundle.metadata);\n const lines = [\n `// Name: ${commentLine(bundle.name)}`,\n `// ID: ${bundle.id}`,\n `// Description: ${metadata?.description ?? `Static bundle of ${components.length} TurboWarp extensions.`}`,\n ];\n for (const [locale, description] of Object.entries(metadata?.descriptions ?? {})) {\n lines.push(`// Description[${locale}]: ${description}`);\n }\n lines.push(`// By: ${metadata?.author ?? commentLine(authors.join(', '))}`);\n for (const [field, label] of [\n ['authorURL', 'Author URL'],\n ['version', 'Version'],\n ['updatedAt', 'Updated'],\n ['repository', 'Repository'],\n ['docsURL', 'Docs URL'],\n ['banner', 'Banner'],\n ['package', 'Package'],\n ] as const) {\n if (metadata?.[field] !== undefined) lines.push(`// ${label}: ${metadata[field]}`);\n }\n lines.push('// License: See the bundled extension notices below.');\n const requirement = bundleUnsandboxedRequirement(components);\n if (requirement !== null) lines.push(`// Unsandboxed: ${requirement}`);\n if (metadata)\n assert(lines.join('\\n').length < 16384, 'Bundle metadata exceeds the security header limit.');\n lines.push('//', '// Bundled extensions:');\n for (const component of components) {\n lines.push(\n `// - Name: ${commentLine(component.metadata.name)}`,\n `// ID: ${component.metadata.id}`,\n `// By: ${commentLine(component.metadata.author)}`,\n `// Description: ${commentLine(component.metadata.description)}`,\n `// License: ${commentLine(component.metadata.license)}`,\n );\n if (component.metadata.unsandboxed !== null) {\n lines.push(`// Unsandboxed: ${component.metadata.unsandboxed}`);\n }\n }\n return `${lines.join('\\n')}\\n`;\n}\n\nfunction componentLoadSource(component: ExtensionBundleComponent): string {\n const memberId = JSON.stringify(component.metadata.id);\n const source = component.contents.endsWith('\\n') ? component.contents : `${component.contents}\\n`;\n return `loadComponent(${memberId}, function (Scratch) {\\n${source}});\\n`;\n}\n\nfunction percentEncode(contents: Uint8Array | string): string {\n return [...Buffer.from(contents)]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction componentDataUrl(component: ExtensionBundleComponent): string {\n const metadata = [component.extension.mediaType, ...component.extension.parameters].join(';');\n const originalContents = component.originalContents ?? Buffer.from(component.contents);\n if (component.extension.encoding === 'base64') {\n return `data:${metadata};base64,${originalContents.toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(originalContents)}`;\n}\n\nfunction recoveryCapsule(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n originalProject: ProjectJson | undefined,\n): UnknownRecord {\n return {\n formatVersion: 1,\n bundle: {id: bundle.id, name: bundle.name},\n components: components.map((component) => ({\n dataUrl: componentDataUrl(component),\n id: component.metadata.id,\n })),\n originalExtensionIds: Array.isArray(originalProject?.extensions)\n ? [...(originalProject.extensions as unknown[])]\n : null,\n originalExtensionUrlIds: Object.keys(originalProject?.extensionURLs ?? {}),\n };\n}\n\nfunction sandboxedNotice(\n bundle: ExtensionBundleConfiguration,\n requirement: UnsandboxedRequirement | null,\n): Record<string, string> | null {\n if (requirement !== 'required' && requirement !== 'optional') {\n assert(\n bundle.sandboxedNotice === undefined,\n `Extension bundle ${bundle.id} sandboxedNotice needs a member that declares ` +\n '// Unsandboxed: required or optional.',\n );\n return null;\n }\n return {...defaultSandboxedNotices[requirement], ...bundle.sandboxedNotice};\n}\n\n/**\n * Detects a sandboxed load for a bundle whose members declared they need (`required`) or benefit\n * from (`optional`) TurboWarp's unsandboxed API. A required bundle registers a placeholder under\n * the bundle ID instead of running its members, so none can fail on a missing `Scratch.vm` and the\n * project still finishes loading: a sandboxed iframe that throws before registering leaves\n * TurboWarp waiting forever, and a worker reports only a generic failure. An optional bundle runs\n * its members and prefixes the palette with the notice. Bundles without a declaration get nothing.\n */\nfunction sandboxedGuardSource(\n requirement: UnsandboxedRequirement | null,\n notice: Record<string, string> | null,\n): string {\n if (notice === null) return '';\n const required = requirement === 'required';\n return `\n const SANDBOXED = !Scratch.extensions || Scratch.extensions.unsandboxed !== true;\n const SANDBOXED_NOTICE = ${JSON.stringify(notice)};\n const currentLocale = () => {\n try {\n if (Scratch.translate && typeof Scratch.translate.language === 'string') {\n return Scratch.translate.language;\n }\n } catch (_error) {\n // Fall through to the browser language.\n }\n return typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en';\n };\n const sandboxedNoticeText = () => {\n const locale = String(currentLocale()).toLowerCase();\n const language = locale.split('-')[0];\n if (Object.prototype.hasOwnProperty.call(SANDBOXED_NOTICE, locale)) return SANDBOXED_NOTICE[locale];\n if (Object.prototype.hasOwnProperty.call(SANDBOXED_NOTICE, language)) return SANDBOXED_NOTICE[language];\n return SANDBOXED_NOTICE.en;\n };\n const sandboxedNoticeBlocks = () => ['⚠ ' + BUNDLE_NAME, ...sandboxedNoticeText().split('\\\\n')]\n .filter((line) => line.length > 0)\n .map((line) => ({\n blockType: (Scratch.BlockType && Scratch.BlockType.LABEL) || 'label',\n sb3Toolchain: {kind: 'bundle-sandboxed-notice'},\n text: line,\n }));\n if (SANDBOXED && typeof console !== 'undefined') {\n const report = console.${required ? 'error' : 'warn'} || console.log;\n report.call(console, '[' + BUNDLE_ID + '] ' + BUNDLE_NAME + ' ${required ? 'requires' : 'works better with'} unsandboxed loading. ' + sandboxedNoticeText().replace(/\\\\n/gu, ' '));\n }\n${\n required\n ? ` if (SANDBOXED) {\n class SandboxedExtensionBundleNotice {\n getInfo() {\n return {\n id: BUNDLE_ID,\n name: BUNDLE_NAME,\n color1: '#D65C5C',\n color2: '#B64E4E',\n color3: '#964040',\n blocks: sandboxedNoticeBlocks(),\n menus: {},\n };\n }\n }\n Scratch.extensions.register(new SandboxedExtensionBundleNotice());\n return;\n }\n`\n : ''\n}`;\n}\n\n/** Editor callbacks and disposers stay owned by the GUI; only registration identities change. */\nfunction blockEditorBridgeSource(): string {\n return `\n const createComponentGui = (componentId) => {\n const baseGui = Scratch.gui;\n const api = baseGui && baseGui.blockEditors;\n if (!api || api.apiVersion !== 1) return baseGui;\n const registrations = new Set(['registerSchema', 'registerSchemaBundle', 'registerSourceEditor', 'registerFixedInputEditor']);\n const editors = new Proxy({}, {\n get(_target, property) {\n const value = Reflect.get(api, property, api);\n if (typeof value !== 'function') return value;\n if (!registrations.has(property)) return value.bind(api);\n return (definition) => {\n if (!definition || definition.extensionId !== componentId ||\n typeof definition.editorId !== 'string' || !Array.isArray(definition.opcodes)) {\n throw new TypeError('Invalid block editor registration for bundle member ' + componentId + '.');\n }\n const opcodes = definition.opcodes.map((opcode) => {\n if (typeof opcode !== 'string' || !opcode.startsWith(componentId + '_')) {\n throw new TypeError('Invalid block editor opcode for bundle member ' + componentId + '.');\n }\n return rewriteOpcode(componentId, opcode);\n });\n return value.call(api, {\n ...definition, extensionId: BUNDLE_ID,\n editorId: componentId + '__' + definition.editorId, opcodes,\n });\n };\n },\n });\n // Empty proxy targets allow the real host to freeze its API properties.\n return new Proxy({}, {\n get(_target, property) {\n return property === 'blockEditors' ? editors : Reflect.get(baseGui, property, baseGui);\n },\n });\n };\n`;\n}\n\nexport function createStaticExtensionBundle(\n bundle: ExtensionBundleConfiguration,\n components: ExtensionBundleComponent[],\n originalProject: ProjectJson | undefined = undefined,\n moduleBindings: readonly string[] | undefined = undefined,\n): Buffer {\n assert(\n bundle.buildMode !== 'module' || moduleBindings?.length === components.length,\n `Module bundle ${bundle.id} requires the asynchronous module builder.`,\n );\n const componentIds = JSON.stringify(components.map((component) => component.metadata.id));\n const header = bundleHeader(bundle, components);\n const requirement = bundleUnsandboxedRequirement(components);\n const notice = sandboxedNotice(bundle, requirement);\n const loaders = moduleBindings\n ? components\n .map(\n (component, index) =>\n `loadModuleComponent(${JSON.stringify(component.extension.id)}, ${moduleBindings[index]});`,\n )\n .join('\\n')\n : components.map(componentLoadSource).join('\\n');\n const moduleValidation = moduleBindings\n ? components\n .map(\n (component, index) => `\n if (!${moduleBindings[index]}.bundleModuleMetadata ||\n ${moduleBindings[index]}.bundleModuleMetadata.formatVersion !== 1 ||\n ${moduleBindings[index]}.bundleModuleMetadata.id !== ${JSON.stringify(component.extension.id)} ||\n ${moduleBindings[index]}.bundleModuleMetadata.unsandboxed !== ${JSON.stringify(component.metadata.unsandboxed)} ||\n typeof ${moduleBindings[index]}.createExtension !== 'function') {\n throw new Error('Module entry contract mismatch: ' + ${JSON.stringify(component.extension.id)});\n }`,\n )\n .join('\\n')\n : '';\n const runtime = `(function (Scratch) {\n 'use strict';\n\n const BUNDLE_ID = ${JSON.stringify(bundle.id)};\n const BUNDLE_NAME = ${JSON.stringify(bundle.name)};\n const COMPONENT_IDS = ${componentIds};\n${moduleBindings ? moduleValidation : sandboxedGuardSource(requirement, notice)} const components = new Map();\n\n const rewriteOpcode = (componentId, opcode) => {\n const prefix = componentId + '_';\n return typeof opcode === 'string' && opcode.startsWith(prefix)\n ? BUNDLE_ID + '_' + componentId + '__' + opcode.slice(prefix.length)\n : opcode;\n };\n\n const rewriteBundleOpcode = (opcode) => {\n for (const componentId of COMPONENT_IDS) {\n const rewritten = rewriteOpcode(componentId, opcode);\n if (rewritten !== opcode) return rewritten;\n }\n return opcode;\n };\n\n const xmlEscape = (value) => String(value).replace(/[<>&'\"]/gu, (character) => ({\n '<': '<',\n '>': '>',\n '&': '&',\n \"'\": ''',\n '\"': '"',\n })[character]);\n\n const installStorageAliases = (storage) => {\n if (!storage || typeof storage !== 'object') return;\n const hasBundleStorage = Object.prototype.hasOwnProperty.call(storage, BUNDLE_ID);\n const hasMemberStorage = COMPONENT_IDS.some((id) => Object.prototype.hasOwnProperty.call(storage, id));\n if (!hasBundleStorage && !hasMemberStorage) return;\n let bundleStorage = storage[BUNDLE_ID];\n if (!bundleStorage || typeof bundleStorage !== 'object' || Array.isArray(bundleStorage)) {\n bundleStorage = {formatVersion: 1, components: {}};\n storage[BUNDLE_ID] = bundleStorage;\n }\n if (!bundleStorage.components || typeof bundleStorage.components !== 'object' || Array.isArray(bundleStorage.components)) {\n throw new Error('Invalid extension storage for static bundle ' + BUNDLE_ID + '.');\n }\n for (const id of COMPONENT_IDS) {\n const descriptor = Object.getOwnPropertyDescriptor(storage, id);\n if (descriptor && !descriptor.get && !Object.prototype.hasOwnProperty.call(bundleStorage.components, id)) {\n bundleStorage.components[id] = storage[id];\n }\n if (!descriptor || !descriptor.get) {\n delete storage[id];\n Object.defineProperty(storage, id, {\n configurable: true,\n enumerable: false,\n get: () => bundleStorage.components[id],\n set: (value) => {\n bundleStorage.components[id] = value;\n },\n });\n }\n }\n };\n\n const installAllStorageAliases = () => {\n const runtime = Scratch.vm && Scratch.vm.runtime;\n if (!runtime) return;\n installStorageAliases(runtime.extensionStorage);\n for (const target of runtime.targets || []) installStorageAliases(target.extensionStorage);\n };\n\n installAllStorageAliases();\n\n${bundle.blockEditorRegistrations === true ? blockEditorBridgeSource() : ''} const createComponentScratch = (componentId, register) => {\n${bundle.blockEditorRegistrations === true ? ' const gui = createComponentGui(componentId);\\n' : ''} const baseRuntime = Scratch.vm && Scratch.vm.runtime;\n const runtime = baseRuntime && new Proxy(baseRuntime, {\n get(target, property) {\n if (property === 'startHats') {\n return (opcode, ...args) => target.startHats(rewriteOpcode(componentId, opcode), ...args);\n }\n if (property === 'getOpcodeFunction') {\n return (opcode, ...args) => target.getOpcodeFunction(rewriteBundleOpcode(opcode), ...args);\n }\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n const baseVm = Scratch.vm;\n const vm = baseVm && new Proxy(baseVm, {\n get(target, property) {\n if (property === 'runtime') return runtime;\n const value = Reflect.get(target, property, target);\n return typeof value === 'function' ? value.bind(target) : value;\n },\n });\n const extensions = Object.create(Scratch.extensions);\n Object.defineProperty(extensions, 'register', {value: register});\n return new Proxy(Scratch, {\n get(target, property) {\n if (property === 'extensions') return extensions;\n${bundle.blockEditorRegistrations === true ? \" if (property === 'gui') return gui;\\n\" : ''} if (property === 'vm') return vm;\n return Reflect.get(target, property, target);\n },\n });\n };\n\n${\n moduleBindings\n ? ` const loadModuleComponent = (componentId, module) => {\n const host = createComponentScratch(componentId, () => {throw new Error('Module factory must not register: ' + componentId);});\n const instance = module.createExtension(host);\n if (!instance || typeof instance.getInfo !== 'function' || typeof instance.then === 'function') {\n throw new Error('Module factory must synchronously return an extension: ' + componentId);\n }\n components.set(componentId, instance);\n };\n`\n : ` const loadComponent = (componentId, execute) => {\n let registration = null;\n let registrationCount = 0;\n let acceptingRegistration = true;\n const componentScratch = createComponentScratch(componentId, (extension) => {\n if (!acceptingRegistration) {\n throw new Error('Asynchronous registration is unsupported in static bundle member ' + componentId + '.');\n }\n registration = extension;\n registrationCount += 1;\n });\n execute(componentScratch);\n acceptingRegistration = false;\n if (registrationCount !== 1) {\n throw new Error(\n 'Static bundle member ' + componentId + ' must register exactly once synchronously; got ' + registrationCount + '.',\n );\n }\n components.set(componentId, registration);\n };\n`\n}\n${\n moduleBindings\n ? ` try {\\n${loaders}\\n } catch (error) {\n for (const component of [...components.values()].reverse()) {\n try {Promise.resolve(component.dispose?.()).catch(() => {});} catch (_cleanupError) { /* Preserve the activation error. */ }\n }\n throw error;\n }`\n : loaders\n}\n class StaticExtensionBundle {\n constructor() {\n this.delegates = new Map();\n }\n${\n moduleBindings\n ? `\n dispose() {\n if (!this.disposal) this.disposal = (async () => {\n const results = await Promise.allSettled([...components.values()].reverse().map(component => Promise.resolve().then(() => component.dispose?.())));\n const failures = results.filter(result => result.status === 'rejected').map(result => result.reason);\n if (failures.length) throw new AggregateError(failures, 'Bundle component cleanup failed.');\n })();\n return this.disposal;\n }\n`\n : ''\n}\n\n addDelegate(name, component, originalName) {\n if (this.delegates.has(name)) throw new Error('Duplicate static bundle delegate: ' + name);\n if (typeof originalName !== 'string' || typeof component[originalName] !== 'function') {\n throw new Error('Missing static bundle handler: ' + originalName);\n }\n this.delegates.set(name, {component, originalName});\n this[name] = (...args) => {\n installAllStorageAliases();\n return component[originalName](...args);\n };\n }\n\n getInfo() {\n const result = {\n id: BUNDLE_ID,\n name: BUNDLE_NAME,\n color1: '#5B67A5',\n color2: '#4D588C',\n color3: '#404874',\n blocks: [],\n menus: {},\n customFieldTypes: {},\n };${\n requirement === 'optional'\n ? `\n if (SANDBOXED) result.blocks.push(...sandboxedNoticeBlocks(), '---', '---');`\n : ''\n }\n this.delegates.clear();\n const transformedOpcodes = new Set();\n\n for (const [componentIndex, componentId] of COMPONENT_IDS.entries()) {\n const component = components.get(componentId);\n const info = component.getInfo();\n if (!info || info.id !== componentId) {\n throw new Error(\n 'Static bundle member runtime ID mismatch: expected ' + componentId + ', got ' +\n (info && info.id ? info.id : '(missing)') + '.',\n );\n }\n if (typeof info.name !== 'string' || info.name.length === 0) {\n throw new Error('Static bundle member ' + componentId + ' must have a non-empty name.');\n }\n const namespace = componentId + '__';\n const memberBlockIconURI =\n typeof info.blockIconURI === 'string' && info.blockIconURI.length > 0\n ? info.blockIconURI\n : null;\n const customFieldTypes = info.customFieldTypes || {};\n for (const [fieldName, fieldInfo] of Object.entries(customFieldTypes)) {\n result.customFieldTypes[namespace + fieldName] = fieldInfo;\n }\n if (componentIndex > 0) result.blocks.push('---', '---');\n result.blocks.push({\n blockType: Scratch.BlockType.LABEL,\n sb3Toolchain: {kind: 'bundle-member-heading', memberId: componentId},\n text: '◆ ' + info.name + ' [' + componentId + '] ◆',\n });\n if (info.docsURI) {\n const docsURI = String(info.docsURI);\n result.blocks.push({\n blockType: Scratch.BlockType.XML,\n sb3Toolchain: {\n docsURI,\n kind: 'bundle-member-docs',\n memberId: componentId,\n },\n xml: '<button text=\"Open Documentation\" callbackKey=\"OPEN_EXTENSION_DOCS\" callbackData=\"' + xmlEscape(docsURI) + '\"></button>',\n });\n }\n for (const block of info.blocks || []) {\n if (block === '---') {\n result.blocks.push(block);\n continue;\n }\n if (!block || typeof block !== 'object') throw new Error('Invalid block in static bundle member ' + componentId + '.');\n if (block.blockType === Scratch.BlockType.XML) {\n throw new Error('XML blocks are unsupported in static bundle member ' + componentId + '.');\n }\n const transformed = {...block};\n if (\n memberBlockIconURI !== null &&\n !Object.prototype.hasOwnProperty.call(block, 'blockIconURI') &&\n block.blockType !== Scratch.BlockType.LABEL &&\n block.blockType !== Scratch.BlockType.BUTTON\n ) {\n transformed.blockIconURI = memberBlockIconURI;\n }\n if (block.arguments) {\n transformed.arguments = Object.fromEntries(\n Object.entries(block.arguments).map(([argumentName, argument]) => {\n const transformedArgument = {...argument};\n if (typeof transformedArgument.menu === 'string') {\n transformedArgument.menu = namespace + transformedArgument.menu;\n }\n if (typeof transformedArgument.type === 'string' && Object.prototype.hasOwnProperty.call(customFieldTypes, transformedArgument.type)) {\n transformedArgument.type = namespace + transformedArgument.type;\n }\n return [argumentName, transformedArgument];\n }),\n );\n }\n if (block.blockType === Scratch.BlockType.LABEL) {\n result.blocks.push(transformed);\n continue;\n }\n if (block.blockType === Scratch.BlockType.BUTTON) {\n const delegateName = namespace + 'button__' + block.func;\n transformed.func = delegateName;\n this.addDelegate(delegateName, component, block.func);\n result.blocks.push(transformed);\n continue;\n }\n if (typeof block.opcode !== 'string' || block.opcode.length === 0) {\n throw new Error('Missing opcode in static bundle member ' + componentId + '.');\n }\n transformed.opcode = namespace + block.opcode;\n if (transformedOpcodes.has(transformed.opcode)) {\n throw new Error('Duplicate static bundle opcode: ' + transformed.opcode);\n }\n transformedOpcodes.add(transformed.opcode);\n if (block.blockType !== Scratch.BlockType.EVENT) {\n const originalName = block.func || block.opcode;\n transformed.func = transformed.opcode;\n this.addDelegate(transformed.opcode, component, originalName);\n } else {\n delete transformed.func;\n }\n result.blocks.push(transformed);\n }\n for (const [menuName, menu] of Object.entries(info.menus || {})) {\n const transformedMenuName = namespace + menuName;\n if (typeof menu === 'string') {\n const delegateName = namespace + 'menu__' + menuName;\n this.addDelegate(delegateName, component, menu);\n result.menus[transformedMenuName] = {items: delegateName};\n } else if (Array.isArray(menu)) {\n result.menus[transformedMenuName] = [...menu];\n } else if (menu && typeof menu === 'object') {\n const transformedMenu = {...menu};\n if (typeof menu.items === 'string') {\n const delegateName = namespace + 'menu__' + menuName;\n this.addDelegate(delegateName, component, menu.items);\n transformedMenu.items = delegateName;\n }\n result.menus[transformedMenuName] = transformedMenu;\n } else {\n throw new Error('Invalid menu in static bundle member ' + componentId + ': ' + menuName + '.');\n }\n }\n }\n return result;\n }\n }\n\n Scratch.extensions.register(new StaticExtensionBundle());\n})(Scratch);\n`;\n if (bundle.recoveryCapsule !== true) {\n return Buffer.from(`${header}\\n${runtime}`);\n }\n const capsule = Buffer.from(\n JSON.stringify(\n recoveryCapsule(\n bundle,\n components,\n originalProject ?? {\n extensions: bundle.members,\n extensionURLs: Object.fromEntries(bundle.members.map((memberId) => [memberId, true])),\n },\n ),\n ),\n ).toString('base64');\n return Buffer.from(`${header}\\n${runtime}\\n// ${extensionBundleRecoveryMarker}: ${capsule}\\n`);\n}\n\nfunction replaceMemberKeys(\n object: UnknownRecord,\n memberIds: Set<string>,\n bundleId: string,\n bundleValue: (value: unknown) => unknown,\n): {inserted: boolean; replacement: UnknownRecord} {\n const replacement: UnknownRecord = {};\n let inserted = false;\n for (const [key, value] of Object.entries(object)) {\n if (memberIds.has(key)) {\n if (!inserted) {\n replacement[bundleId] = bundleValue(value);\n inserted = true;\n }\n } else {\n replacement[key] = value;\n }\n }\n return {inserted, replacement};\n}\n\nfunction bundleStorage(storage: unknown, bundle: ExtensionBundleConfiguration): unknown {\n if (!isObject(storage)) return storage;\n const memberIds = new Set(bundle.members);\n const componentStorage: UnknownRecord = {};\n for (const memberId of bundle.members) {\n if (Object.hasOwn(storage, memberId)) componentStorage[memberId] = storage[memberId];\n }\n if (Object.keys(componentStorage).length === 0) return storage;\n assert(\n !Object.hasOwn(storage, bundle.id),\n `Extension storage already contains bundle ID: ${bundle.id}`,\n );\n return replaceMemberKeys(storage, memberIds, bundle.id, () => ({\n formatVersion: 1,\n components: componentStorage,\n })).replacement;\n}\n\nfunction rewriteOpcodeValues(\n value: unknown,\n bundle: ExtensionBundleConfiguration,\n counts: ExtensionBundleCounts,\n): void {\n if (!value || typeof value !== 'object') return;\n if (Array.isArray(value)) {\n for (const entry of value as unknown[]) rewriteOpcodeValues(entry, bundle, counts);\n return;\n }\n const record = value as UnknownRecord;\n for (const [key, entry] of Object.entries(record)) {\n if (key === 'opcode' && typeof entry === 'string') {\n for (const memberId of bundle.members) {\n const prefix = `${memberId}_`;\n if (entry.startsWith(prefix)) {\n record[key] = `${bundle.id}_${memberId}__${entry.slice(prefix.length)}`;\n counts.opcodes += 1;\n break;\n }\n }\n } else {\n rewriteOpcodeValues(entry, bundle, counts);\n }\n }\n}\n\nfunction collectRemainingOpcodeReferences(\n value: unknown,\n bundle: ExtensionBundleConfiguration,\n): string[] {\n const references: string[] = [];\n const prefixes = bundle.members.map((memberId) => `${memberId}_`);\n function visit(current: unknown, pointer: string): void {\n if (typeof current === 'string') {\n if (prefixes.some((prefix) => current.startsWith(prefix))) references.push(pointer || '/');\n return;\n }\n if (!current || typeof current !== 'object') return;\n if (Array.isArray(current)) {\n (current as unknown[]).forEach((entry, index) => visit(entry, `${pointer}/${index}`));\n return;\n }\n for (const [key, entry] of Object.entries(current as UnknownRecord)) {\n visit(entry, `${pointer}/${key}`);\n }\n }\n visit(value, '');\n return references;\n}\n\nfunction rewriteProjectForBundle(\n project: ProjectJson,\n bundle: ExtensionBundleConfiguration,\n): {counts: ExtensionBundleCounts; project: ProjectJson} {\n const rewritten = structuredClone(project);\n const memberIds = new Set(bundle.members);\n const counts: ExtensionBundleCounts = {\n extensionStorage: 0,\n extensionUrls: 0,\n opcodes: 0,\n projectExtensions: 0,\n };\n assert(isObject(rewritten.extensionURLs), 'project.source.json extensionURLs must be an object.');\n assert(\n !Object.hasOwn(rewritten.extensionURLs, bundle.id),\n `project.source.json already uses bundle ID: ${bundle.id}`,\n );\n for (const memberId of bundle.members) {\n assert(\n rewritten.extensionURLs[memberId] === `embedded-extension:extensions/${memberId}.js`,\n `Extension bundle ${bundle.id} member URL mismatch: ${memberId}`,\n );\n }\n const extensionUrls = replaceMemberKeys(\n rewritten.extensionURLs,\n memberIds,\n bundle.id,\n () => `embedded-extension:extensions/${bundle.id}.js`,\n );\n assert(\n extensionUrls.inserted,\n `Extension bundle ${bundle.id} did not replace any extension URL.`,\n );\n rewritten.extensionURLs = extensionUrls.replacement;\n counts.extensionUrls = bundle.members.length + 1;\n\n if (rewritten.extensions !== undefined) {\n assert(\n Array.isArray(rewritten.extensions),\n 'project.source.json extensions must be an array when present.',\n );\n const output: unknown[] = [];\n let inserted = false;\n for (const id of rewritten.extensions as unknown[]) {\n if (typeof id === 'string' && memberIds.has(id)) {\n counts.projectExtensions += 1;\n if (!inserted) {\n output.push(bundle.id);\n inserted = true;\n }\n } else {\n output.push(id);\n }\n }\n rewritten.extensions = output;\n }\n\n const originalGlobalStorage = rewritten.extensionStorage;\n rewritten.extensionStorage = bundleStorage(rewritten.extensionStorage, bundle);\n if (rewritten.extensionStorage !== originalGlobalStorage) counts.extensionStorage += 1;\n for (const target of (rewritten.targets as unknown[] | undefined) ?? []) {\n if (!isObject(target)) continue;\n const originalTargetStorage = target.extensionStorage;\n target.extensionStorage = bundleStorage(target.extensionStorage, bundle);\n if (target.extensionStorage !== originalTargetStorage) counts.extensionStorage += 1;\n }\n\n rewriteOpcodeValues(rewritten.targets, bundle, counts);\n rewriteOpcodeValues(rewritten.monitors, bundle, counts);\n const remainingReferences = collectRemainingOpcodeReferences(rewritten, bundle);\n assert(\n remainingReferences.length === 0,\n `Extension bundle ${bundle.id} has unsupported opcode references at: ` +\n remainingReferences.slice(0, 8).join(', '),\n );\n return {counts, project: rewritten};\n}\n\nexport function buildExtensionBundles({\n extensionBundles,\n extensionContents,\n extensions,\n project,\n moduleBuilds,\n}: BuildExtensionBundlesInput): BuildExtensionBundlesResult {\n if (extensionBundles.length === 0) {\n return {bundlePlans: [], extensionContents, extensions, project};\n }\n const extensionsById = new Map(extensions.map((extension) => [extension.id, extension]));\n const bundlesByMemberId = new Map<string, ExtensionBundleConfiguration>();\n const bundlePlans: ExtensionBundlePlan[] = [];\n let bundledProject = project;\n const bundledContents = new Map(extensionContents);\n\n for (const bundle of extensionBundles) {\n const components = readBundleComponents(bundle, extensionsById, extensionContents);\n const rewrite = rewriteProjectForBundle(bundledProject, bundle);\n const moduleBuild = moduleBuilds?.get(bundle.id);\n assert(\n bundle.buildMode !== 'module' || moduleBuild,\n `Module bundle ${bundle.id} requires buildExtensionBundlesWithModules.`,\n );\n const contents =\n moduleBuild?.contents ?? createStaticExtensionBundle(bundle, components, project);\n bundledProject = rewrite.project;\n bundledContents.set(bundle.id, contents);\n for (const memberId of bundle.members) {\n bundlesByMemberId.set(memberId, bundle);\n bundledContents.delete(memberId);\n }\n bundlePlans.push({\n bundle,\n components,\n contents,\n counts: rewrite.counts,\n ...(moduleBuild ? {moduleBuild: moduleBuild.report} : {}),\n });\n }\n\n const bundledExtensions: EmbeddedExtension[] = [];\n const emittedBundleIds = new Set<string>();\n for (const extension of extensions) {\n const bundle = bundlesByMemberId.get(extension.id);\n if (!bundle) {\n bundledExtensions.push(extension);\n } else if (!emittedBundleIds.has(bundle.id)) {\n emittedBundleIds.add(bundle.id);\n bundledExtensions.push({\n encoding: 'base64',\n id: bundle.id,\n mediaType: 'text/javascript',\n parameters: [],\n path: `extensions/${bundle.id}.js`,\n });\n }\n }\n return {\n bundlePlans,\n extensionContents: bundledContents,\n extensions: bundledExtensions,\n project: bundledProject,\n };\n}\n\nexport {validateBundleId, validateBundleName, bundleHeader, sandboxedGuardSource, sandboxedNotice};\n"],"mappings":";;;;AAcA,IAAa,gCAAgC;AAuC7C,SAAS,SAAS,OAAwC;CACxD,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAS,iBAAiB,IAAa,cAAc,uBAA+B;CAClF,OACE,OAAO,OAAO,YAAY,eAAe,KAAK,EAAE,GAChD,GAAG,YAAY,0CAA0C,KAAK,UAAU,EAAE,GAC5E;CACA,OAAO;AACT;;;;;AAMA,IAAa,0BAET,OAAO,OAAO;CAChB,UAAU,OAAO,OAAO;EACtB,IACE;EAIF,IACE;CAIJ,CAAC;CACD,UAAU,OAAO,OAAO;EACtB,IACE;EAGF,IACE;CAGJ,CAAC;AACH,CAAC;;;;;;AAOD,SAAgB,6BACd,YAC+B;CAC/B,MAAM,WAAW,WAAW,KAAK,cAAc,uBAAuB,UAAU,QAAQ,CAAC;CACzF,IAAI,SAAS,SAAS,UAAU,GAAG,OAAO;CAC1C,IAAI,SAAS,SAAS,UAAU,GAAG,OAAO;CAC1C,IAAI,SAAS,SAAS,KAAK,SAAS,OAAO,gBAAgB,gBAAgB,YAAY,GACrF,OAAO;CAET,OAAO;AACT;AAEA,SAAS,wBAAwB,QAAiB,UAA0C;CAC1F,OACE,SAAS,MAAM,KAAK,OAAO,KAAK,MAAM,CAAC,CAAC,SAAS,GACjD,oBAAoB,SAAS,gEAC/B;CACA,MAAM,YAAoC,CAAC;CAC3C,KAAK,MAAM,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I,IAAY;CACzC,KAAK,MAAM,aAAa,YAAY;EAClC,MAAM,SAAS,kBAAkB,IAAI,UAAU,EAAE;EACjD,IAAI,CAAC,QACH,kBAAkB,KAAK,SAAS;OAC3B,IAAI,CAAC,iBAAiB,IAAI,OAAO,EAAE,GAAG;GAC3C,iBAAiB,IAAI,OAAO,EAAE;GAC9B,kBAAkB,KAAK;IACrB,UAAU;IACV,IAAI,OAAO;IACX,WAAW;IACX,YAAY,CAAC;IACb,MAAM,cAAc,OAAO,GAAG;GAChC,CAAC;EACH;CACF;CACA,OAAO;EACL;EACA,mBAAmB;EACnB,YAAY;EACZ,SAAS;CACX;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
export type { EmbeddedExtension, EmbeddedExtensionManifest, ExtensionApiManifestSource, ExtensionBundleConfiguration, ExtensionEncoding, ExtensionModuleSource, ExtensionSource, GitHubExtensionSource, NpmExtensionSource, ProjectAssetReference, ProjectJson, ProjectTarget, Sb3SourceManifest, } from './types';
|
|
1
|
+
export type { EmbeddedExtension, EmbeddedExtensionManifest, ExtensionApiManifestSource, ExtensionBundleConfiguration, ExtensionBundleMetadata, ExtensionEncoding, ExtensionModuleSource, ExtensionSource, GitHubExtensionSource, NpmExtensionSource, ProjectAssetReference, ProjectJson, ProjectTarget, Sb3SourceManifest, } from './types';
|
|
2
2
|
export { assert } from './assert';
|
|
3
3
|
export { validateArchiveEntryName } from './archive';
|
|
4
4
|
export { buildSb3 } from './build';
|
package/dist/types.d.ts
CHANGED
|
@@ -39,10 +39,24 @@ export interface EmbeddedExtension {
|
|
|
39
39
|
encoding: ExtensionEncoding;
|
|
40
40
|
source?: ExtensionSource;
|
|
41
41
|
}
|
|
42
|
+
/** Explicit presentation of the bundle itself, independent of its member packages. */
|
|
43
|
+
export interface ExtensionBundleMetadata {
|
|
44
|
+
description?: string;
|
|
45
|
+
descriptions?: Record<string, string>;
|
|
46
|
+
author?: string;
|
|
47
|
+
authorURL?: string;
|
|
48
|
+
version?: string;
|
|
49
|
+
updatedAt?: string;
|
|
50
|
+
repository?: string;
|
|
51
|
+
docsURL?: string;
|
|
52
|
+
banner?: string;
|
|
53
|
+
package?: string;
|
|
54
|
+
}
|
|
42
55
|
export interface ExtensionBundleConfiguration {
|
|
43
56
|
id: string;
|
|
44
57
|
name: string;
|
|
45
58
|
members: string[];
|
|
59
|
+
metadata?: ExtensionBundleMetadata;
|
|
46
60
|
recoveryCapsule?: boolean;
|
|
47
61
|
sandboxedNotice?: Record<string, string>;
|
|
48
62
|
blockEditorRegistrations?: boolean;
|
|
@@ -68,6 +68,36 @@ sb3-toolchain build app --output dist/project.sb3
|
|
|
68
68
|
`bundleExtensions` and `planExtensionBundle` also accept `buildMode` and `sharedDependencies`.
|
|
69
69
|
Repeat `--share` for additional packages. GUI editor adaptation remains an explicit manifest option.
|
|
70
70
|
|
|
71
|
+
The bundle's optional `metadata` describes the complete bundle, rather than its first member:
|
|
72
|
+
|
|
73
|
+
```json
|
|
74
|
+
{
|
|
75
|
+
"description": "The complete application extension.",
|
|
76
|
+
"descriptions": {"ja": "アプリ全体の機能拡張。"},
|
|
77
|
+
"author": "Application Author",
|
|
78
|
+
"authorURL": "https://example.com/author",
|
|
79
|
+
"version": "1.2.3",
|
|
80
|
+
"repository": "https://github.com/example/application",
|
|
81
|
+
"docsURL": "https://example.com/docs/",
|
|
82
|
+
"banner": "https://example.com/banner.png",
|
|
83
|
+
"package": "@example/application"
|
|
84
|
+
}
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Put this object in `extensionBundles[].metadata`, pass `metadata` to `bundleExtensions` or
|
|
88
|
+
`planExtensionBundle`, or use `--metadata-json '{"version":"1.2.3"}'` with the bundle command.
|
|
89
|
+
The exported `ExtensionBundleMetadata` type also accepts `updatedAt`. Fields are single lines of at
|
|
90
|
+
most 1000 characters. Locale keys are lowercase language tags. Repository and documentation URLs
|
|
91
|
+
use HTTPS; author URLs allow HTTP or HTTPS and require an explicit author in the same object.
|
|
92
|
+
Banners allow HTTPS or image data URLs for PNG, JPEG, GIF, WebP, or SVG; the data URL prefix is
|
|
93
|
+
normalized to lowercase. Invalid values, credentials, and unknown fields are rejected.
|
|
94
|
+
|
|
95
|
+
These fields become comment headers in both classic and module bundles, without executing members
|
|
96
|
+
to obtain display information. Name and ID remain bundle settings; licenses and sandbox requirements
|
|
97
|
+
remain derived from members. No package or author URL is inferred from a member. Omitting `metadata`
|
|
98
|
+
retains the existing generated bytes; removing it restores that output for future builds. Previously
|
|
99
|
+
frozen release artifacts must retain their original bytes.
|
|
100
|
+
|
|
71
101
|
The resolver checks the selected version against each importer's declared range and uses one real
|
|
72
102
|
package under browser conditions. yaml must use its browser entry; duplicate copies or mixed Node
|
|
73
103
|
and browser graphs fail. Missing entries, mismatched package versions, classic artifacts, module
|
package/docs/index.html
CHANGED
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
<body>
|
|
70
70
|
<header>
|
|
71
71
|
<h1>SB3 Toolchain</h1>
|
|
72
|
-
<p><code>@kubohiroya/sb3-toolchain@0.19.
|
|
72
|
+
<p><code>@kubohiroya/sb3-toolchain@0.19.1</code></p>
|
|
73
73
|
<nav aria-label="Documentation">
|
|
74
74
|
<a href="#scope">責務</a><a href="#usage">使い方</a><a href="#api">API</a
|
|
75
75
|
><a href="#schemas">Schema</a><a href="#guides">関連文書</a>
|
|
@@ -90,7 +90,7 @@
|
|
|
90
90
|
<section id="usage">
|
|
91
91
|
<h2>使い方</h2>
|
|
92
92
|
<p>公開済みの完全固定versionを使います。</p>
|
|
93
|
-
<pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.19.
|
|
93
|
+
<pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.19.1</code></pre>
|
|
94
94
|
<pre><code>sb3-toolchain import tmp/project.sb3 --output app
|
|
95
95
|
sb3-toolchain check app
|
|
96
96
|
sb3-toolchain build app --output dist/project.sb3</code></pre>
|
|
@@ -64,6 +64,36 @@ sb3-toolchain build app --output dist/project.sb3
|
|
|
64
64
|
APIは`bundleExtensions` / `planExtensionBundle`の`buildMode`と`sharedDependencies`でも指定できます。
|
|
65
65
|
`--share`は複数指定でき、完全な版番号を要求します。GUIの編集登録変換は従来どおりmanifestで明示選択します。
|
|
66
66
|
|
|
67
|
+
任意の`metadata`は、先頭メンバーではなくbundle全体の表示情報を明示します。
|
|
68
|
+
|
|
69
|
+
```json
|
|
70
|
+
{
|
|
71
|
+
"description": "The complete application extension.",
|
|
72
|
+
"descriptions": {"ja": "アプリ全体の機能拡張。"},
|
|
73
|
+
"author": "Application Author",
|
|
74
|
+
"authorURL": "https://example.com/author",
|
|
75
|
+
"version": "1.2.3",
|
|
76
|
+
"repository": "https://github.com/example/application",
|
|
77
|
+
"docsURL": "https://example.com/docs/",
|
|
78
|
+
"banner": "https://example.com/banner.png",
|
|
79
|
+
"package": "@example/application"
|
|
80
|
+
}
|
|
81
|
+
```
|
|
82
|
+
|
|
83
|
+
このobjectを`extensionBundles[].metadata`へ保存するか、APIの`bundleExtensions`/
|
|
84
|
+
`planExtensionBundle`へ`metadata`として渡します。CLIではbundleコマンドに
|
|
85
|
+
`--metadata-json '{"version":"1.2.3"}'`を指定します。公開型`ExtensionBundleMetadata`は
|
|
86
|
+
`updatedAt`も受け付けます。各値は1000文字以内の単行で、localeは小文字の言語タグです。
|
|
87
|
+
repository/docsURLはHTTPS、authorURLはHTTPまたはHTTPSとし、同じobjectにauthorも明示します。
|
|
88
|
+
bannerはHTTPSまたはPNG/JPEG/GIF/WebP/SVGの画像data URIを受け付け、data URIのprefixを
|
|
89
|
+
小文字に正規化します。不正な値・認証情報付きURL・未定義fieldは拒否します。
|
|
90
|
+
|
|
91
|
+
classic/moduleの両方でコメントheaderへ出力し、表示情報を得るためにメンバーを実行しません。
|
|
92
|
+
名前とIDは従来のbundle設定、ライセンスと実行要件は従来のメンバー集約を維持します。
|
|
93
|
+
メンバーのpackageやauthorURLをbundle全体へ推測適用しません。metadataを省略した場合の
|
|
94
|
+
生成bytesは従来どおりです。metadataを外すと以後のbuildは従来出力に戻せますが、凍結済みの
|
|
95
|
+
リリース成果物は元のbytesを保持してください。
|
|
96
|
+
|
|
67
97
|
共有packageの要求範囲と選択版を照合し、browser条件で同じ実体へ解決します。yamlはbrowser入口に限定し、
|
|
68
98
|
別コピーやNode向け実装が混ざるgraphを拒否します。版・classicとの一致・module integrity・対応入口不足も診断します。
|
|
69
99
|
必要なunsandboxed権限を得られなければ、ライブラリ評価やfactory生成より前に従来の案内拡張だけを登録します。
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@kubohiroya/sb3-toolchain",
|
|
3
|
-
"version": "0.19.
|
|
3
|
+
"version": "0.19.1",
|
|
4
4
|
"description": "Git-friendly source management and deterministic builds for Scratch 3 and TurboWarp SB3 projects",
|
|
5
5
|
"type": "module",
|
|
6
6
|
"license": "MPL-2.0",
|
|
@@ -85,9 +85,9 @@
|
|
|
85
85
|
"source-control",
|
|
86
86
|
"reproducible-builds"
|
|
87
87
|
],
|
|
88
|
-
"gitHead": "
|
|
88
|
+
"gitHead": "642f5c81d99c1892fdfc90b5a9bd52fe90e65184",
|
|
89
89
|
"x-turbowarp-source": {
|
|
90
|
-
"revision": "
|
|
90
|
+
"revision": "642f5c81d99c1892fdfc90b5a9bd52fe90e65184",
|
|
91
91
|
"revisionRole": "base-commit",
|
|
92
92
|
"sourceState": "local-release-overlay"
|
|
93
93
|
}
|