@kubohiroya/sb3-toolchain 0.24.0 → 0.25.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 +14 -0
- package/README.ja.md +5 -2
- package/README.md +5 -2
- package/dist/block-palette.d.ts +60 -0
- package/dist/block-palette.js +295 -0
- package/dist/block-palette.js.map +1 -0
- package/dist/browser.d.ts +13 -4
- package/dist/browser.js +14 -3
- package/dist/browser.js.map +1 -1
- package/dist/build.d.ts +1 -1
- package/dist/clean-up-sb3.d.ts +2 -2
- package/dist/cli.d.ts +2 -2
- package/dist/cli.js +1 -0
- 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/expand-archive.d.ts +6 -3
- package/dist/expand-archive.js +14 -3
- package/dist/expand-archive.js.map +1 -1
- package/dist/extension-api-manifest.d.ts +1 -1
- package/dist/extension-bundle-configuration.d.ts +4 -4
- package/dist/extension-bundle-metadata.d.ts +1 -1
- package/dist/extension-bundle.d.ts +3 -3
- package/dist/extension-dependencies.d.ts +1 -1
- package/dist/extension-id-migration.d.ts +2 -2
- package/dist/extension-module-bundle.d.ts +2 -2
- package/dist/extension-sb3-replacement.d.ts +2 -2
- package/dist/extension-sync.d.ts +6 -6
- package/dist/import.d.ts +6 -3
- package/dist/import.js +4 -3
- package/dist/import.js.map +1 -1
- package/dist/index.d.ts +42 -40
- package/dist/index.js +3 -2
- package/dist/npm-extension-source.d.ts +1 -1
- package/dist/output-safety.d.ts +1 -1
- package/dist/output-safety.js +2 -2
- package/dist/output-safety.js.map +1 -1
- package/dist/project-asset-additions.d.ts +1 -1
- package/dist/release-snapshot.d.ts +1 -1
- package/dist/source-format.d.ts +8 -1
- package/dist/source-format.js +10 -2
- package/dist/source-format.js.map +1 -1
- package/dist/source.d.ts +7 -4
- package/dist/source.js +7 -2
- package/dist/source.js.map +1 -1
- package/dist/turbowarp-clean-up.d.ts +1 -1
- package/dist/types.d.ts +2 -0
- package/docs/index.html +4 -2
- package/docs/ja/source-format-v1.md +2 -0
- package/docs/ja/source-format-v2.md +139 -0
- package/docs/source-format-v1.md +3 -0
- package/docs/source-format-v2.md +171 -0
- package/package.json +1 -1
package/dist/import.js
CHANGED
|
@@ -2,7 +2,7 @@ import { assert } from "./assert.js";
|
|
|
2
2
|
import { assertNoInterruptedRollback, assertRecognizedOutputDirectory, compareDirectories, inspectGitOutputState, pathExists, replaceDirectoryTransactionally, validateOutputDirectoryPath } from "./output-safety.js";
|
|
3
3
|
import { validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
|
|
4
4
|
import { validateManagedExtensionContents } from "./extension-dependencies.js";
|
|
5
|
-
import { isObject } from "./source-format.js";
|
|
5
|
+
import { isObject, supportedSourceFormatVersions } from "./source-format.js";
|
|
6
6
|
import { decodeExtensionBytes, expandArchive, formatSourceFiles } from "./expand-archive.js";
|
|
7
7
|
import process from "node:process";
|
|
8
8
|
import path from "node:path";
|
|
@@ -19,7 +19,7 @@ async function authorizeOutputReplacement({ candidateDirectory, confirmReplace,
|
|
|
19
19
|
comparison: null,
|
|
20
20
|
gitState: null
|
|
21
21
|
};
|
|
22
|
-
await assertRecognizedOutputDirectory(outputDirectory,
|
|
22
|
+
await assertRecognizedOutputDirectory(outputDirectory, supportedSourceFormatVersions);
|
|
23
23
|
const comparison = await compareDirectories(outputDirectory, candidateDirectory);
|
|
24
24
|
if (comparison.identical) return {
|
|
25
25
|
action: "unchanged",
|
|
@@ -150,7 +150,8 @@ async function importSb3({ inputPath, outputDirectory, protectedRoot = process.c
|
|
|
150
150
|
} : null,
|
|
151
151
|
inputPath: resolvedInputPath,
|
|
152
152
|
outputDirectory: resolvedOutputDirectory,
|
|
153
|
-
rollbackCleanupWarning
|
|
153
|
+
rollbackCleanupWarning,
|
|
154
|
+
warnings: expanded.blockPaletteWarnings
|
|
154
155
|
};
|
|
155
156
|
}
|
|
156
157
|
//#endregion
|
package/dist/import.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"import.js","names":[],"sources":["../src/import.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\nimport process from 'node:process';\n\nimport {assert} from './assert';\nimport {decodeExtensionBytes, expandArchive, formatSourceFiles} from './expand-archive';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateManagedExtensionContents} from './extension-dependencies';\nimport {\n assertNoInterruptedRollback,\n assertRecognizedOutputDirectory,\n compareDirectories,\n inspectGitOutputState,\n pathExists,\n replaceDirectoryTransactionally,\n validateOutputDirectoryPath,\n} from './output-safety';\nimport type {DirectoryComparison, GitOutputState} from './output-safety';\nimport {isObject, sourceFormatVersion} from './source-format';\nimport type {ExtensionEncoding, ExtensionSource} from './types';\n\nexport {validateOutputDirectoryPath} from './output-safety';\n\nexport interface DecodedExtensionDataUrl {\n encoding: ExtensionEncoding;\n mediaType: string;\n parameters: string[];\n source: Buffer;\n}\n\nexport interface OutputReplacementContext {\n comparison: DirectoryComparison;\n discardLocalChanges: boolean;\n gitState: GitOutputState;\n outputDirectory: string;\n}\n\ninterface OutputReplacementDecision {\n action: 'create' | 'unchanged' | 'replace';\n comparison: DirectoryComparison | null;\n discardLocalChanges?: boolean;\n gitState: GitOutputState | null;\n outputDirectory?: string;\n}\n\nexport interface ImportSb3Options {\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges?: boolean;\n inputPath: string;\n outputDirectory: string;\n protectedRoot?: string;\n yes?: boolean;\n}\n\nexport interface ImportSb3Result {\n archiveEntryCount: number;\n assetCount: number;\n changed: boolean;\n differenceCounts: {added: number; modified: number; removed: number} | null;\n embeddedExtensionCount: number;\n inputPath: string;\n outputDirectory: string;\n rollbackCleanupWarning: string | null;\n}\n\nfunction summarizeGitChanges(gitState: GitOutputState): string {\n const entries = [\n ...gitState.statusEntries,\n ...gitState.untrackedContent.map((entry) => `not tracked: ${entry}`),\n ];\n const visibleEntries = entries.slice(0, 8).join(', ');\n const remainder = entries.length > 8 ? `, and ${entries.length - 8} more` : '';\n return `${visibleEntries}${remainder}`;\n}\n\nasync function authorizeOutputReplacement({\n candidateDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory,\n yes,\n}: {\n candidateDirectory: string;\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges: boolean;\n outputDirectory: string;\n yes: boolean;\n}): Promise<OutputReplacementDecision> {\n await assertNoInterruptedRollback(outputDirectory);\n if (!(await pathExists(outputDirectory))) {\n return {action: 'create', comparison: null, gitState: null};\n }\n\n await assertRecognizedOutputDirectory(outputDirectory, sourceFormatVersion);\n const comparison = await compareDirectories(outputDirectory, candidateDirectory);\n if (comparison.identical) {\n return {action: 'unchanged', comparison, gitState: null};\n }\n\n const gitState = await inspectGitOutputState(outputDirectory, comparison.existingFilePaths);\n assert(\n gitState.managed,\n `Existing output differs from the SB3 candidate but is not tracked by Git: ${outputDirectory}. ` +\n 'Import to a new output directory instead of replacing unrecoverable content.',\n );\n assert(\n gitState.clean || discardLocalChanges,\n `Existing output differs from the SB3 candidate and has uncommitted Git changes: ` +\n `${summarizeGitChanges(gitState)}. Commit or stash them first, or explicitly use ` +\n '--discard-local-changes.',\n );\n\n const context = {\n comparison,\n discardLocalChanges,\n gitState,\n outputDirectory,\n };\n if (yes) {\n return {action: 'replace', ...context};\n }\n assert(\n typeof confirmReplace === 'function',\n `Output directory already exists: ${outputDirectory}. ` +\n 'Refusing to replace differing content without interactive confirmation or --yes.',\n );\n assert(\n await confirmReplace(context),\n 'SB3 import cancelled; the existing output was not changed.',\n );\n return {action: 'replace', ...context};\n}\n\nasync function revalidateOutputReplacement({\n candidateDirectory,\n decision,\n discardLocalChanges,\n outputDirectory,\n}: {\n candidateDirectory: string;\n decision: OutputReplacementContext;\n discardLocalChanges: boolean;\n outputDirectory: string;\n}): Promise<void> {\n const latestComparison = await compareDirectories(outputDirectory, candidateDirectory);\n assert(\n latestComparison.existingFingerprint === decision.comparison.existingFingerprint &&\n latestComparison.candidateFingerprint === decision.comparison.candidateFingerprint,\n 'Output or candidate content changed during SB3 import; refusing to replace it.',\n );\n const latestGitState = await inspectGitOutputState(\n outputDirectory,\n latestComparison.existingFilePaths,\n );\n assert(\n latestGitState.managed,\n 'Output stopped being Git-managed during SB3 import; refusing to replace it.',\n );\n assert(\n latestGitState.fingerprint === decision.gitState.fingerprint,\n 'Git state changed during SB3 import; refusing to replace the output.',\n );\n assert(\n latestGitState.clean || discardLocalChanges,\n 'Output gained uncommitted Git changes during SB3 import; refusing to replace it.',\n );\n}\n\nasync function readExistingExtensionSources(\n outputDirectory: string,\n): Promise<Map<string, ExtensionSource>> {\n if (!(await pathExists(outputDirectory))) {\n return new Map();\n }\n\n const manifestPath = path.join(outputDirectory, 'embedded-extensions.json');\n if (!(await pathExists(manifestPath))) {\n return new Map();\n }\n\n let manifest: unknown;\n try {\n manifest = JSON.parse(await readFile(manifestPath, 'utf8'));\n } catch (error) {\n throw new Error(`Existing embedded extension manifest is not valid JSON: ${manifestPath}`, {\n cause: error,\n });\n }\n assert(\n isObject(manifest) && Array.isArray(manifest.extensions),\n `Existing embedded extension manifest is invalid: ${manifestPath}`,\n );\n\n const sources = new Map<string, ExtensionSource>();\n for (const extension of manifest.extensions as unknown[]) {\n if (\n !isObject(extension) ||\n typeof extension.id !== 'string' ||\n typeof extension.path !== 'string' ||\n extension.source === undefined\n ) {\n continue;\n }\n sources.set(`${extension.id}\\u0000${extension.path}`, extension.source as ExtensionSource);\n }\n return sources;\n}\n\nexport function decodeExtensionDataUrl(dataUrl: unknown): DecodedExtensionDataUrl {\n const decoded = decodeExtensionBytes(dataUrl);\n return {...decoded, source: Buffer.from(decoded.source)};\n}\n\nexport async function importSb3({\n inputPath,\n outputDirectory,\n protectedRoot = process.cwd(),\n discardLocalChanges = false,\n yes = false,\n confirmReplace,\n}: ImportSb3Options): Promise<ImportSb3Result> {\n assert(typeof inputPath === 'string', 'Input SB3 path is required.');\n assert(typeof outputDirectory === 'string', 'SB3 source output directory is required.');\n const resolvedInputPath = path.resolve(inputPath);\n const resolvedOutputDirectory = validateOutputDirectoryPath(outputDirectory, protectedRoot);\n\n const expanded = expandArchive(await readFile(resolvedInputPath));\n const existingSources = await readExistingExtensionSources(resolvedOutputDirectory);\n for (const extension of expanded.embeddedExtensions) {\n const source = existingSources.get(`${extension.id}\\u0000${extension.path}`);\n if (source === undefined) continue;\n extension.source = structuredClone(source);\n validateManagedExtensionContents(extension, expanded.extensionFiles.get(extension.path)!);\n if (extension.source.apiManifest) {\n const contents = await readFile(\n path.join(resolvedOutputDirectory, extension.source.apiManifest.path),\n );\n validateManagedExtensionApiManifest(extension, contents);\n expanded.extensionFiles.set(extension.source.apiManifest.path, contents);\n }\n }\n let decision: OutputReplacementDecision | undefined;\n let rollbackCleanupWarning: string | null = null;\n\n const outputParent = path.dirname(resolvedOutputDirectory);\n await mkdir(outputParent, {recursive: true});\n const temporaryDirectory = await mkdtemp(\n path.join(outputParent, `.${path.basename(resolvedOutputDirectory)}.import-`),\n );\n\n try {\n await mkdir(path.join(temporaryDirectory, 'assets'), {recursive: true});\n await mkdir(path.join(temporaryDirectory, 'extensions'), {recursive: true});\n for (const [name, contents] of formatSourceFiles(expanded)) {\n const outputPath = path.resolve(temporaryDirectory, name);\n assert(\n outputPath.startsWith(`${temporaryDirectory}${path.sep}`),\n `SB3 archive entry escapes the source directory: ${JSON.stringify(name)}`,\n );\n await mkdir(path.dirname(outputPath), {recursive: true});\n await writeFile(outputPath, contents);\n }\n decision = await authorizeOutputReplacement({\n candidateDirectory: temporaryDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n yes,\n });\n if (decision.action === 'unchanged') {\n await rm(temporaryDirectory, {recursive: true, force: true});\n } else {\n if (decision.action === 'replace') {\n await revalidateOutputReplacement({\n candidateDirectory: temporaryDirectory,\n decision: decision as OutputReplacementContext,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n });\n }\n ({rollbackCleanupWarning} = await replaceDirectoryTransactionally(\n temporaryDirectory,\n resolvedOutputDirectory,\n ));\n }\n } catch (error) {\n await rm(temporaryDirectory, {recursive: true, force: true});\n throw error;\n }\n\n return {\n archiveEntryCount: expanded.archiveEntries.length,\n assetCount: expanded.assets.size,\n embeddedExtensionCount: expanded.embeddedExtensions.length,\n changed: decision.action !== 'unchanged',\n differenceCounts: decision.comparison\n ? {\n added: decision.comparison.differences.added.length,\n modified: decision.comparison.differences.modified.length,\n removed: decision.comparison.differences.removed.length,\n }\n : null,\n inputPath: resolvedInputPath,\n outputDirectory: resolvedOutputDirectory,\n rollbackCleanupWarning,\n };\n}\n"],"mappings":";;;;;;;;;;AAmEA,SAAS,oBAAoB,UAAkC;CAC7D,MAAM,UAAU,CACd,GAAG,SAAS,eACZ,GAAG,SAAS,iBAAiB,KAAK,UAAU,gBAAgB,OAAO,CACrE;CAGA,OAAO,GAFgB,QAAQ,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,IAEtC,IADQ,QAAQ,SAAS,IAAI,SAAS,QAAQ,SAAS,EAAE,SAAS;AAE9E;AAEA,eAAe,2BAA2B,EACxC,oBACA,gBACA,qBACA,iBACA,OAOqC;CACrC,MAAM,4BAA4B,eAAe;CACjD,IAAI,CAAE,MAAM,WAAW,eAAe,GACpC,OAAO;EAAC,QAAQ;EAAU,YAAY;EAAM,UAAU;CAAI;CAG5D,MAAM,gCAAgC,iBAAA,CAAoC;CAC1E,MAAM,aAAa,MAAM,mBAAmB,iBAAiB,kBAAkB;CAC/E,IAAI,WAAW,WACb,OAAO;EAAC,QAAQ;EAAa;EAAY,UAAU;CAAI;CAGzD,MAAM,WAAW,MAAM,sBAAsB,iBAAiB,WAAW,iBAAiB;CAC1F,OACE,SAAS,SACT,6EAA6E,gBAAgB,+EAE/F;CACA,O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F;AACF"}
|
|
1
|
+
{"version":3,"file":"import.js","names":[],"sources":["../src/import.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {mkdir, mkdtemp, readFile, rm, writeFile} from 'node:fs/promises';\nimport path from 'node:path';\nimport process from 'node:process';\n\nimport {assert} from './assert';\nimport {decodeExtensionBytes, expandArchive, formatSourceFiles} from './expand-archive';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateManagedExtensionContents} from './extension-dependencies';\nimport {\n assertNoInterruptedRollback,\n assertRecognizedOutputDirectory,\n compareDirectories,\n inspectGitOutputState,\n pathExists,\n replaceDirectoryTransactionally,\n validateOutputDirectoryPath,\n} from './output-safety';\nimport type {DirectoryComparison, GitOutputState} from './output-safety';\nimport {isObject, supportedSourceFormatVersions} from './source-format';\nimport type {ExtensionEncoding, ExtensionSource} from './types';\nimport type {BlockPaletteWarning} from './block-palette';\n\nexport {validateOutputDirectoryPath} from './output-safety';\n\nexport interface DecodedExtensionDataUrl {\n encoding: ExtensionEncoding;\n mediaType: string;\n parameters: string[];\n source: Buffer;\n}\n\nexport interface OutputReplacementContext {\n comparison: DirectoryComparison;\n discardLocalChanges: boolean;\n gitState: GitOutputState;\n outputDirectory: string;\n}\n\ninterface OutputReplacementDecision {\n action: 'create' | 'unchanged' | 'replace';\n comparison: DirectoryComparison | null;\n discardLocalChanges?: boolean;\n gitState: GitOutputState | null;\n outputDirectory?: string;\n}\n\nexport interface ImportSb3Options {\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges?: boolean;\n inputPath: string;\n outputDirectory: string;\n protectedRoot?: string;\n yes?: boolean;\n}\n\nexport interface ImportSb3Result {\n archiveEntryCount: number;\n assetCount: number;\n changed: boolean;\n differenceCounts: {added: number; modified: number; removed: number} | null;\n embeddedExtensionCount: number;\n inputPath: string;\n outputDirectory: string;\n rollbackCleanupWarning: string | null;\n /** Block palette comments that were normalized or kept as plain comments. */\n warnings: BlockPaletteWarning[];\n}\n\nfunction summarizeGitChanges(gitState: GitOutputState): string {\n const entries = [\n ...gitState.statusEntries,\n ...gitState.untrackedContent.map((entry) => `not tracked: ${entry}`),\n ];\n const visibleEntries = entries.slice(0, 8).join(', ');\n const remainder = entries.length > 8 ? `, and ${entries.length - 8} more` : '';\n return `${visibleEntries}${remainder}`;\n}\n\nasync function authorizeOutputReplacement({\n candidateDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory,\n yes,\n}: {\n candidateDirectory: string;\n confirmReplace?: (context: OutputReplacementContext) => boolean | Promise<boolean>;\n discardLocalChanges: boolean;\n outputDirectory: string;\n yes: boolean;\n}): Promise<OutputReplacementDecision> {\n await assertNoInterruptedRollback(outputDirectory);\n if (!(await pathExists(outputDirectory))) {\n return {action: 'create', comparison: null, gitState: null};\n }\n\n await assertRecognizedOutputDirectory(outputDirectory, supportedSourceFormatVersions);\n const comparison = await compareDirectories(outputDirectory, candidateDirectory);\n if (comparison.identical) {\n return {action: 'unchanged', comparison, gitState: null};\n }\n\n const gitState = await inspectGitOutputState(outputDirectory, comparison.existingFilePaths);\n assert(\n gitState.managed,\n `Existing output differs from the SB3 candidate but is not tracked by Git: ${outputDirectory}. ` +\n 'Import to a new output directory instead of replacing unrecoverable content.',\n );\n assert(\n gitState.clean || discardLocalChanges,\n `Existing output differs from the SB3 candidate and has uncommitted Git changes: ` +\n `${summarizeGitChanges(gitState)}. Commit or stash them first, or explicitly use ` +\n '--discard-local-changes.',\n );\n\n const context = {\n comparison,\n discardLocalChanges,\n gitState,\n outputDirectory,\n };\n if (yes) {\n return {action: 'replace', ...context};\n }\n assert(\n typeof confirmReplace === 'function',\n `Output directory already exists: ${outputDirectory}. ` +\n 'Refusing to replace differing content without interactive confirmation or --yes.',\n );\n assert(\n await confirmReplace(context),\n 'SB3 import cancelled; the existing output was not changed.',\n );\n return {action: 'replace', ...context};\n}\n\nasync function revalidateOutputReplacement({\n candidateDirectory,\n decision,\n discardLocalChanges,\n outputDirectory,\n}: {\n candidateDirectory: string;\n decision: OutputReplacementContext;\n discardLocalChanges: boolean;\n outputDirectory: string;\n}): Promise<void> {\n const latestComparison = await compareDirectories(outputDirectory, candidateDirectory);\n assert(\n latestComparison.existingFingerprint === decision.comparison.existingFingerprint &&\n latestComparison.candidateFingerprint === decision.comparison.candidateFingerprint,\n 'Output or candidate content changed during SB3 import; refusing to replace it.',\n );\n const latestGitState = await inspectGitOutputState(\n outputDirectory,\n latestComparison.existingFilePaths,\n );\n assert(\n latestGitState.managed,\n 'Output stopped being Git-managed during SB3 import; refusing to replace it.',\n );\n assert(\n latestGitState.fingerprint === decision.gitState.fingerprint,\n 'Git state changed during SB3 import; refusing to replace the output.',\n );\n assert(\n latestGitState.clean || discardLocalChanges,\n 'Output gained uncommitted Git changes during SB3 import; refusing to replace it.',\n );\n}\n\nasync function readExistingExtensionSources(\n outputDirectory: string,\n): Promise<Map<string, ExtensionSource>> {\n if (!(await pathExists(outputDirectory))) {\n return new Map();\n }\n\n const manifestPath = path.join(outputDirectory, 'embedded-extensions.json');\n if (!(await pathExists(manifestPath))) {\n return new Map();\n }\n\n let manifest: unknown;\n try {\n manifest = JSON.parse(await readFile(manifestPath, 'utf8'));\n } catch (error) {\n throw new Error(`Existing embedded extension manifest is not valid JSON: ${manifestPath}`, {\n cause: error,\n });\n }\n assert(\n isObject(manifest) && Array.isArray(manifest.extensions),\n `Existing embedded extension manifest is invalid: ${manifestPath}`,\n );\n\n const sources = new Map<string, ExtensionSource>();\n for (const extension of manifest.extensions as unknown[]) {\n if (\n !isObject(extension) ||\n typeof extension.id !== 'string' ||\n typeof extension.path !== 'string' ||\n extension.source === undefined\n ) {\n continue;\n }\n sources.set(`${extension.id}\\u0000${extension.path}`, extension.source as ExtensionSource);\n }\n return sources;\n}\n\nexport function decodeExtensionDataUrl(dataUrl: unknown): DecodedExtensionDataUrl {\n const decoded = decodeExtensionBytes(dataUrl);\n return {...decoded, source: Buffer.from(decoded.source)};\n}\n\nexport async function importSb3({\n inputPath,\n outputDirectory,\n protectedRoot = process.cwd(),\n discardLocalChanges = false,\n yes = false,\n confirmReplace,\n}: ImportSb3Options): Promise<ImportSb3Result> {\n assert(typeof inputPath === 'string', 'Input SB3 path is required.');\n assert(typeof outputDirectory === 'string', 'SB3 source output directory is required.');\n const resolvedInputPath = path.resolve(inputPath);\n const resolvedOutputDirectory = validateOutputDirectoryPath(outputDirectory, protectedRoot);\n\n const expanded = expandArchive(await readFile(resolvedInputPath));\n const existingSources = await readExistingExtensionSources(resolvedOutputDirectory);\n for (const extension of expanded.embeddedExtensions) {\n const source = existingSources.get(`${extension.id}\\u0000${extension.path}`);\n if (source === undefined) continue;\n extension.source = structuredClone(source);\n validateManagedExtensionContents(extension, expanded.extensionFiles.get(extension.path)!);\n if (extension.source.apiManifest) {\n const contents = await readFile(\n path.join(resolvedOutputDirectory, extension.source.apiManifest.path),\n );\n validateManagedExtensionApiManifest(extension, contents);\n expanded.extensionFiles.set(extension.source.apiManifest.path, contents);\n }\n }\n let decision: OutputReplacementDecision | undefined;\n let rollbackCleanupWarning: string | null = null;\n\n const outputParent = path.dirname(resolvedOutputDirectory);\n await mkdir(outputParent, {recursive: true});\n const temporaryDirectory = await mkdtemp(\n path.join(outputParent, `.${path.basename(resolvedOutputDirectory)}.import-`),\n );\n\n try {\n await mkdir(path.join(temporaryDirectory, 'assets'), {recursive: true});\n await mkdir(path.join(temporaryDirectory, 'extensions'), {recursive: true});\n for (const [name, contents] of formatSourceFiles(expanded)) {\n const outputPath = path.resolve(temporaryDirectory, name);\n assert(\n outputPath.startsWith(`${temporaryDirectory}${path.sep}`),\n `SB3 archive entry escapes the source directory: ${JSON.stringify(name)}`,\n );\n await mkdir(path.dirname(outputPath), {recursive: true});\n await writeFile(outputPath, contents);\n }\n decision = await authorizeOutputReplacement({\n candidateDirectory: temporaryDirectory,\n confirmReplace,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n yes,\n });\n if (decision.action === 'unchanged') {\n await rm(temporaryDirectory, {recursive: true, force: true});\n } else {\n if (decision.action === 'replace') {\n await revalidateOutputReplacement({\n candidateDirectory: temporaryDirectory,\n decision: decision as OutputReplacementContext,\n discardLocalChanges,\n outputDirectory: resolvedOutputDirectory,\n });\n }\n ({rollbackCleanupWarning} = await replaceDirectoryTransactionally(\n temporaryDirectory,\n resolvedOutputDirectory,\n ));\n }\n } catch (error) {\n await rm(temporaryDirectory, {recursive: true, force: true});\n throw error;\n }\n\n return {\n archiveEntryCount: expanded.archiveEntries.length,\n assetCount: expanded.assets.size,\n embeddedExtensionCount: expanded.embeddedExtensions.length,\n changed: decision.action !== 'unchanged',\n differenceCounts: decision.comparison\n ? {\n added: decision.comparison.differences.added.length,\n modified: decision.comparison.differences.modified.length,\n removed: decision.comparison.differences.removed.length,\n }\n : null,\n inputPath: resolvedInputPath,\n outputDirectory: resolvedOutputDirectory,\n rollbackCleanupWarning,\n warnings: expanded.blockPaletteWarnings,\n };\n}\n"],"mappings":";;;;;;;;;;AAsEA,SAAS,oBAAoB,UAAkC;CAC7D,MAAM,UAAU,CACd,GAAG,SAAS,eACZ,GAAG,SAAS,iBAAiB,KAAK,UAAU,gBAAgB,OAAO,CACrE;CAGA,OAAO,GAFgB,QAAQ,MAAM,GAAG,CAAC,CAAC,CAAC,KAAK,IAEtC,IADQ,QAAQ,SAAS,IAAI,SAAS,QAAQ,SAAS,EAAE,SAAS;AAE9E;AAEA,eAAe,2BAA2B,EACxC,oBACA,gBACA,qBACA,iBACA,OAOqC;CACrC,MAAM,4BAA4B,eAAe;CACjD,IAAI,CAAE,MAAM,WAAW,eAAe,GACpC,OAAO;EAAC,QAAQ;EAAU,YAAY;EAAM,UAAU;CAAI;CAG5D,MAAM,gCAAgC,iBAAiB,6BAA6B;CACpF,MAAM,aAAa,MAAM,mBAAmB,iBAAiB,kBAAkB;CAC/E,IAAI,WAAW,WACb,OAAO;EAAC,QAAQ;EAAa;EAAY,UAAU;CAAI;CAGzD,MAAM,WAAW,MAAM,sB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;GACnD,SAAS,SAAS,WAAW,YAAY,QAAQ;EACnD,IACA;EACJ,WAAW;EACX,iBAAiB;EACjB;EACA,UAAU,SAAS;CACrB;AACF"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,40 +1,42 @@
|
|
|
1
|
-
export type { EmbeddedExtension, EmbeddedExtensionManifest, ExtensionApiManifestSource, ExtensionBundleConfiguration, ExtensionBundleMetadata, ExtensionEncoding, ExtensionModuleSource, ExtensionSource, GitHubExtensionSource, NpmExtensionSource, ProjectAssetReference, ProjectJson, ProjectTarget, Sb3SourceManifest, } from './types';
|
|
2
|
-
export { assert } from './assert';
|
|
3
|
-
export { validateArchiveEntryName } from './archive';
|
|
4
|
-
export {
|
|
5
|
-
export {
|
|
6
|
-
export
|
|
7
|
-
export {
|
|
8
|
-
export {
|
|
9
|
-
export {
|
|
10
|
-
export {
|
|
11
|
-
export {
|
|
12
|
-
export {
|
|
13
|
-
export
|
|
14
|
-
export {
|
|
15
|
-
export {
|
|
16
|
-
export
|
|
17
|
-
export {
|
|
18
|
-
export {
|
|
19
|
-
export {
|
|
20
|
-
export {
|
|
21
|
-
export {
|
|
22
|
-
export {
|
|
23
|
-
export {
|
|
24
|
-
export {
|
|
25
|
-
export
|
|
26
|
-
export
|
|
27
|
-
export type {
|
|
28
|
-
export type {
|
|
29
|
-
export type {
|
|
30
|
-
export type {
|
|
31
|
-
export type {
|
|
32
|
-
export type {
|
|
33
|
-
export type {
|
|
34
|
-
export type {
|
|
35
|
-
export type {
|
|
36
|
-
export type {
|
|
37
|
-
export type {
|
|
38
|
-
export type {
|
|
39
|
-
export {
|
|
40
|
-
export type {
|
|
1
|
+
export type { EmbeddedExtension, EmbeddedExtensionManifest, ExtensionApiManifestSource, ExtensionBundleConfiguration, ExtensionBundleMetadata, ExtensionEncoding, ExtensionModuleSource, ExtensionSource, GitHubExtensionSource, NpmExtensionSource, ProjectAssetReference, ProjectJson, ProjectTarget, Sb3SourceManifest, } from './types.js';
|
|
2
|
+
export { assert } from './assert.js';
|
|
3
|
+
export { validateArchiveEntryName } from './archive.js';
|
|
4
|
+
export { applyBlockPaletteComments, blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, extractBlockPalette, formatBlockPaletteComment, hasBlockPaletteSettings, resolveBlockPaletteReferences, serializeBlockPaletteDocument, validateBlockPaletteDocument, } from './block-palette.js';
|
|
5
|
+
export type { BlockPaletteDocument, BlockPaletteSet, BlockPaletteTargetSetting, BlockPaletteWarning, BlockPaletteWarningCode, } from './block-palette.js';
|
|
6
|
+
export { buildSb3 } from './build.js';
|
|
7
|
+
export { cleanUpSb3, cleanUpSb3Archive } from './clean-up-sb3.js';
|
|
8
|
+
export type { CleanUpSb3ArchiveResult, CleanUpSb3Options, CleanUpSb3Result } from './clean-up-sb3.js';
|
|
9
|
+
export { packageName, packageVersion } from './constants.js';
|
|
10
|
+
export { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, unsandboxedRequirement, unsandboxedRequirements, validateExtensionSourceMetadata, validateManagedExtensionContents, } from './extension-dependencies.js';
|
|
11
|
+
export { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, formatExtensionApiCompatibilityChanges, parseExtensionApiManifest, tryParseExtensionApiManifest, validateExtensionApiManifestSourceMetadata, validateManagedExtensionApiManifest, } from './extension-api-manifest.js';
|
|
12
|
+
export { bundleExtensions, planExtensionBundle, planExtensionUnbundle, unbundleExtensions, } from './extension-bundle-configuration.js';
|
|
13
|
+
export { planBundledSb3Unbundle, unbundleSb3 } from './extension-bundle-archive.js';
|
|
14
|
+
export { extensionSourceTypes, formatExtensionDigestInventory, inspectSb3ExtensionDigests, inventoryExtensionDigests, projectManifestKey, readProjectManifest, } from './extension-digest-inventory.js';
|
|
15
|
+
export type { ExtensionDigestEntry, ExtensionDigestInventory, ExtensionDigestUsage, ExtensionExecutionMode, ExtensionSourceType, Sb3ExtensionDigests, } from './extension-digest-inventory.js';
|
|
16
|
+
export { buildExtensionBundles, createStaticExtensionBundle, bundleUnsandboxedRequirement, defaultSandboxedNotices, extensionBundleRecoveryMarker, validateExtensionBundleConfigurations, } from './extension-bundle.js';
|
|
17
|
+
export { buildExtensionBundlesWithModules } from './extension-module-bundle.js';
|
|
18
|
+
export type { ExtensionModuleBuildReport } from './extension-module-bundle.js';
|
|
19
|
+
export { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId, } from './extension-id-migration.js';
|
|
20
|
+
export { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions, } from './extension-sync.js';
|
|
21
|
+
export { decodeExtensionDataUrl, importSb3 } from './import.js';
|
|
22
|
+
export { compareDirectories, inspectGitOutputState, validateOutputDirectoryPath, } from './output-safety.js';
|
|
23
|
+
export { createDeterministicSb3, blockPaletteSourceFormatVersion, fixedZipTimestamp, sourceFormatVersion, supportedSourceFormatVersions, validateSb3Source, } from './source.js';
|
|
24
|
+
export { applyProjectAssetAdditions, projectAssetAdditionsFormatVersion, } from './project-asset-additions.js';
|
|
25
|
+
export { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate, } from './release-snapshot.js';
|
|
26
|
+
export { cleanUpTurboWarpBlocks, turboWarpCleanUpLayout } from './turbowarp-clean-up.js';
|
|
27
|
+
export type { BuildSb3Options, WriteSb3ArchiveOptions, WriteSb3ArchiveResult } from './build.js';
|
|
28
|
+
export type { CliOptions } from './cli.js';
|
|
29
|
+
export type { ExtensionApiCompatibilityChange, ExtensionApiManifest, ExtensionApiManifestArgument, ExtensionApiManifestBlock, ExtensionApiManifestDataReferenceType, ExtensionApiManifestEffect, ExtensionApiManifestFormatVersion, ExtensionApiManifestMenu, ExtensionApiManifestParseFailure, ExtensionApiManifestParseResult, ExtensionApiManifestParseSuccess, ExtensionApiManifestPathSegmentType, ExtensionApiManifestResultType, ExtensionApiManifestServer, } from './extension-api-manifest.js';
|
|
30
|
+
export type { BuildExtensionBundlesResult, ExtensionBundleComponent, ExtensionBundleCounts, ExtensionBundlePlan, } from './extension-bundle.js';
|
|
31
|
+
export type { BundledSb3UnbundlePlan } from './extension-bundle-archive.js';
|
|
32
|
+
export type { ExtensionHeaderMetadata, UnsandboxedRequirement } from './extension-dependencies.js';
|
|
33
|
+
export type { ExtensionIdMigrationCounts, ExtensionIdReference, RewriteExtensionIdDocumentsResult, } from './extension-id-migration.js';
|
|
34
|
+
export type { ExtensionSyncConfirmContext, SyncExtensionsOptions, UpdateExtensionsOptions, } from './extension-sync.js';
|
|
35
|
+
export type { DecodedExtensionDataUrl, ImportSb3Options, ImportSb3Result, OutputReplacementContext, } from './import.js';
|
|
36
|
+
export type { DirectoryComparison, DirectoryDifferences, GitOutputState } from './output-safety.js';
|
|
37
|
+
export type { ProjectAssetAdditionsSummary } from './project-asset-additions.js';
|
|
38
|
+
export type { Sb3ReleaseSnapshotMetadata } from './release-snapshot.js';
|
|
39
|
+
export type { DeterministicSb3, InspectedSb3Source } from './source.js';
|
|
40
|
+
export type { TurboWarpCleanUpResult } from './turbowarp-clean-up.js';
|
|
41
|
+
export { defaultKamishibaiManifestUrl, kamishibaiReplacementIds, replaceSb3Extensions, } from './extension-sb3-replacement.js';
|
|
42
|
+
export type { ReplaceSb3ExtensionsOptions, ReplaceSb3ExtensionsResult, } from './extension-sb3-replacement.js';
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { assert } from "./assert.js";
|
|
2
2
|
import { compareDirectories, inspectGitOutputState, validateOutputDirectoryPath } from "./output-safety.js";
|
|
3
|
+
import { applyBlockPaletteComments, blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, extractBlockPalette, formatBlockPaletteComment, hasBlockPaletteSettings, resolveBlockPaletteReferences, serializeBlockPaletteDocument, validateBlockPaletteDocument } from "./block-palette.js";
|
|
3
4
|
import { validateArchiveEntryName } from "./archive.js";
|
|
4
5
|
import { compareExtensionApiManifests, defaultExtensionApiManifestSizeLimit, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, formatExtensionApiCompatibilityChanges, parseExtensionApiManifest, tryParseExtensionApiManifest, validateExtensionApiManifestSourceMetadata, validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
|
|
5
6
|
import { extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, unsandboxedRequirement, unsandboxedRequirements, validateExtensionSourceMetadata, validateManagedExtensionContents } from "./extension-dependencies.js";
|
|
@@ -7,7 +8,7 @@ import { buildExtensionBundles, bundleUnsandboxedRequirement, createStaticExtens
|
|
|
7
8
|
import { buildExtensionBundlesWithModules } from "./extension-module-bundle.js";
|
|
8
9
|
import { applyProjectAssetAdditions, projectAssetAdditionsFormatVersion } from "./project-asset-additions.js";
|
|
9
10
|
import { cleanUpTurboWarpBlocks, turboWarpCleanUpLayout } from "./turbowarp-clean-up.js";
|
|
10
|
-
import { sourceFormatVersion } from "./source-format.js";
|
|
11
|
+
import { blockPaletteSourceFormatVersion, sourceFormatVersion, supportedSourceFormatVersions } from "./source-format.js";
|
|
11
12
|
import { createDeterministicSb3, fixedZipTimestamp, validateSb3Source } from "./source.js";
|
|
12
13
|
import { buildSb3 } from "./build.js";
|
|
13
14
|
import { cleanUpSb3, cleanUpSb3Archive } from "./clean-up-sb3.js";
|
|
@@ -20,4 +21,4 @@ import { migrateExtensionId, planExtensionIdMigration, validateNewExtensionId }
|
|
|
20
21
|
import { defaultKamishibaiManifestUrl, kamishibaiReplacementIds, replaceSb3Extensions } from "./extension-sb3-replacement.js";
|
|
21
22
|
import { defaultExtensionArtifactSizeLimit, extensionStatus, syncExtensions, updateExtensions } from "./extension-sync.js";
|
|
22
23
|
import { assertSb3ReleaseSnapshotMetadata, computeReleaseSourceIdentity, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, freezeSb3ReleaseSnapshot, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate } from "./release-snapshot.js";
|
|
23
|
-
export { applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, buildExtensionBundles, buildExtensionBundlesWithModules, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpSb3, cleanUpSb3Archive, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultKamishibaiManifestUrl, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionSourceTypes, extensionStatus, fixedZipTimestamp, formatExtensionApiCompatibilityChanges, formatExtensionDigestInventory, freezeSb3ReleaseSnapshot, importSb3, inspectGitOutputState, inspectSb3ExtensionDigests, inventoryExtensionDigests, kamishibaiReplacementIds, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, projectManifestKey, readProjectManifest, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, replaceSb3Extensions, sourceFormatVersion, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
|
|
24
|
+
export { applyBlockPaletteComments, applyProjectAssetAdditions, assert, assertSb3ReleaseSnapshotMetadata, blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSourceFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, buildExtensionBundles, buildExtensionBundlesWithModules, buildSb3, bundleExtensions, bundleUnsandboxedRequirement, cleanUpSb3, cleanUpSb3Archive, cleanUpTurboWarpBlocks, compareDirectories, compareExtensionApiManifests, computeReleaseSourceIdentity, createDeterministicSb3, createSb3ReleaseSnapshot, createSb3ReleaseSnapshotMetadata, createStaticExtensionBundle, decodeExtensionDataUrl, defaultExtensionApiManifestSizeLimit, defaultExtensionArtifactSizeLimit, defaultKamishibaiManifestUrl, defaultSandboxedNotices, extensionApiManifestEffects, extensionApiManifestFormatVersion, extensionApiManifestFormatVersions, extensionApiManifestIntegrity, extensionApiManifestLocalPath, extensionApiManifestResultTypes, extensionBundleRecoveryMarker, extensionHeaderId, extensionHeaderMetadata, extensionIntegrity, extensionSourceTypes, extensionStatus, extractBlockPalette, fixedZipTimestamp, formatBlockPaletteComment, formatExtensionApiCompatibilityChanges, formatExtensionDigestInventory, freezeSb3ReleaseSnapshot, hasBlockPaletteSettings, importSb3, inspectGitOutputState, inspectSb3ExtensionDigests, inventoryExtensionDigests, kamishibaiReplacementIds, migrateExtensionId, packageName, packageVersion, parseExtensionApiManifest, planBundledSb3Unbundle, planExtensionBundle, planExtensionIdMigration, planExtensionUnbundle, projectAssetAdditionsFormatVersion, projectManifestKey, readProjectManifest, readSb3ReleaseSnapshotMetadata, recordPublishedSb3ReleaseSnapshot, replaceSb3Extensions, resolveBlockPaletteReferences, serializeBlockPaletteDocument, sourceFormatVersion, supportedSourceFormatVersions, syncExtensions, tryParseExtensionApiManifest, turboWarpCleanUpLayout, unbundleExtensions, unbundleSb3, unsandboxedRequirement, unsandboxedRequirements, updateExtensions, validateArchiveEntryName, validateBlockPaletteDocument, validateExtensionApiManifestSourceMetadata, validateExtensionBundleConfigurations, validateExtensionSourceMetadata, validateManagedExtensionApiManifest, validateManagedExtensionContents, validateNewExtensionId, validateOutputDirectoryPath, validateSb3Source, verifySb3ReleaseSnapshot, writeSb3ReleaseCandidate };
|
package/dist/output-safety.d.ts
CHANGED
|
@@ -20,7 +20,7 @@ export interface GitOutputState {
|
|
|
20
20
|
}
|
|
21
21
|
export declare function pathExists(targetPath: string): Promise<boolean>;
|
|
22
22
|
export declare function validateOutputDirectoryPath(outputDirectory: string, protectedRoot: string): string;
|
|
23
|
-
export declare function assertRecognizedOutputDirectory(outputDirectory: string,
|
|
23
|
+
export declare function assertRecognizedOutputDirectory(outputDirectory: string, sourceFormatVersions: readonly number[]): Promise<void>;
|
|
24
24
|
export declare function compareDirectories(existingDirectory: string, candidateDirectory: string): Promise<DirectoryComparison>;
|
|
25
25
|
export declare function inspectGitOutputState(outputDirectory: string, existingFilePaths: string[]): Promise<GitOutputState>;
|
|
26
26
|
export declare function assertNoInterruptedRollback(outputDirectory: string): Promise<void>;
|
package/dist/output-safety.js
CHANGED
|
@@ -28,7 +28,7 @@ function validateOutputDirectoryPath(outputDirectory, protectedRoot) {
|
|
|
28
28
|
assert(!resolvedOutputDirectory.split(path.sep).includes(".git"), "Refusing to write imported SB3 sources into a .git directory.");
|
|
29
29
|
return resolvedOutputDirectory;
|
|
30
30
|
}
|
|
31
|
-
async function assertRecognizedOutputDirectory(outputDirectory,
|
|
31
|
+
async function assertRecognizedOutputDirectory(outputDirectory, sourceFormatVersions) {
|
|
32
32
|
const stats = await lstat(outputDirectory);
|
|
33
33
|
assert(stats.isDirectory() && !stats.isSymbolicLink(), `Refusing to replace a non-directory or symbolic link: ${outputDirectory}`);
|
|
34
34
|
let manifest;
|
|
@@ -38,7 +38,7 @@ async function assertRecognizedOutputDirectory(outputDirectory, sourceFormatVers
|
|
|
38
38
|
if (errorCode(error) !== "ENOENT" && !(error instanceof SyntaxError)) throw error;
|
|
39
39
|
throw new Error(`Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`, { cause: error });
|
|
40
40
|
}
|
|
41
|
-
assert(manifest
|
|
41
|
+
assert(manifest !== null && sourceFormatVersions.includes(manifest.formatVersion) && manifest.project === "project.source.json" && manifest.embeddedExtensions === "embedded-extensions.json" && manifest.assetsDirectory === "assets" && Array.isArray(manifest.archiveEntries), `Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`);
|
|
42
42
|
}
|
|
43
43
|
function digest(value) {
|
|
44
44
|
return createHash("sha256").update(value).digest("hex");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"output-safety.js","names":[],"sources":["../src/output-safety.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {execFile} from 'node:child_process';\nimport {createHash, randomUUID} from 'node:crypto';\nimport {access, lstat, realpath, readdir, readFile, readlink, rename, rm} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert, errorMessage} from './assert';\n\ntype SnapshotEntry =\n | {type: 'directory'}\n | {type: 'file'; size: number; digest: string}\n | {type: 'symbolic-link'; target: string}\n | {type: 'other'};\n\nexport interface DirectoryDifferences {\n added: string[];\n modified: string[];\n removed: string[];\n}\n\nexport interface DirectoryComparison {\n candidateFingerprint: string;\n differences: DirectoryDifferences;\n existingFilePaths: string[];\n existingFingerprint: string;\n identical: boolean;\n}\n\nexport interface GitOutputState {\n clean: boolean;\n fingerprint: string;\n managed: boolean;\n repositoryRoot: string | null;\n statusEntries: string[];\n untrackedContent: string[];\n}\n\nfunction errorCode(error: unknown): string | number | undefined {\n return (error as NodeJS.ErrnoException | null)?.code;\n}\n\nexport async function pathExists(targetPath: string): Promise<boolean> {\n try {\n await access(targetPath);\n return true;\n } catch (error) {\n if (errorCode(error) === 'ENOENT') {\n return false;\n }\n throw error;\n }\n}\n\nfunction isSamePathOrAncestor(candidatePath: string, targetPath: string): boolean {\n const relativePath = path.relative(candidatePath, targetPath);\n return (\n relativePath === '' ||\n (relativePath !== '..' &&\n !relativePath.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relativePath))\n );\n}\n\nexport function validateOutputDirectoryPath(\n outputDirectory: string,\n protectedRoot: string,\n): string {\n const resolvedOutputDirectory = path.resolve(outputDirectory);\n const resolvedProtectedRoot = path.resolve(protectedRoot);\n assert(\n resolvedOutputDirectory !== path.parse(resolvedOutputDirectory).root,\n 'Refusing to replace a filesystem root with imported SB3 sources.',\n );\n assert(\n !isSamePathOrAncestor(resolvedOutputDirectory, resolvedProtectedRoot),\n 'Refusing to replace the repository root or one of its ancestors.',\n );\n assert(\n !resolvedOutputDirectory.split(path.sep).includes('.git'),\n 'Refusing to write imported SB3 sources into a .git directory.',\n );\n return resolvedOutputDirectory;\n}\n\nexport async function assertRecognizedOutputDirectory(\n outputDirectory: string,\n sourceFormatVersion: number,\n): Promise<void> {\n const stats = await lstat(outputDirectory);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `Refusing to replace a non-directory or symbolic link: ${outputDirectory}`,\n );\n\n let manifest: Record<string, unknown> | null;\n try {\n manifest = JSON.parse(await readFile(path.join(outputDirectory, 'sb3-source.json'), 'utf8'));\n } catch (error) {\n if (errorCode(error) !== 'ENOENT' && !(error instanceof SyntaxError)) {\n throw error;\n }\n throw new Error(\n `Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`,\n {cause: error},\n );\n }\n\n assert(\n manifest?.formatVersion === sourceFormatVersion &&\n manifest.project === 'project.source.json' &&\n manifest.embeddedExtensions === 'embedded-extensions.json' &&\n manifest.assetsDirectory === 'assets' &&\n Array.isArray(manifest.archiveEntries),\n `Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`,\n );\n}\n\nfunction digest(value: Uint8Array | string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nasync function snapshotDirectory(rootDirectory: string): Promise<Map<string, SnapshotEntry>> {\n const snapshot = new Map<string, SnapshotEntry>();\n\n async function visit(directory: string, relativeDirectory: string): Promise<void> {\n const entries = await readdir(directory, {withFileTypes: true});\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n\n for (const entry of entries) {\n const relativePath = relativeDirectory\n ? path.posix.join(relativeDirectory, entry.name)\n : entry.name;\n const absolutePath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n snapshot.set(relativePath, {type: 'directory'});\n await visit(absolutePath, relativePath);\n } else if (entry.isFile()) {\n const contents = await readFile(absolutePath);\n snapshot.set(relativePath, {\n type: 'file',\n size: contents.length,\n digest: digest(contents),\n });\n } else if (entry.isSymbolicLink()) {\n snapshot.set(relativePath, {\n type: 'symbolic-link',\n target: await readlink(absolutePath),\n });\n } else {\n snapshot.set(relativePath, {type: 'other'});\n }\n }\n }\n\n await visit(rootDirectory, '');\n return snapshot;\n}\n\nfunction snapshotFingerprint(snapshot: Map<string, SnapshotEntry>): string {\n return digest(JSON.stringify([...snapshot.entries()]));\n}\n\nfunction entriesMatch(left: SnapshotEntry, right: SnapshotEntry): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport async function compareDirectories(\n existingDirectory: string,\n candidateDirectory: string,\n): Promise<DirectoryComparison> {\n const [existingSnapshot, candidateSnapshot] = await Promise.all([\n snapshotDirectory(existingDirectory),\n snapshotDirectory(candidateDirectory),\n ]);\n const paths = [...new Set([...existingSnapshot.keys(), ...candidateSnapshot.keys()])].sort();\n const differences: DirectoryDifferences = {added: [], modified: [], removed: []};\n\n for (const relativePath of paths) {\n const existingEntry = existingSnapshot.get(relativePath);\n const candidateEntry = candidateSnapshot.get(relativePath);\n if (!existingEntry) {\n differences.added.push(relativePath);\n } else if (!candidateEntry) {\n differences.removed.push(relativePath);\n } else if (!entriesMatch(existingEntry, candidateEntry)) {\n differences.modified.push(relativePath);\n }\n }\n\n return {\n candidateFingerprint: snapshotFingerprint(candidateSnapshot),\n differences,\n existingFilePaths: [...existingSnapshot.entries()]\n .filter(([, entry]) => entry.type !== 'directory')\n .map(([relativePath]) => relativePath),\n existingFingerprint: snapshotFingerprint(existingSnapshot),\n identical: Object.values(differences).every((entries) => entries.length === 0),\n };\n}\n\nfunction executeGit(arguments_: string[], cwd: string): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n execFile(\n 'git',\n arguments_,\n {cwd, encoding: 'utf8', maxBuffer: 10 * 1024 * 1024},\n (error, stdout, stderr) => {\n if (error) {\n Object.assign(error, {stdout, stderr});\n reject(error);\n return;\n }\n resolve(stdout);\n },\n );\n });\n}\n\nfunction toPosixPath(value: string): string {\n return value.split(path.sep).join('/');\n}\n\nexport async function inspectGitOutputState(\n outputDirectory: string,\n existingFilePaths: string[],\n): Promise<GitOutputState> {\n let repositoryRoot: string;\n try {\n repositoryRoot = (await executeGit(['rev-parse', '--show-toplevel'], outputDirectory)).trim();\n } catch (error) {\n if (errorCode(error) === 128) {\n return {\n clean: false,\n fingerprint: 'not-git-managed',\n managed: false,\n repositoryRoot: null,\n statusEntries: [],\n untrackedContent: [...existingFilePaths],\n };\n }\n throw error;\n }\n\n const [canonicalOutputDirectory, canonicalRepositoryRoot] = await Promise.all([\n realpath(outputDirectory),\n realpath(repositoryRoot),\n ]);\n repositoryRoot = canonicalRepositoryRoot;\n const relativeOutputDirectory = path.relative(repositoryRoot, canonicalOutputDirectory);\n assert(\n relativeOutputDirectory !== '..' &&\n !relativeOutputDirectory.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relativeOutputDirectory),\n `Output directory is outside its detected Git worktree: ${outputDirectory}`,\n );\n const pathspec = relativeOutputDirectory || '.';\n const [statusOutput, trackedOutput] = await Promise.all([\n executeGit(\n ['status', '--porcelain=v1', '--untracked-files=all', '--', pathspec],\n repositoryRoot,\n ),\n executeGit(['ls-files', '-z', '--', pathspec], repositoryRoot),\n ]);\n const statusEntries = statusOutput.split('\\n').filter(Boolean);\n const trackedPaths = new Set(\n trackedOutput\n .split('\\0')\n .filter(Boolean)\n .map((trackedPath) =>\n toPosixPath(\n path.relative(canonicalOutputDirectory, path.join(repositoryRoot, trackedPath)),\n ),\n ),\n );\n const untrackedContent = existingFilePaths.filter((filePath) => !trackedPaths.has(filePath));\n const managed = trackedPaths.size > 0;\n const clean = managed && statusEntries.length === 0 && untrackedContent.length === 0;\n const fingerprint = digest(\n JSON.stringify({\n clean,\n managed,\n repositoryRoot,\n statusEntries,\n trackedPaths: [...trackedPaths].sort(),\n untrackedContent: [...untrackedContent].sort(),\n }),\n );\n\n return {\n clean,\n fingerprint,\n managed,\n repositoryRoot,\n statusEntries,\n untrackedContent,\n };\n}\n\nexport async function assertNoInterruptedRollback(outputDirectory: string): Promise<void> {\n const parentDirectory = path.dirname(outputDirectory);\n const outputName = path.basename(outputDirectory);\n const rollbackPrefixes = [`.${outputName}.rollback-`, `.${outputName}.backup-`];\n const leftovers = (await readdir(parentDirectory))\n .filter((entryName) => rollbackPrefixes.some((prefix) => entryName.startsWith(prefix)))\n .map((entryName) => path.join(parentDirectory, entryName));\n assert(\n leftovers.length === 0,\n `Found an interrupted SB3 import rollback directory. ` +\n `Inspect or restore it before retrying: ${leftovers.join(', ')}`,\n );\n}\n\nexport async function replaceDirectoryTransactionally(\n temporaryDirectory: string,\n outputDirectory: string,\n): Promise<{rollbackCleanupWarning: string | null}> {\n const parentDirectory = path.dirname(outputDirectory);\n await assertNoInterruptedRollback(outputDirectory);\n const rollbackDirectory = path.join(\n parentDirectory,\n `.${path.basename(outputDirectory)}.rollback-${randomUUID()}`,\n );\n assert(\n !(await pathExists(rollbackDirectory)),\n `Refusing to overwrite an existing rollback directory: ${rollbackDirectory}`,\n );\n const outputExists = await pathExists(outputDirectory);\n\n if (outputExists) {\n await rename(outputDirectory, rollbackDirectory);\n }\n\n try {\n await rename(temporaryDirectory, outputDirectory);\n } catch (installError) {\n if (outputExists) {\n try {\n await rename(rollbackDirectory, outputDirectory);\n } catch (restoreError) {\n throw new AggregateError(\n [installError, restoreError],\n `SB3 import failed and automatic restoration also failed. ` +\n `Original output remains at: ${rollbackDirectory}`,\n );\n }\n }\n throw installError;\n }\n\n if (!outputExists) {\n return {rollbackCleanupWarning: null};\n }\n\n try {\n await rm(rollbackDirectory, {recursive: true});\n return {rollbackCleanupWarning: null};\n } catch (error) {\n return {\n rollbackCleanupWarning:\n `Imported output was installed, but its temporary rollback ` +\n `directory could not be removed: ${rollbackDirectory} (${errorMessage(error)})`,\n };\n }\n}\n"],"mappings":";;;;;;AAsCA,SAAS,UAAU,OAA6C;CAC9D,OAAQ,OAAwC;AAClD;AAEA,eAAsB,WAAW,YAAsC;CACrE,IAAI;EACF,MAAM,OAAO,UAAU;EACvB,OAAO;CACT,SAAS,OAAO;EACd,IAAI,UAAU,KAAK,MAAM,UACvB,OAAO;EAET,MAAM;CACR;AACF;AAEA,SAAS,qBAAqB,eAAuB,YAA6B;CAChF,MAAM,eAAe,KAAK,SAAS,eAAe,UAAU;CAC5D,OACE,iBAAiB,MAChB,iBAAiB,QAChB,CAAC,aAAa,WAAW,KAAK,KAAK,KAAK,KACxC,CAAC,KAAK,WAAW,YAAY;AAEnC;AAEA,SAAgB,4BACd,iBACA,eACQ;CACR,MAAM,0BAA0B,KAAK,QAAQ,eAAe;CAC5D,MAAM,wBAAwB,KAAK,QAAQ,aAAa;CACxD,OACE,4BAA4B,KAAK,MAAM,uBAAuB,CAAC,CAAC,MAChE,kEACF;CACA,OACE,CAAC,qBAAqB,yBAAyB,qBAAqB,GACpE,kEACF;CACA,OACE,CAA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OACE,UAAU,WAAW,GACrB,8FAC4C,UAAU,KAAK,IAAI,GACjE;AACF;AAEA,eAAsB,gCACpB,oBACA,iBACkD;CAClD,MAAM,kBAAkB,KAAK,QAAQ,eAAe;CACpD,MAAM,4BAA4B,eAAe;CACjD,MAAM,oBAAoB,KAAK,KAC7B,iBACA,IAAI,KAAK,SAAS,eAAe,EAAE,YAAY,WAAW,GAC5D;CACA,OACE,CAAE,MAAM,WAAW,iBAAiB,GACpC,yDAAyD,mBAC3D;CACA,MAAM,eAAe,MAAM,WAAW,eAAe;CAErD,IAAI,cACF,MAAM,OAAO,iBAAiB,iBAAiB;CAGjD,IAAI;EACF,MAAM,OAAO,oBAAoB,eAAe;CAClD,SAAS,cAAc;EACrB,IAAI,cACF,IAAI;GACF,MAAM,OAAO,mBAAmB,eAAe;EACjD,SAAS,cAAc;GACrB,MAAM,IAAI,eACR,CAAC,cAAc,YAAY,GAC3B,wFACiC,mBACnC;EACF;EAEF,MAAM;CACR;CAEA,IAAI,CAAC,cACH,OAAO,EAAC,wBAAwB,KAAI;CAGtC,IAAI;EACF,MAAM,GAAG,mBAAmB,EAAC,WAAW,KAAI,CAAC;EAC7C,OAAO,EAAC,wBAAwB,KAAI;CACtC,SAAS,OAAO;EACd,OAAO,EACL,wBACE,6FACmC,kBAAkB,IAAI,aAAa,KAAK,EAAE,GACjF;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"output-safety.js","names":[],"sources":["../src/output-safety.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {execFile} from 'node:child_process';\nimport {createHash, randomUUID} from 'node:crypto';\nimport {access, lstat, realpath, readdir, readFile, readlink, rename, rm} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {assert, errorMessage} from './assert';\n\ntype SnapshotEntry =\n | {type: 'directory'}\n | {type: 'file'; size: number; digest: string}\n | {type: 'symbolic-link'; target: string}\n | {type: 'other'};\n\nexport interface DirectoryDifferences {\n added: string[];\n modified: string[];\n removed: string[];\n}\n\nexport interface DirectoryComparison {\n candidateFingerprint: string;\n differences: DirectoryDifferences;\n existingFilePaths: string[];\n existingFingerprint: string;\n identical: boolean;\n}\n\nexport interface GitOutputState {\n clean: boolean;\n fingerprint: string;\n managed: boolean;\n repositoryRoot: string | null;\n statusEntries: string[];\n untrackedContent: string[];\n}\n\nfunction errorCode(error: unknown): string | number | undefined {\n return (error as NodeJS.ErrnoException | null)?.code;\n}\n\nexport async function pathExists(targetPath: string): Promise<boolean> {\n try {\n await access(targetPath);\n return true;\n } catch (error) {\n if (errorCode(error) === 'ENOENT') {\n return false;\n }\n throw error;\n }\n}\n\nfunction isSamePathOrAncestor(candidatePath: string, targetPath: string): boolean {\n const relativePath = path.relative(candidatePath, targetPath);\n return (\n relativePath === '' ||\n (relativePath !== '..' &&\n !relativePath.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relativePath))\n );\n}\n\nexport function validateOutputDirectoryPath(\n outputDirectory: string,\n protectedRoot: string,\n): string {\n const resolvedOutputDirectory = path.resolve(outputDirectory);\n const resolvedProtectedRoot = path.resolve(protectedRoot);\n assert(\n resolvedOutputDirectory !== path.parse(resolvedOutputDirectory).root,\n 'Refusing to replace a filesystem root with imported SB3 sources.',\n );\n assert(\n !isSamePathOrAncestor(resolvedOutputDirectory, resolvedProtectedRoot),\n 'Refusing to replace the repository root or one of its ancestors.',\n );\n assert(\n !resolvedOutputDirectory.split(path.sep).includes('.git'),\n 'Refusing to write imported SB3 sources into a .git directory.',\n );\n return resolvedOutputDirectory;\n}\n\nexport async function assertRecognizedOutputDirectory(\n outputDirectory: string,\n sourceFormatVersions: readonly number[],\n): Promise<void> {\n const stats = await lstat(outputDirectory);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `Refusing to replace a non-directory or symbolic link: ${outputDirectory}`,\n );\n\n let manifest: Record<string, unknown> | null;\n try {\n manifest = JSON.parse(await readFile(path.join(outputDirectory, 'sb3-source.json'), 'utf8'));\n } catch (error) {\n if (errorCode(error) !== 'ENOENT' && !(error instanceof SyntaxError)) {\n throw error;\n }\n throw new Error(\n `Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`,\n {cause: error},\n );\n }\n\n assert(\n manifest !== null &&\n sourceFormatVersions.includes(manifest.formatVersion as number) &&\n manifest.project === 'project.source.json' &&\n manifest.embeddedExtensions === 'embedded-extensions.json' &&\n manifest.assetsDirectory === 'assets' &&\n Array.isArray(manifest.archiveEntries),\n `Refusing to replace an unrecognized directory without a valid sb3-source.json: ${outputDirectory}`,\n );\n}\n\nfunction digest(value: Uint8Array | string): string {\n return createHash('sha256').update(value).digest('hex');\n}\n\nasync function snapshotDirectory(rootDirectory: string): Promise<Map<string, SnapshotEntry>> {\n const snapshot = new Map<string, SnapshotEntry>();\n\n async function visit(directory: string, relativeDirectory: string): Promise<void> {\n const entries = await readdir(directory, {withFileTypes: true});\n entries.sort((left, right) => (left.name < right.name ? -1 : left.name > right.name ? 1 : 0));\n\n for (const entry of entries) {\n const relativePath = relativeDirectory\n ? path.posix.join(relativeDirectory, entry.name)\n : entry.name;\n const absolutePath = path.join(directory, entry.name);\n if (entry.isDirectory()) {\n snapshot.set(relativePath, {type: 'directory'});\n await visit(absolutePath, relativePath);\n } else if (entry.isFile()) {\n const contents = await readFile(absolutePath);\n snapshot.set(relativePath, {\n type: 'file',\n size: contents.length,\n digest: digest(contents),\n });\n } else if (entry.isSymbolicLink()) {\n snapshot.set(relativePath, {\n type: 'symbolic-link',\n target: await readlink(absolutePath),\n });\n } else {\n snapshot.set(relativePath, {type: 'other'});\n }\n }\n }\n\n await visit(rootDirectory, '');\n return snapshot;\n}\n\nfunction snapshotFingerprint(snapshot: Map<string, SnapshotEntry>): string {\n return digest(JSON.stringify([...snapshot.entries()]));\n}\n\nfunction entriesMatch(left: SnapshotEntry, right: SnapshotEntry): boolean {\n return JSON.stringify(left) === JSON.stringify(right);\n}\n\nexport async function compareDirectories(\n existingDirectory: string,\n candidateDirectory: string,\n): Promise<DirectoryComparison> {\n const [existingSnapshot, candidateSnapshot] = await Promise.all([\n snapshotDirectory(existingDirectory),\n snapshotDirectory(candidateDirectory),\n ]);\n const paths = [...new Set([...existingSnapshot.keys(), ...candidateSnapshot.keys()])].sort();\n const differences: DirectoryDifferences = {added: [], modified: [], removed: []};\n\n for (const relativePath of paths) {\n const existingEntry = existingSnapshot.get(relativePath);\n const candidateEntry = candidateSnapshot.get(relativePath);\n if (!existingEntry) {\n differences.added.push(relativePath);\n } else if (!candidateEntry) {\n differences.removed.push(relativePath);\n } else if (!entriesMatch(existingEntry, candidateEntry)) {\n differences.modified.push(relativePath);\n }\n }\n\n return {\n candidateFingerprint: snapshotFingerprint(candidateSnapshot),\n differences,\n existingFilePaths: [...existingSnapshot.entries()]\n .filter(([, entry]) => entry.type !== 'directory')\n .map(([relativePath]) => relativePath),\n existingFingerprint: snapshotFingerprint(existingSnapshot),\n identical: Object.values(differences).every((entries) => entries.length === 0),\n };\n}\n\nfunction executeGit(arguments_: string[], cwd: string): Promise<string> {\n return new Promise<string>((resolve, reject) => {\n execFile(\n 'git',\n arguments_,\n {cwd, encoding: 'utf8', maxBuffer: 10 * 1024 * 1024},\n (error, stdout, stderr) => {\n if (error) {\n Object.assign(error, {stdout, stderr});\n reject(error);\n return;\n }\n resolve(stdout);\n },\n );\n });\n}\n\nfunction toPosixPath(value: string): string {\n return value.split(path.sep).join('/');\n}\n\nexport async function inspectGitOutputState(\n outputDirectory: string,\n existingFilePaths: string[],\n): Promise<GitOutputState> {\n let repositoryRoot: string;\n try {\n repositoryRoot = (await executeGit(['rev-parse', '--show-toplevel'], outputDirectory)).trim();\n } catch (error) {\n if (errorCode(error) === 128) {\n return {\n clean: false,\n fingerprint: 'not-git-managed',\n managed: false,\n repositoryRoot: null,\n statusEntries: [],\n untrackedContent: [...existingFilePaths],\n };\n }\n throw error;\n }\n\n const [canonicalOutputDirectory, canonicalRepositoryRoot] = await Promise.all([\n realpath(outputDirectory),\n realpath(repositoryRoot),\n ]);\n repositoryRoot = canonicalRepositoryRoot;\n const relativeOutputDirectory = path.relative(repositoryRoot, canonicalOutputDirectory);\n assert(\n relativeOutputDirectory !== '..' &&\n !relativeOutputDirectory.startsWith(`..${path.sep}`) &&\n !path.isAbsolute(relativeOutputDirectory),\n `Output directory is outside its detected Git worktree: ${outputDirectory}`,\n );\n const pathspec = relativeOutputDirectory || '.';\n const [statusOutput, trackedOutput] = await Promise.all([\n executeGit(\n ['status', '--porcelain=v1', '--untracked-files=all', '--', pathspec],\n repositoryRoot,\n ),\n executeGit(['ls-files', '-z', '--', pathspec], repositoryRoot),\n ]);\n const statusEntries = statusOutput.split('\\n').filter(Boolean);\n const trackedPaths = new Set(\n trackedOutput\n .split('\\0')\n .filter(Boolean)\n .map((trackedPath) =>\n toPosixPath(\n path.relative(canonicalOutputDirectory, path.join(repositoryRoot, trackedPath)),\n ),\n ),\n );\n const untrackedContent = existingFilePaths.filter((filePath) => !trackedPaths.has(filePath));\n const managed = trackedPaths.size > 0;\n const clean = managed && statusEntries.length === 0 && untrackedContent.length === 0;\n const fingerprint = digest(\n JSON.stringify({\n clean,\n managed,\n repositoryRoot,\n statusEntries,\n trackedPaths: [...trackedPaths].sort(),\n untrackedContent: [...untrackedContent].sort(),\n }),\n );\n\n return {\n clean,\n fingerprint,\n managed,\n repositoryRoot,\n statusEntries,\n untrackedContent,\n };\n}\n\nexport async function assertNoInterruptedRollback(outputDirectory: string): Promise<void> {\n const parentDirectory = path.dirname(outputDirectory);\n const outputName = path.basename(outputDirectory);\n const rollbackPrefixes = [`.${outputName}.rollback-`, `.${outputName}.backup-`];\n const leftovers = (await readdir(parentDirectory))\n .filter((entryName) => rollbackPrefixes.some((prefix) => entryName.startsWith(prefix)))\n .map((entryName) => path.join(parentDirectory, entryName));\n assert(\n leftovers.length === 0,\n `Found an interrupted SB3 import rollback directory. ` +\n `Inspect or restore it before retrying: ${leftovers.join(', ')}`,\n );\n}\n\nexport async function replaceDirectoryTransactionally(\n temporaryDirectory: string,\n outputDirectory: string,\n): Promise<{rollbackCleanupWarning: string | null}> {\n const parentDirectory = path.dirname(outputDirectory);\n await assertNoInterruptedRollback(outputDirectory);\n const rollbackDirectory = path.join(\n parentDirectory,\n `.${path.basename(outputDirectory)}.rollback-${randomUUID()}`,\n );\n assert(\n !(await pathExists(rollbackDirectory)),\n `Refusing to overwrite an existing rollback directory: ${rollbackDirectory}`,\n );\n const outputExists = await pathExists(outputDirectory);\n\n if (outputExists) {\n await rename(outputDirectory, rollbackDirectory);\n }\n\n try {\n await rename(temporaryDirectory, outputDirectory);\n } catch (installError) {\n if (outputExists) {\n try {\n await rename(rollbackDirectory, outputDirectory);\n } catch (restoreError) {\n throw new AggregateError(\n [installError, restoreError],\n `SB3 import failed and automatic restoration also failed. ` +\n `Original output remains at: ${rollbackDirectory}`,\n );\n }\n }\n throw installError;\n }\n\n if (!outputExists) {\n return {rollbackCleanupWarning: null};\n }\n\n try {\n await rm(rollbackDirectory, {recursive: true});\n return {rollbackCleanupWarning: null};\n } catch (error) {\n return {\n rollbackCleanupWarning:\n `Imported output was installed, but its temporary rollback ` +\n `directory could not be removed: ${rollbackDirectory} (${errorMessage(error)})`,\n };\n }\n}\n"],"mappings":";;;;;;AAsCA,SAAS,UAAU,OAA6C;CAC9D,OAAQ,OAAwC;AAClD;AAEA,eAAsB,WAAW,YAAsC;CACrE,IAAI;EACF,MAAM,OAAO,UAAU;EACvB,OAAO;CACT,SAAS,OAAO;EACd,IAAI,UAAU,KAAK,MAAM,UACvB,OAAO;EAET,MAAM;CACR;AACF;AAEA,SAAS,qBAAqB,eAAuB,YAA6B;CAChF,MAAM,eAAe,KAAK,SAAS,eAAe,UAAU;CAC5D,OACE,iBAAiB,MAChB,iBAAiB,QAChB,CAAC,aAAa,WAAW,KAAK,KAAK,KAAK,KACxC,CAAC,KAAK,WAAW,YAAY;AAEnC;AAEA,SAAgB,4BACd,iBACA,eACQ;CACR,MAAM,0BAA0B,KAAK,QAAQ,eAAe;CAC5D,MAAM,w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CAC9E,MAAM,aAAa,MAAM,QAAQ,eAAe,EAAA,CAC7C,QAAQ,cAAc,iBAAiB,MAAM,WAAW,UAAU,WAAW,MAAM,CAAC,CAAC,CAAC,CACtF,KAAK,cAAc,KAAK,KAAK,iBAAiB,SAAS,CAAC;CAC3D,OACE,UAAU,WAAW,GACrB,8FAC4C,UAAU,KAAK,IAAI,GACjE;AACF;AAEA,eAAsB,gCACpB,oBACA,iBACkD;CAClD,MAAM,kBAAkB,KAAK,QAAQ,eAAe;CACpD,MAAM,4BAA4B,eAAe;CACjD,MAAM,oBAAoB,KAAK,KAC7B,iBACA,IAAI,KAAK,SAAS,eAAe,EAAE,YAAY,WAAW,GAC5D;CACA,OACE,CAAE,MAAM,WAAW,iBAAiB,GACpC,yDAAyD,mBAC3D;CACA,MAAM,eAAe,MAAM,WAAW,eAAe;CAErD,IAAI,cACF,MAAM,OAAO,iBAAiB,iBAAiB;CAGjD,IAAI;EACF,MAAM,OAAO,oBAAoB,eAAe;CAClD,SAAS,cAAc;EACrB,IAAI,cACF,IAAI;GACF,MAAM,OAAO,mBAAmB,eAAe;EACjD,SAAS,cAAc;GACrB,MAAM,IAAI,eACR,CAAC,cAAc,YAAY,GAC3B,wFACiC,mBACnC;EACF;EAEF,MAAM;CACR;CAEA,IAAI,CAAC,cACH,OAAO,EAAC,wBAAwB,KAAI;CAGtC,IAAI;EACF,MAAM,GAAG,mBAAmB,EAAC,WAAW,KAAI,CAAC;EAC7C,OAAO,EAAC,wBAAwB,KAAI;CACtC,SAAS,OAAO;EACd,OAAO,EACL,wBACE,6FACmC,kBAAkB,IAAI,aAAa,KAAK,EAAE,GACjF;CACF;AACF"}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { UnknownRecord } from './types';
|
|
1
|
+
import { UnknownRecord } from './types.js';
|
|
2
2
|
export type ReleaseSnapshotState = 'candidate' | 'frozen' | 'published';
|
|
3
3
|
export type ReleaseSourceFiles = Map<string, Buffer | Uint8Array | string>;
|
|
4
4
|
export interface ReleaseSnapshotArtifact {
|
package/dist/source-format.d.ts
CHANGED
|
@@ -1,5 +1,12 @@
|
|
|
1
|
-
import { EmbeddedExtension, ProjectJson, Sb3SourceManifest, UnknownRecord } from './types';
|
|
1
|
+
import { EmbeddedExtension, ProjectJson, Sb3SourceManifest, UnknownRecord } from './types.js';
|
|
2
|
+
/** The source format version written for projects without block palette settings. */
|
|
2
3
|
export declare const sourceFormatVersion = 1;
|
|
4
|
+
/** The source format version written for projects with `block-palette.json`. */
|
|
5
|
+
export declare const blockPaletteSourceFormatVersion = 2;
|
|
6
|
+
/** Every source format version that readers accept. */
|
|
7
|
+
export declare const supportedSourceFormatVersions: readonly number[];
|
|
8
|
+
/** `embedded-extensions.json` keeps its own version, independent of the source format. */
|
|
9
|
+
export declare const embeddedExtensionManifestFormatVersion = 1;
|
|
3
10
|
export declare function isObject(value: unknown): value is UnknownRecord;
|
|
4
11
|
export declare function assertSameFileSet(actualFiles: string[], expectedFiles: string[], description: string): void;
|
|
5
12
|
export declare function validateSourceManifest(manifest: unknown): asserts manifest is Sb3SourceManifest;
|
package/dist/source-format.js
CHANGED
|
@@ -1,7 +1,13 @@
|
|
|
1
1
|
import { assert } from "./assert.js";
|
|
2
|
+
import { blockPaletteFile } from "./block-palette.js";
|
|
2
3
|
import { validateArchiveEntryName } from "./archive.js";
|
|
3
4
|
//#region src/source-format.ts
|
|
5
|
+
/** The source format version written for projects without block palette settings. */
|
|
4
6
|
var sourceFormatVersion = 1;
|
|
7
|
+
/** The source format version written for projects with `block-palette.json`. */
|
|
8
|
+
var blockPaletteSourceFormatVersion = 2;
|
|
9
|
+
/** Every source format version that readers accept. */
|
|
10
|
+
var supportedSourceFormatVersions = [1, 2];
|
|
5
11
|
function isObject(value) {
|
|
6
12
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
7
13
|
}
|
|
@@ -14,7 +20,9 @@ function assertSameFileSet(actualFiles, expectedFiles, description) {
|
|
|
14
20
|
}
|
|
15
21
|
function validateSourceManifest(manifest) {
|
|
16
22
|
assert(isObject(manifest), "sb3-source.json must contain an object.");
|
|
17
|
-
assert(manifest.formatVersion
|
|
23
|
+
assert(supportedSourceFormatVersions.includes(manifest.formatVersion), `Unsupported SB3 source format version: ${manifest.formatVersion}`);
|
|
24
|
+
if (manifest.formatVersion === 2) assert(manifest.blockPalette === blockPaletteFile, `SB3 source format 2 requires ${blockPaletteFile}.`);
|
|
25
|
+
else assert(manifest.blockPalette === void 0, "sb3-source.json blockPalette requires SB3 source format 2.");
|
|
18
26
|
assert(manifest.project === "project.source.json", "SB3 source format 1 requires project.source.json.");
|
|
19
27
|
assert(manifest.embeddedExtensions === "embedded-extensions.json", "SB3 source format 1 requires embedded-extensions.json.");
|
|
20
28
|
assert(manifest.assetsDirectory === "assets", "SB3 source format 1 requires the assets directory.");
|
|
@@ -121,6 +129,6 @@ function collectSourceAssetReferences(project) {
|
|
|
121
129
|
});
|
|
122
130
|
}
|
|
123
131
|
//#endregion
|
|
124
|
-
export { assertSameFileSet, collectSourceAssetReferences, isObject, sourceFormatVersion, validateExtensionLayout, validateSourceManifest };
|
|
132
|
+
export { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest };
|
|
125
133
|
|
|
126
134
|
//# sourceMappingURL=source-format.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source-format.js","names":[],"sources":["../src/source-format.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert} from './assert';\nimport type {\n EmbeddedExtension,\n ProjectAssetReference,\n ProjectJson,\n Sb3SourceManifest,\n UnknownRecord,\n} from './types';\n\nexport const sourceFormatVersion = 1;\n\nexport function isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function assertSameFileSet(\n actualFiles: string[],\n expectedFiles: string[],\n description: string,\n): void {\n const actual = new Set(actualFiles);\n const expected = new Set(expectedFiles);\n const missing = [...expected].filter((filePath) => !actual.has(filePath)).sort();\n const extra = [...actual].filter((filePath) => !expected.has(filePath)).sort();\n assert(\n missing.length === 0 && extra.length === 0,\n `${description} does not match its manifest. Missing: ${missing.join(', ') || '(none)'}. ` +\n `Extra: ${extra.join(', ') || '(none)'}.`,\n );\n}\n\nexport function validateSourceManifest(manifest: unknown): asserts manifest is Sb3SourceManifest {\n assert(isObject(manifest), 'sb3-source.json must contain an object.');\n assert(\n manifest.formatVersion === sourceFormatVersion,\n `Unsupported SB3 source format version: ${manifest.formatVersion}`,\n );\n assert(\n manifest.project === 'project.source.json',\n 'SB3 source format 1 requires project.source.json.',\n );\n assert(\n manifest.embeddedExtensions === 'embedded-extensions.json',\n 'SB3 source format 1 requires embedded-extensions.json.',\n );\n assert(\n manifest.assetsDirectory === 'assets',\n 'SB3 source format 1 requires the assets directory.',\n );\n assert(\n Array.isArray(manifest.archiveEntries) && manifest.archiveEntries.length > 0,\n 'sb3-source.json archiveEntries must be a non-empty array.',\n );\n\n const seenEntries = new Set<string>();\n let projectEntryCount = 0;\n for (const rawEntryName of manifest.archiveEntries as unknown[]) {\n const entryName = validateArchiveEntryName(rawEntryName);\n assert(!seenEntries.has(entryName), `Duplicate archive entry in manifest: ${entryName}`);\n assert(\n !entryName.endsWith('/'),\n `Directory ZIP entries are not supported in SB3 source format 1: ${entryName}`,\n );\n assert(\n !/^(?:0|[1-9][0-9]*)$/u.test(entryName),\n `Integer-like ZIP entry names cannot preserve JavaScript object order: ${entryName}`,\n );\n seenEntries.add(entryName);\n if (entryName === 'project.json') {\n projectEntryCount += 1;\n }\n }\n assert(projectEntryCount === 1, 'archiveEntries must contain project.json exactly once.');\n}\n\nexport function validateExtensionLayout(\n extensionManifest: unknown,\n project: ProjectJson,\n extensionFiles: string[],\n validateManagedSource?: (extension: EmbeddedExtension) => unknown,\n): {extensionBundles: unknown; extensions: EmbeddedExtension[]} {\n assert(isObject(extensionManifest), 'embedded-extensions.json must contain an object.');\n assert(\n extensionManifest.formatVersion === sourceFormatVersion,\n `Unsupported embedded extension manifest version: ${extensionManifest.formatVersion}`,\n );\n assert(\n Array.isArray(extensionManifest.extensions),\n 'embedded-extensions.json extensions must be an array.',\n );\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n assert(\n isObject(extensionUrls),\n 'project.source.json extensionURLs must be an object when present.',\n );\n const extensionsById = new Map<string, EmbeddedExtension>();\n const expectedFiles: string[] = [];\n const extensions: EmbeddedExtension[] = [];\n\n for (const entry of extensionManifest.extensions as unknown[]) {\n assert(isObject(entry), 'Each embedded extension manifest entry must be an object.');\n const extension = entry as unknown as EmbeddedExtension;\n assert(\n typeof extension.id === 'string' && /^[A-Za-z0-9._-]+$/u.test(extension.id),\n `Invalid embedded extension ID: ${JSON.stringify(extension.id)}`,\n );\n assert(!extensionsById.has(extension.id), `Duplicate embedded extension ID: ${extension.id}`);\n const expectedPath = `extensions/${extension.id}.js`;\n assert(\n extension.path === expectedPath,\n `Embedded extension path must match its ID: expected ${expectedPath}, got ${extension.path}`,\n );\n assert(\n typeof extension.mediaType === 'string' &&\n extension.mediaType.length > 0 &&\n !/[;,\\r\\n]/u.test(extension.mediaType),\n `Invalid media type for embedded extension ${extension.id}: ${extension.mediaType}`,\n );\n assert(\n Array.isArray(extension.parameters) &&\n extension.parameters.every(\n (parameter) =>\n typeof parameter === 'string' && parameter.length > 0 && !/[;,\\r\\n]/u.test(parameter),\n ),\n `Invalid data URL parameters for embedded extension ${extension.id}.`,\n );\n assert(\n extension.encoding === 'base64' || extension.encoding === 'percent',\n `Unsupported encoding for embedded extension ${extension.id}: ${extension.encoding}`,\n );\n assert(\n extensionUrls[extension.id] === `embedded-extension:${extension.path}`,\n `project.source.json mapping does not match embedded extension ${extension.id}.`,\n );\n if (extension.source !== undefined) {\n assert(isObject(extension.source), `Invalid source for embedded extension ${extension.id}.`);\n const sidecar = extension.source.apiManifest;\n assert(\n sidecar === undefined ||\n (isObject(sidecar) && sidecar.path === `extensions/${extension.id}.manifest.json`),\n `Invalid API manifest path for embedded extension ${extension.id}.`,\n );\n }\n validateManagedSource?.(extension);\n extensionsById.set(extension.id, extension);\n extensions.push(extension);\n expectedFiles.push(`${extension.id}.js`);\n if (extension.source?.apiManifest) {\n expectedFiles.push(extension.source.apiManifest.path.slice('extensions/'.length));\n }\n }\n\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n assert(\n typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:'),\n `project.source.json still contains an embedded data URL: ${extensionId}`,\n );\n if (typeof extensionUrl === 'string' && extensionUrl.startsWith('embedded-extension:')) {\n assert(\n extensionsById.has(extensionId),\n `project.source.json has no metadata for embedded extension ${extensionId}.`,\n );\n }\n }\n\n assertSameFileSet(extensionFiles, expectedFiles, 'Embedded extension files');\n return {\n extensionBundles: extensionManifest.extensionBundles,\n extensions,\n };\n}\n\nfunction collectAssetReferences(\n project: ProjectJson,\n): {asset: ProjectAssetReference; description: string}[] {\n assert(Array.isArray(project.targets), 'project.source.json targets must be an array.');\n const references: {asset: ProjectAssetReference; description: string}[] = [];\n for (const [targetIndex, target] of (project.targets as unknown[]).entries()) {\n assert(isObject(target), `Project target ${targetIndex} must be an object.`);\n for (const [collectionName, kind] of [\n ['costumes', 'costume'],\n ['sounds', 'sound'],\n ] as const) {\n const assets: unknown = target[collectionName] ?? [];\n assert(\n Array.isArray(assets),\n `Project target ${targetIndex} ${collectionName} must be an array.`,\n );\n for (const [assetIndex, asset] of (assets as unknown[]).entries()) {\n assert(isObject(asset), `Project ${kind} ${targetIndex}:${assetIndex} must be an object.`);\n references.push({asset, description: `${kind} ${targetIndex}:${assetIndex}`});\n }\n }\n }\n const fonts = project.customFonts ?? [];\n assert(Array.isArray(fonts), 'project.source.json customFonts must be an array.');\n for (const [index, font] of fonts.entries()) {\n if (!isObject(font) || font.system !== false || font.md5ext === undefined) continue;\n const md5ext = font.md5ext;\n const match = typeof md5ext === 'string' && /^([a-f0-9]{32})\\.(ttf|otf|woff2?)$/u.exec(md5ext);\n assert(match, `Invalid font asset reference for font ${index}: ${md5ext}`);\n const [, assetId, dataFormat] = match;\n references.push({asset: {assetId, dataFormat, md5ext}, description: `font ${index}`});\n }\n return references;\n}\n\nexport function collectSourceAssetReferences(\n project: ProjectJson,\n): {filename: string; description: string}[] {\n return collectAssetReferences(project).map(({asset, description}) => {\n assert(\n typeof asset.assetId === 'string' && /^[a-f0-9]{32}$/u.test(asset.assetId),\n `Invalid assetId for ${description}: ${asset.assetId}`,\n );\n assert(\n typeof asset.dataFormat === 'string' && /^[A-Za-z0-9]+$/u.test(asset.dataFormat),\n `Invalid dataFormat for ${description}: ${asset.dataFormat}`,\n );\n const expectedFilename = `${asset.assetId}.${asset.dataFormat}`;\n assert(\n asset.md5ext === expectedFilename,\n `Asset filename mismatch for ${description}: expected ${expectedFilename}, got ${asset.md5ext}`,\n );\n return {filename: expectedFilename, description};\n });\n}\n"],"mappings":";;;AAYA,IAAa,sBAAsB;AAEnC,SAAgB,SAAS,OAAwC;CAC/D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,kBACd,aACA,eACA,aACM;CACN,MAAM,SAAS,IAAI,IAAI,WAAW;CAClC,MAAM,WAAW,IAAI,IAAI,aAAa;CACtC,MAAM,UAAU,CAAC,GAAG,QAAQ,CAAC,CAAC,QAAQ,aAAa,CAAC,OAAO,IAAI,QAAQ,CAAC,CAAC,CAAC,KAAK;CAC/E,MAAM,QAAQ,CAAC,GAAG,MAAM,CAAC,CAAC,QAAQ,aAAa,CAAC,SAAS,IAAI,QAAQ,CAAC,CAAC,CAAC,KAAK;CAC7E,OACE,QAAQ,WAAW,KAAK,MAAM,WAAW,GACzC,GAAG,YAAY,yCAAyC,QAAQ,KAAK,IAAI,KAAK,SAAS,WAC3E,MAAM,KAAK,IAAI,KAAK,SAAS,EAC3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I,QAAQ;EACzE,MAAM,GAAG,SAAS,cAAc;EAChC,WAAW,KAAK;GAAC,OAAO;IAAC;IAAS;IAAY;GAAM;GAAG,aAAa,QAAQ;EAAO,CAAC;CACtF;CACA,OAAO;AACT;AAEA,SAAgB,6BACd,SAC2C;CAC3C,OAAO,uBAAuB,OAAO,CAAC,CAAC,KAAK,EAAC,OAAO,kBAAiB;EACnE,OACE,OAAO,MAAM,YAAY,YAAY,kBAAkB,KAAK,MAAM,OAAO,GACzE,uBAAuB,YAAY,IAAI,MAAM,SAC/C;EACA,OACE,OAAO,MAAM,eAAe,YAAY,kBAAkB,KAAK,MAAM,UAAU,GAC/E,0BAA0B,YAAY,IAAI,MAAM,YAClD;EACA,MAAM,mBAAmB,GAAG,MAAM,QAAQ,GAAG,MAAM;EACnD,OACE,MAAM,WAAW,kBACjB,+BAA+B,YAAY,aAAa,iBAAiB,QAAQ,MAAM,QACzF;EACA,OAAO;GAAC,UAAU;GAAkB;EAAW;CACjD,CAAC;AACH"}
|
|
1
|
+
{"version":3,"file":"source-format.js","names":[],"sources":["../src/source-format.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert} from './assert';\nimport {blockPaletteFile} from './block-palette';\nimport type {\n EmbeddedExtension,\n ProjectAssetReference,\n ProjectJson,\n Sb3SourceManifest,\n UnknownRecord,\n} from './types';\n\n/** The source format version written for projects without block palette settings. */\nexport const sourceFormatVersion = 1;\n/** The source format version written for projects with `block-palette.json`. */\nexport const blockPaletteSourceFormatVersion = 2;\n/** Every source format version that readers accept. */\nexport const supportedSourceFormatVersions: readonly number[] = [1, 2];\n/** `embedded-extensions.json` keeps its own version, independent of the source format. */\nexport const embeddedExtensionManifestFormatVersion = 1;\n\nexport function isObject(value: unknown): value is UnknownRecord {\n return typeof value === 'object' && value !== null && !Array.isArray(value);\n}\n\nexport function assertSameFileSet(\n actualFiles: string[],\n expectedFiles: string[],\n description: string,\n): void {\n const actual = new Set(actualFiles);\n const expected = new Set(expectedFiles);\n const missing = [...expected].filter((filePath) => !actual.has(filePath)).sort();\n const extra = [...actual].filter((filePath) => !expected.has(filePath)).sort();\n assert(\n missing.length === 0 && extra.length === 0,\n `${description} does not match its manifest. Missing: ${missing.join(', ') || '(none)'}. ` +\n `Extra: ${extra.join(', ') || '(none)'}.`,\n );\n}\n\nexport function validateSourceManifest(manifest: unknown): asserts manifest is Sb3SourceManifest {\n assert(isObject(manifest), 'sb3-source.json must contain an object.');\n assert(\n supportedSourceFormatVersions.includes(manifest.formatVersion as number),\n `Unsupported SB3 source format version: ${manifest.formatVersion}`,\n );\n if (manifest.formatVersion === blockPaletteSourceFormatVersion) {\n assert(\n manifest.blockPalette === blockPaletteFile,\n `SB3 source format 2 requires ${blockPaletteFile}.`,\n );\n } else {\n assert(\n manifest.blockPalette === undefined,\n 'sb3-source.json blockPalette requires SB3 source format 2.',\n );\n }\n assert(\n manifest.project === 'project.source.json',\n 'SB3 source format 1 requires project.source.json.',\n );\n assert(\n manifest.embeddedExtensions === 'embedded-extensions.json',\n 'SB3 source format 1 requires embedded-extensions.json.',\n );\n assert(\n manifest.assetsDirectory === 'assets',\n 'SB3 source format 1 requires the assets directory.',\n );\n assert(\n Array.isArray(manifest.archiveEntries) && manifest.archiveEntries.length > 0,\n 'sb3-source.json archiveEntries must be a non-empty array.',\n );\n\n const seenEntries = new Set<string>();\n let projectEntryCount = 0;\n for (const rawEntryName of manifest.archiveEntries as unknown[]) {\n const entryName = validateArchiveEntryName(rawEntryName);\n assert(!seenEntries.has(entryName), `Duplicate archive entry in manifest: ${entryName}`);\n assert(\n !entryName.endsWith('/'),\n `Directory ZIP entries are not supported in SB3 source format 1: ${entryName}`,\n );\n assert(\n !/^(?:0|[1-9][0-9]*)$/u.test(entryName),\n `Integer-like ZIP entry names cannot preserve JavaScript object order: ${entryName}`,\n );\n seenEntries.add(entryName);\n if (entryName === 'project.json') {\n projectEntryCount += 1;\n }\n }\n assert(projectEntryCount === 1, 'archiveEntries must contain project.json exactly once.');\n}\n\nexport function validateExtensionLayout(\n extensionManifest: unknown,\n project: ProjectJson,\n extensionFiles: string[],\n validateManagedSource?: (extension: EmbeddedExtension) => unknown,\n): {extensionBundles: unknown; extensions: EmbeddedExtension[]} {\n assert(isObject(extensionManifest), 'embedded-extensions.json must contain an object.');\n assert(\n extensionManifest.formatVersion === embeddedExtensionManifestFormatVersion,\n `Unsupported embedded extension manifest version: ${extensionManifest.formatVersion}`,\n );\n assert(\n Array.isArray(extensionManifest.extensions),\n 'embedded-extensions.json extensions must be an array.',\n );\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n assert(\n isObject(extensionUrls),\n 'project.source.json extensionURLs must be an object when present.',\n );\n const extensionsById = new Map<string, EmbeddedExtension>();\n const expectedFiles: string[] = [];\n const extensions: EmbeddedExtension[] = [];\n\n for (const entry of extensionManifest.extensions as unknown[]) {\n assert(isObject(entry), 'Each embedded extension manifest entry must be an object.');\n const extension = entry as unknown as EmbeddedExtension;\n assert(\n typeof extension.id === 'string' && /^[A-Za-z0-9._-]+$/u.test(extension.id),\n `Invalid embedded extension ID: ${JSON.stringify(extension.id)}`,\n );\n assert(!extensionsById.has(extension.id), `Duplicate embedded extension ID: ${extension.id}`);\n const expectedPath = `extensions/${extension.id}.js`;\n assert(\n extension.path === expectedPath,\n `Embedded extension path must match its ID: expected ${expectedPath}, got ${extension.path}`,\n );\n assert(\n typeof extension.mediaType === 'string' &&\n extension.mediaType.length > 0 &&\n !/[;,\\r\\n]/u.test(extension.mediaType),\n `Invalid media type for embedded extension ${extension.id}: ${extension.mediaType}`,\n );\n assert(\n Array.isArray(extension.parameters) &&\n extension.parameters.every(\n (parameter) =>\n typeof parameter === 'string' && parameter.length > 0 && !/[;,\\r\\n]/u.test(parameter),\n ),\n `Invalid data URL parameters for embedded extension ${extension.id}.`,\n );\n assert(\n extension.encoding === 'base64' || extension.encoding === 'percent',\n `Unsupported encoding for embedded extension ${extension.id}: ${extension.encoding}`,\n );\n assert(\n extensionUrls[extension.id] === `embedded-extension:${extension.path}`,\n `project.source.json mapping does not match embedded extension ${extension.id}.`,\n );\n if (extension.source !== undefined) {\n assert(isObject(extension.source), `Invalid source for embedded extension ${extension.id}.`);\n const sidecar = extension.source.apiManifest;\n assert(\n sidecar === undefined ||\n (isObject(sidecar) && sidecar.path === `extensions/${extension.id}.manifest.json`),\n `Invalid API manifest path for embedded extension ${extension.id}.`,\n );\n }\n validateManagedSource?.(extension);\n extensionsById.set(extension.id, extension);\n extensions.push(extension);\n expectedFiles.push(`${extension.id}.js`);\n if (extension.source?.apiManifest) {\n expectedFiles.push(extension.source.apiManifest.path.slice('extensions/'.length));\n }\n }\n\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n assert(\n typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:'),\n `project.source.json still contains an embedded data URL: ${extensionId}`,\n );\n if (typeof extensionUrl === 'string' && extensionUrl.startsWith('embedded-extension:')) {\n assert(\n extensionsById.has(extensionId),\n `project.source.json has no metadata for embedded extension ${extensionId}.`,\n );\n }\n }\n\n assertSameFileSet(extensionFiles, expectedFiles, 'Embedded extension files');\n return {\n extensionBundles: extensionManifest.extensionBundles,\n extensions,\n };\n}\n\nfunction collectAssetReferences(\n project: ProjectJson,\n): {asset: ProjectAssetReference; description: string}[] {\n assert(Array.isArray(project.targets), 'project.source.json targets must be an array.');\n const references: {asset: ProjectAssetReference; description: string}[] = [];\n for (const [targetIndex, target] of (project.targets as unknown[]).entries()) {\n assert(isObject(target), `Project target ${targetIndex} must be an object.`);\n for (const [collectionName, kind] of [\n ['costumes', 'costume'],\n ['sounds', 'sound'],\n ] as const) {\n const assets: unknown = target[collectionName] ?? [];\n assert(\n Array.isArray(assets),\n `Project target ${targetIndex} ${collectionName} must be an array.`,\n );\n for (const [assetIndex, asset] of (assets as unknown[]).entries()) {\n assert(isObject(asset), `Project ${kind} ${targetIndex}:${assetIndex} must be an object.`);\n references.push({asset, description: `${kind} ${targetIndex}:${assetIndex}`});\n }\n }\n }\n const fonts = project.customFonts ?? [];\n assert(Array.isArray(fonts), 'project.source.json customFonts must be an array.');\n for (const [index, font] of fonts.entries()) {\n if (!isObject(font) || font.system !== false || font.md5ext === undefined) continue;\n const md5ext = font.md5ext;\n const match = typeof md5ext === 'string' && /^([a-f0-9]{32})\\.(ttf|otf|woff2?)$/u.exec(md5ext);\n assert(match, `Invalid font asset reference for font ${index}: ${md5ext}`);\n const [, assetId, dataFormat] = match;\n references.push({asset: {assetId, dataFormat, md5ext}, description: `font ${index}`});\n }\n return references;\n}\n\nexport function collectSourceAssetReferences(\n project: ProjectJson,\n): {filename: string; description: string}[] {\n return collectAssetReferences(project).map(({asset, description}) => {\n assert(\n typeof asset.assetId === 'string' && /^[a-f0-9]{32}$/u.test(asset.assetId),\n `Invalid assetId for ${description}: ${asset.assetId}`,\n );\n assert(\n typeof asset.dataFormat === 'string' && /^[A-Za-z0-9]+$/u.test(asset.dataFormat),\n `Invalid dataFormat for ${description}: ${asset.dataFormat}`,\n );\n const expectedFilename = `${asset.assetId}.${asset.dataFormat}`;\n assert(\n asset.md5ext === expectedFilename,\n `Asset filename mismatch for ${description}: expected ${expectedFilename}, got ${asset.md5ext}`,\n );\n return {filename: expectedFilename, description};\n });\n}\n"],"mappings":";;;;;AAcA,IAAa,sBAAsB;;AAEnC,IAAa,kCAAkC;;AAE/C,IAAa,gCAAmD,CAAC,GAAG,CAAC;AAIrE,SAAgB,SAAS,OAAwC;CAC/D,OAAO,OAAO,UAAU,YAAY,UAAU,QAAQ,CAAC,MAAM,QAAQ,KAAK;AAC5E;AAEA,SAAgB,kBACd,aACA,eACA,aACM;CACN,MAAM,SAAS,IAAI,IAAI,WAAW;CAClC,MAAM,WAAW,IAAI,IAAI,aAAa;CACtC,MAAM,UAAU,CAAC,GAAG,QAAQ,CAAC,CAAC,QAAQ,aAAa,CAAC,OAAO,IAAI,QAAQ,CAAC,CAAC,CAAC,KAAK;CAC/E,MAAM,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AAG,YAAY,GAAG;IAAY,CAAC;GAC9E;EACF;CACF;CACA,MAAM,QAAQ,QAAQ,eAAe,CAAC;CACtC,OAAO,MAAM,QAAQ,KAAK,GAAG,mDAAmD;CAChF,KAAK,MAAM,CAAC,OAAO,SAAS,MAAM,QAAQ,GAAG;EAC3C,IAAI,CAAC,SAAS,IAAI,KAAK,KAAK,WAAW,SAAS,KAAK,WAAW,KAAA,GAAW;EAC3E,MAAM,SAAS,KAAK;EACpB,MAAM,QAAQ,OAAO,WAAW,YAAY,sCAAsC,KAAK,MAAM;EAC7F,OAAO,OAAO,yCAAyC,MAAM,IAAI,QAAQ;EACzE,MAAM,GAAG,SAAS,cAAc;EAChC,WAAW,KAAK;GAAC,OAAO;IAAC;IAAS;IAAY;GAAM;GAAG,aAAa,QAAQ;EAAO,CAAC;CACtF;CACA,OAAO;AACT;AAEA,SAAgB,6BACd,SAC2C;CAC3C,OAAO,uBAAuB,OAAO,CAAC,CAAC,KAAK,EAAC,OAAO,kBAAiB;EACnE,OACE,OAAO,MAAM,YAAY,YAAY,kBAAkB,KAAK,MAAM,OAAO,GACzE,uBAAuB,YAAY,IAAI,MAAM,SAC/C;EACA,OACE,OAAO,MAAM,eAAe,YAAY,kBAAkB,KAAK,MAAM,UAAU,GAC/E,0BAA0B,YAAY,IAAI,MAAM,YAClD;EACA,MAAM,mBAAmB,GAAG,MAAM,QAAQ,GAAG,MAAM;EACnD,OACE,MAAM,WAAW,kBACjB,+BAA+B,YAAY,aAAa,iBAAiB,QAAQ,MAAM,QACzF;EACA,OAAO;GAAC,UAAU;GAAkB;EAAW;CACjD,CAAC;AACH"}
|
package/dist/source.d.ts
CHANGED
|
@@ -1,11 +1,14 @@
|
|
|
1
|
-
import {
|
|
2
|
-
import {
|
|
3
|
-
import {
|
|
4
|
-
|
|
1
|
+
import { BlockPaletteDocument } from './block-palette.js';
|
|
2
|
+
import { ExtensionBundlePlan } from './extension-bundle.js';
|
|
3
|
+
import { ProjectAssetAdditionsSummary } from './project-asset-additions.js';
|
|
4
|
+
import { EmbeddedExtension, ExtensionBundleConfiguration, ProjectJson, Sb3SourceManifest } from './types.js';
|
|
5
|
+
export { blockPaletteSourceFormatVersion, sourceFormatVersion, supportedSourceFormatVersions, } from './source-format.js';
|
|
5
6
|
export declare const fixedZipTimestamp: Date;
|
|
6
7
|
export interface InspectedSb3Source {
|
|
7
8
|
assetContents: Map<string, Uint8Array>;
|
|
8
9
|
assetReferenceCount: number;
|
|
10
|
+
/** `block-palette.json` in source format 2, otherwise null. */
|
|
11
|
+
blockPalette: BlockPaletteDocument | null;
|
|
9
12
|
extensions: EmbeddedExtension[];
|
|
10
13
|
extensionApiManifestContents: Map<string, Uint8Array>;
|
|
11
14
|
extensionBundles: ExtensionBundleConfiguration[];
|
package/dist/source.js
CHANGED
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
import { assert, errorMessage } from "./assert.js";
|
|
2
|
+
import { applyBlockPaletteComments, resolveBlockPaletteReferences, validateBlockPaletteDocument } from "./block-palette.js";
|
|
2
3
|
import { validateManagedExtensionApiManifest } from "./extension-api-manifest.js";
|
|
3
4
|
import { validateExtensionSourceMetadata, validateManagedExtensionContents } from "./extension-dependencies.js";
|
|
4
5
|
import { validateExtensionBundleConfigurations } from "./extension-bundle.js";
|
|
5
6
|
import { buildExtensionBundlesWithModules } from "./extension-module-bundle.js";
|
|
6
7
|
import { applyProjectAssetAdditions } from "./project-asset-additions.js";
|
|
7
8
|
import { cleanUpTurboWarpBlocks } from "./turbowarp-clean-up.js";
|
|
8
|
-
import { assertSameFileSet, collectSourceAssetReferences, isObject, sourceFormatVersion, validateExtensionLayout, validateSourceManifest } from "./source-format.js";
|
|
9
|
+
import { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest } from "./source-format.js";
|
|
9
10
|
import path from "node:path";
|
|
10
11
|
import { createHash } from "node:crypto";
|
|
11
12
|
import { lstat, readFile, readdir } from "node:fs/promises";
|
|
@@ -66,6 +67,8 @@ async function inspectSb3Source(sourceDirectory, validateManagedExtensions) {
|
|
|
66
67
|
const assetEntries = sourceManifest.archiveEntries.filter((entryName) => entryName !== "project.json");
|
|
67
68
|
const project = await readJson(path.join(resolvedSourceDirectory, sourceManifest.project), "SB3 project source");
|
|
68
69
|
assert(isObject(project), "project.source.json must contain an object.");
|
|
70
|
+
const blockPalette = sourceManifest.blockPalette === void 0 ? null : validateBlockPaletteDocument(await readJson(path.join(resolvedSourceDirectory, sourceManifest.blockPalette), "Block palette settings"));
|
|
71
|
+
resolveBlockPaletteReferences(project, blockPalette);
|
|
69
72
|
const extensionManifest = await readJson(path.join(resolvedSourceDirectory, sourceManifest.embeddedExtensions), "Embedded extension manifest");
|
|
70
73
|
const assetsDirectory = path.join(resolvedSourceDirectory, sourceManifest.assetsDirectory);
|
|
71
74
|
const extensionsDirectory = path.join(resolvedSourceDirectory, "extensions");
|
|
@@ -105,6 +108,7 @@ async function inspectSb3Source(sourceDirectory, validateManagedExtensions) {
|
|
|
105
108
|
return {
|
|
106
109
|
assetContents,
|
|
107
110
|
assetReferenceCount: references.length,
|
|
111
|
+
blockPalette,
|
|
108
112
|
extensions,
|
|
109
113
|
extensionApiManifestContents,
|
|
110
114
|
extensionBundles,
|
|
@@ -166,6 +170,7 @@ async function createDeterministicSb3(sourceDirectory, options = {}) {
|
|
|
166
170
|
targetCount: cleaned.targetCount
|
|
167
171
|
};
|
|
168
172
|
}
|
|
173
|
+
applyBlockPaletteComments(project, source.blockPalette);
|
|
169
174
|
const extensionUrls = project.extensionURLs ?? {};
|
|
170
175
|
for (const extension of bundled.extensions) {
|
|
171
176
|
const contents = bundled.extensionContents.get(extension.id);
|
|
@@ -199,6 +204,6 @@ async function createDeterministicSb3(sourceDirectory, options = {}) {
|
|
|
199
204
|
};
|
|
200
205
|
}
|
|
201
206
|
//#endregion
|
|
202
|
-
export { createDeterministicSb3, fixedZipTimestamp, inspectSb3SourceForExtensionSync, sourceFormatVersion, validateSb3Source };
|
|
207
|
+
export { blockPaletteSourceFormatVersion, createDeterministicSb3, fixedZipTimestamp, inspectSb3SourceForExtensionSync, sourceFormatVersion, supportedSourceFormatVersions, validateSb3Source };
|
|
203
208
|
|
|
204
209
|
//# sourceMappingURL=source.js.map
|