@kubohiroya/sb3-toolchain 0.25.1 → 0.26.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +9 -0
- package/README.ja.md +4 -4
- package/README.md +4 -4
- package/dist/browser.js +10 -7
- package/dist/browser.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 +3 -4
- package/dist/expand-archive.js +9 -17
- package/dist/expand-archive.js.map +1 -1
- package/dist/import.js +1 -1
- package/dist/import.js.map +1 -1
- package/dist/source-format.d.ts +7 -0
- package/dist/source-format.js +8 -1
- package/dist/source-format.js.map +1 -1
- package/dist/source.d.ts +2 -0
- package/dist/source.js +22 -4
- package/dist/source.js.map +1 -1
- package/docs/index.html +2 -2
- package/docs/ja/source-format-v1.md +5 -1
- package/docs/ja/source-format-v2.md +2 -0
- package/docs/source-format-v1.md +11 -2
- package/docs/source-format-v2.md +4 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,14 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## 0.26.0 - 2026-11-16
|
|
4
|
+
|
|
5
|
+
- TurboWarp Plus Editor の画面状態(SB3 の `tw-plus/workspace.json`)を、作品フォルダの `.tw-plus/workspace.json` とバイト列のまま行き来させる。エディターが後から書いたファイルは SB3 の最後のエントリにする。ブラウザー版の `unpackSb3` が、このエントリを含む SB3 を拒否しなくなった(#94)。
|
|
6
|
+
- import と unpack は、ブロックパレットのコメントを `block-palette.json` に移さず、いつも形式 1 で書く。0.25 が書いた形式 2 の作品フォルダは、引き続き読んで build できる(#94)。
|
|
7
|
+
|
|
8
|
+
## 0.26.0 - 2026-11-16
|
|
9
|
+
|
|
10
|
+
- feat(source): エディターの画面状態を保ち、パレットのコメントを形式 2 に移すのをやめる (#94)
|
|
11
|
+
|
|
3
12
|
## 0.25.1 - 2026-11-16
|
|
4
13
|
|
|
5
14
|
- ブロックパレットの設定を扱う `extractBlockPalette`・`resolveBlockPaletteReferences`・`applyBlockPaletteComments`・`hasBlockPaletteSettings` を、ブラウザー向けの入口とパッケージの入口から出した(#92)。
|
package/README.ja.md
CHANGED
|
@@ -34,7 +34,7 @@ Scratch 3およびTurboWarpの`.sb3`プロジェクトを、Gitで差分を確
|
|
|
34
34
|
再現可能なインストールのため、検証済みのnpmバージョンを固定します。
|
|
35
35
|
|
|
36
36
|
```bash
|
|
37
|
-
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.
|
|
37
|
+
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.26.0
|
|
38
38
|
```
|
|
39
39
|
|
|
40
40
|
## クイックスタート
|
|
@@ -153,9 +153,9 @@ await unbundleSb3({
|
|
|
153
153
|
|
|
154
154
|
### ブラウザーで作品フォルダを作る
|
|
155
155
|
|
|
156
|
-
`@kubohiroya/sb3-toolchain/browser` の `unpackSb3(bytes)` は、SB3 のバイト列を作品フォルダの `Map<string, Uint8Array>`
|
|
156
|
+
`@kubohiroya/sb3-toolchain/browser` の `unpackSb3(bytes)` は、SB3 のバイト列を作品フォルダの `Map<string, Uint8Array>` と警告の一覧に変換します。作品フォルダは展開ソース形式 1 で作ります。TurboWarp Plus Editor の画面状態(ZIP のエントリ `tw-plus/workspace.json`)は `.tw-plus/workspace.json` になります。生成されたファイルは `validateSourceFiles(files)` で再検査できます。どちらの関数も Node.js の組み込みモジュールやファイルシステムを使いません。
|
|
157
157
|
|
|
158
|
-
|
|
158
|
+
同じ入口のブロックパレットの関数(`resolveBlockPaletteReferences`・`applyBlockPaletteComments`・`extractBlockPalette`・`hasBlockPaletteSettings`)は、今は書かない[展開ソース形式 v2](docs/ja/source-format-v2.md)の作品フォルダを扱うために残しています。
|
|
159
159
|
|
|
160
160
|
参照のないハッシュ名の素材と ZIP のディレクトリエントリーは、警告を返して除外します。Plus 拡張マニフェストと参照のない添付ファイルは、対応する作品フォルダで開けないため `Sb3SourceError` の `unsupported-project` として報告します。画像・音声・フォントの参照と内容、埋め込み拡張のファイル構成を確認します。バンドルのビルドと管理対象拡張の完全な検査には CLI の `check` と `build` を使えます。
|
|
161
161
|
|
|
@@ -163,7 +163,7 @@ await unbundleSb3({
|
|
|
163
163
|
|
|
164
164
|
- [`docs/ja/workflows.md`](docs/ja/workflows.md): SB3ソースと機能拡張を管理するワークフロー
|
|
165
165
|
- [`docs/ja/source-format-v1.md`](docs/ja/source-format-v1.md): 展開ソース形式と決定的出力
|
|
166
|
-
- [`docs/ja/source-format-v2.md`](docs/ja/source-format-v2.md): ブロックパレットの設定を足した形式 v2
|
|
166
|
+
- [`docs/ja/source-format-v2.md`](docs/ja/source-format-v2.md): ブロックパレットの設定を足した形式 v2(読むだけで、今は書かない)
|
|
167
167
|
- [`docs/ja/project-asset-additions.md`](docs/ja/project-asset-additions.md): `--project-assets`のJSON/YAML、backdrop、編集/strict lock仕様
|
|
168
168
|
- [`docs/ja/extension-id-migration.md`](docs/ja/extension-id-migration.md): プロジェクトで使用中の機能拡張IDの移行
|
|
169
169
|
- [`docs/ja/extension-api-compatibility.md`](docs/ja/extension-api-compatibility.md): 機能拡張更新時の任意の静的API互換性検査
|
package/README.md
CHANGED
|
@@ -35,7 +35,7 @@ expanded sources and rebuilding bit-for-bit identical SB3 files from the same in
|
|
|
35
35
|
Pin the verified npm version for reproducible installation.
|
|
36
36
|
|
|
37
37
|
```bash
|
|
38
|
-
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.
|
|
38
|
+
pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.26.0
|
|
39
39
|
```
|
|
40
40
|
|
|
41
41
|
## Quick start
|
|
@@ -157,9 +157,9 @@ await unbundleSb3({
|
|
|
157
157
|
|
|
158
158
|
### Create a project folder in a browser
|
|
159
159
|
|
|
160
|
-
`unpackSb3(bytes)` from `@kubohiroya/sb3-toolchain/browser` expands SB3 bytes into a project folder represented by a `Map<string, Uint8Array>` and a list of warnings. The folder uses source format
|
|
160
|
+
`unpackSb3(bytes)` from `@kubohiroya/sb3-toolchain/browser` expands SB3 bytes into a project folder represented by a `Map<string, Uint8Array>` and a list of warnings. The folder uses source format 1. The TurboWarp Plus Editor screen state (the ZIP entry `tw-plus/workspace.json`) becomes `.tw-plus/workspace.json`. Use `validateSourceFiles(files)` to check the resulting files again. Both functions run without Node.js built-ins or filesystem access.
|
|
161
161
|
|
|
162
|
-
|
|
162
|
+
The block palette functions of the same entry (`resolveBlockPaletteReferences`, `applyBlockPaletteComments`, `extractBlockPalette`, `hasBlockPaletteSettings`) remain for folders in [source format v2](docs/source-format-v2.md), which is no longer written.
|
|
163
163
|
|
|
164
164
|
The browser API reports and omits unreferenced assets with hash-based filenames and directory entries. It rejects Plus extension manifests and unsupported attachments with the `Sb3SourceError` code `unsupported-project`. Validation checks image, sound and font references and bytes, and the layout of embedded extensions. Use the CLI `check` and `build` commands for bundle builds and full managed-extension validation.
|
|
165
165
|
|
|
@@ -167,7 +167,7 @@ The browser API reports and omits unreferenced assets with hash-based filenames
|
|
|
167
167
|
|
|
168
168
|
- [`docs/workflows.md`](docs/workflows.md): SB3 source and extension management workflows
|
|
169
169
|
- [`docs/source-format-v1.md`](docs/source-format-v1.md): expanded source format and deterministic output
|
|
170
|
-
- [`docs/source-format-v2.md`](docs/source-format-v2.md): format v2, which
|
|
170
|
+
- [`docs/source-format-v2.md`](docs/source-format-v2.md): format v2, which added block palette settings (read, no longer written)
|
|
171
171
|
- [`docs/project-asset-additions.md`](docs/project-asset-additions.md): JSON/YAML `--project-assets`, backdrops, and editable or strict locks
|
|
172
172
|
- [`docs/extension-id-migration.md`](docs/extension-id-migration.md): migration of extension IDs already used by a project
|
|
173
173
|
- [`docs/extension-api-compatibility.md`](docs/extension-api-compatibility.md) ([日本語](docs/ja/extension-api-compatibility.md)): opt-in static API compatibility checks for extension updates
|
package/dist/browser.js
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
import { assert, errorMessage } from "./assert.js";
|
|
2
2
|
import { applyBlockPaletteComments, blockPaletteCommentMarker, blockPaletteCommentMaxLength, blockPaletteCommentReference, blockPaletteFile, blockPaletteFormatVersion, blockPaletteSpriteCommentHeader, blockPaletteStageCommentHeader, extractBlockPalette, formatBlockPaletteComment, hasBlockPaletteSettings, resolveBlockPaletteReferences, serializeBlockPaletteDocument, validateBlockPaletteDocument } from "./block-palette.js";
|
|
3
3
|
import { validateArchiveEntryName } from "./archive.js";
|
|
4
|
-
import { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest } from "./source-format.js";
|
|
4
|
+
import { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, screenStateFile, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest } from "./source-format.js";
|
|
5
5
|
import { packageVersion } from "./constants.js";
|
|
6
6
|
import { Sb3SourceError, expandArchive, formatSourceFiles } from "./expand-archive.js";
|
|
7
7
|
import { strFromU8 } from "fflate";
|
|
@@ -54,7 +54,12 @@ function validateSourceFiles(files) {
|
|
|
54
54
|
const project = json(manifest.project);
|
|
55
55
|
assert(isObject(project), "project.source.json must contain an object.");
|
|
56
56
|
const references = validatedAssetReferences(project);
|
|
57
|
-
const assetEntries = manifest.archiveEntries.filter((name) => name !== "project.json");
|
|
57
|
+
const assetEntries = manifest.archiveEntries.filter((name) => name !== "project.json" && name !== "tw-plus/workspace.json");
|
|
58
|
+
if (files.has(".tw-plus/workspace.json")) try {
|
|
59
|
+
json(screenStateFile);
|
|
60
|
+
} catch (cause) {
|
|
61
|
+
throw new Sb3SourceError("invalid-source", `${screenStateFile} is not valid JSON: ${errorMessage(cause)}`, { cause });
|
|
62
|
+
}
|
|
58
63
|
assertSameFileSet(assetEntries, references.map(({ filename }) => filename), "Asset manifest");
|
|
59
64
|
const seen = /* @__PURE__ */ new Set();
|
|
60
65
|
for (const { filename, description } of references) {
|
|
@@ -75,6 +80,7 @@ function validateSourceFiles(files) {
|
|
|
75
80
|
"sb3-source.json",
|
|
76
81
|
manifest.project,
|
|
77
82
|
manifest.embeddedExtensions,
|
|
83
|
+
screenStateFile,
|
|
78
84
|
...manifest.blockPalette === void 0 ? [] : [manifest.blockPalette],
|
|
79
85
|
...assetEntries.map((name) => `assets/${name}`)
|
|
80
86
|
]);
|
|
@@ -102,12 +108,9 @@ function unpackSb3(bytes) {
|
|
|
102
108
|
const expanded = expandArchive(bytes, archiveLimits);
|
|
103
109
|
const references = new Set(validatedAssetReferences(expanded.project).map(({ filename }) => filename));
|
|
104
110
|
for (const name of references) if (!expanded.assets.has(name)) throw new Sb3SourceError("missing-asset", `Referenced asset is missing: ${name}`);
|
|
105
|
-
const warnings =
|
|
106
|
-
...warning,
|
|
107
|
-
path: "project.json"
|
|
108
|
-
}));
|
|
111
|
+
const warnings = [];
|
|
109
112
|
expanded.archiveEntries = expanded.archiveEntries.filter((name) => {
|
|
110
|
-
if (name === "project.json" || references.has(name)) return true;
|
|
113
|
+
if (name === "project.json" || name === "tw-plus/workspace.json" || references.has(name)) return true;
|
|
111
114
|
if (name.endsWith("/")) warnings.push({
|
|
112
115
|
code: "directory-entry",
|
|
113
116
|
path: name
|
package/dist/browser.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"browser.js","names":[],"sources":["../src/browser.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {md5} from '@noble/hashes/legacy.js';\nimport {bytesToHex} from '@noble/hashes/utils.js';\nimport {strFromU8} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {resolveBlockPaletteReferences, validateBlockPaletteDocument} from './block-palette';\nimport type {BlockPaletteWarningCode} from './block-palette';\nimport {expandArchive, formatSourceFiles, Sb3SourceError} from './expand-archive';\nimport {\n assertSameFileSet,\n collectSourceAssetReferences,\n isObject,\n validateExtensionLayout,\n validateSourceManifest,\n} from './source-format';\nimport type {ProjectJson} from './types';\n\nexport {Sb3SourceError} from './expand-archive';\nexport type {Sb3SourceErrorCode} from './expand-archive';\nexport {packageVersion} from './constants';\nexport {\n applyBlockPaletteComments,\n blockPaletteCommentMarker,\n blockPaletteCommentMaxLength,\n blockPaletteCommentReference,\n blockPaletteFile,\n blockPaletteFormatVersion,\n blockPaletteSpriteCommentHeader,\n blockPaletteStageCommentHeader,\n extractBlockPalette,\n formatBlockPaletteComment,\n hasBlockPaletteSettings,\n resolveBlockPaletteReferences,\n serializeBlockPaletteDocument,\n validateBlockPaletteDocument,\n} from './block-palette';\nexport type {\n BlockPaletteDocument,\n BlockPaletteSet,\n BlockPaletteTargetSetting,\n BlockPaletteWarning,\n BlockPaletteWarningCode,\n} from './block-palette';\nexport {\n blockPaletteSourceFormatVersion,\n sourceFormatVersion,\n supportedSourceFormatVersions,\n} from './source-format';\n\nexport interface UnpackWarning {\n code: 'directory-entry' | 'unreferenced-asset' | BlockPaletteWarningCode;\n /** The archive entry, or `project.json` for block palette comments. */\n path: string;\n /** Present for block palette warnings. */\n commentId?: string;\n message?: string;\n target?: string;\n}\n\nexport interface UnpackedSb3 {\n files: Map<string, Uint8Array>;\n warnings: UnpackWarning[];\n}\n\nconst archiveLimits = {\n maxArchiveBytes: 100 * 1024 * 1024,\n maxEntryBytes: 100 * 1024 * 1024,\n maxExpandedBytes: 512 * 1024 * 1024,\n maxEntries: 20_000,\n};\n\nfunction validateEditorProject(project: ProjectJson) {\n if (project.turboWarpPlus !== undefined) {\n throw new Sb3SourceError(\n 'unsupported-project',\n 'Plus extension manifests are not supported in project folders.',\n );\n }\n assert(Array.isArray(project.targets), 'Missing project targets.');\n const targetNames = new Set<string>();\n let stages = 0;\n for (const target of project.targets) {\n assert(\n isObject(target) && typeof target.isStage === 'boolean' && typeof target.name === 'string',\n 'Invalid project target.',\n );\n if (target.isStage) {\n stages++;\n } else {\n assert(!targetNames.has(target.name), `Duplicate sprite name: ${target.name}`);\n targetNames.add(target.name);\n }\n assert(target.blocks === undefined || isObject(target.blocks), 'Invalid target blocks.');\n assert(target.comments === undefined || isObject(target.comments), 'Invalid target comments.');\n }\n assert(stages === 1, 'Expected exactly one stage.');\n assert(\n project.extensionURLs === undefined ||\n (isObject(project.extensionURLs) &&\n Object.values(project.extensionURLs).every((url) => typeof url === 'string')),\n 'Invalid project extensionURLs.',\n );\n}\n\nfunction validatedAssetReferences(project: ProjectJson) {\n try {\n validateEditorProject(project);\n return collectSourceAssetReferences(project);\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-project', errorMessage(cause), {cause});\n }\n}\n\n/** Validate the layout and asset bytes of a project folder in memory. */\nexport function validateSourceFiles(files: ReadonlyMap<string, Uint8Array>): void {\n const json = (filename: string): unknown => {\n const bytes = files.get(filename);\n assert(bytes, `Missing source file: ${filename}`);\n return JSON.parse(strFromU8(bytes));\n };\n\n try {\n const manifest = json('sb3-source.json');\n validateSourceManifest(manifest);\n const project = json(manifest.project);\n assert(isObject(project), 'project.source.json must contain an object.');\n const references = validatedAssetReferences(project);\n\n const assetEntries = manifest.archiveEntries.filter((name) => name !== 'project.json');\n assertSameFileSet(\n assetEntries,\n references.map(({filename}) => filename),\n 'Asset manifest',\n );\n const seen = new Set<string>();\n for (const {filename, description} of references) {\n if (seen.has(filename)) continue;\n seen.add(filename);\n const asset = files.get(`assets/${filename}`);\n if (!asset) {\n throw new Sb3SourceError(\n 'missing-asset',\n `Referenced asset is missing for ${description}: ${filename}`,\n );\n }\n if (bytesToHex(md5(asset)) !== filename.slice(0, 32)) {\n throw new Sb3SourceError(\n 'invalid-asset',\n `Asset content hash mismatch for ${description}: ${filename}`,\n );\n }\n }\n\n try {\n const blockPalette =\n manifest.blockPalette === undefined\n ? null\n : validateBlockPaletteDocument(json(manifest.blockPalette));\n resolveBlockPaletteReferences(project, blockPalette);\n } catch (cause) {\n throw new Sb3SourceError('invalid-block-palette', errorMessage(cause), {cause});\n }\n\n const extensionFiles: string[] = [];\n const expected = new Set([\n 'sb3-source.json',\n manifest.project,\n manifest.embeddedExtensions,\n ...(manifest.blockPalette === undefined ? [] : [manifest.blockPalette]),\n ...assetEntries.map((name) => `assets/${name}`),\n ]);\n for (const name of files.keys()) {\n try {\n validateArchiveEntryName(name);\n } catch (cause) {\n throw new Sb3SourceError('unsafe-path', errorMessage(cause), {cause});\n }\n if (name.startsWith('extensions/')) {\n extensionFiles.push(name.slice('extensions/'.length));\n } else {\n assert(expected.has(name), `Unexpected source file: ${name}`);\n }\n }\n try {\n validateExtensionLayout(json(manifest.embeddedExtensions), project, extensionFiles);\n } catch (cause) {\n throw new Sb3SourceError('invalid-extension', errorMessage(cause), {cause});\n }\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-source', errorMessage(cause), {cause});\n }\n}\n\n/** Expand an SB3 into files suitable for opening as an Editor project folder. */\nexport function unpackSb3(bytes: Uint8Array): UnpackedSb3 {\n const expanded = expandArchive(bytes, archiveLimits);\n const references = new Set(\n validatedAssetReferences(expanded.project).map(({filename}) => filename),\n );\n for (const name of references) {\n if (!expanded.assets.has(name)) {\n throw new Sb3SourceError('missing-asset', `Referenced asset is missing: ${name}`);\n }\n }\n const warnings: UnpackWarning[] = expanded.blockPaletteWarnings.map((warning) => ({\n ...warning,\n path: 'project.json',\n }));\n expanded.archiveEntries = expanded.archiveEntries.filter((name) => {\n if (name === 'project.json' || references.has(name)) return true;\n if (name.endsWith('/')) {\n warnings.push({code: 'directory-entry', path: name});\n } else if (/^[a-f0-9]{32}\\.[A-Za-z0-9]+$/u.test(name)) {\n expanded.assets.delete(name);\n warnings.push({code: 'unreferenced-asset', path: name});\n } else {\n throw new Sb3SourceError('unsupported-project', `Unsupported SB3 attachment: ${name}`);\n }\n return false;\n });\n const files = formatSourceFiles(expanded);\n validateSourceFiles(files);\n return {files, warnings};\n}\n"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ACD,MAAM,QAAQ,kBAAkB,QAAQ;CACxC,oBAAoB,KAAK;CACzB,OAAO;EAAC;EAAO;CAAQ;AACzB"}
|
|
1
|
+
{"version":3,"file":"browser.js","names":[],"sources":["../src/browser.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {md5} from '@noble/hashes/legacy.js';\nimport {bytesToHex} from '@noble/hashes/utils.js';\nimport {strFromU8} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {resolveBlockPaletteReferences, validateBlockPaletteDocument} from './block-palette';\nimport type {BlockPaletteWarningCode} from './block-palette';\nimport {expandArchive, formatSourceFiles, Sb3SourceError} from './expand-archive';\nimport {\n assertSameFileSet,\n collectSourceAssetReferences,\n isObject,\n screenStateEntry,\n screenStateFile,\n validateExtensionLayout,\n validateSourceManifest,\n} from './source-format';\nimport type {ProjectJson} from './types';\n\nexport {Sb3SourceError} from './expand-archive';\nexport type {Sb3SourceErrorCode} from './expand-archive';\nexport {packageVersion} from './constants';\nexport {\n applyBlockPaletteComments,\n blockPaletteCommentMarker,\n blockPaletteCommentMaxLength,\n blockPaletteCommentReference,\n blockPaletteFile,\n blockPaletteFormatVersion,\n blockPaletteSpriteCommentHeader,\n blockPaletteStageCommentHeader,\n extractBlockPalette,\n formatBlockPaletteComment,\n hasBlockPaletteSettings,\n resolveBlockPaletteReferences,\n serializeBlockPaletteDocument,\n validateBlockPaletteDocument,\n} from './block-palette';\nexport type {\n BlockPaletteDocument,\n BlockPaletteSet,\n BlockPaletteTargetSetting,\n BlockPaletteWarning,\n BlockPaletteWarningCode,\n} from './block-palette';\nexport {\n blockPaletteSourceFormatVersion,\n sourceFormatVersion,\n supportedSourceFormatVersions,\n} from './source-format';\n\nexport interface UnpackWarning {\n code: 'directory-entry' | 'unreferenced-asset' | BlockPaletteWarningCode;\n /** The archive entry, or `project.json` for block palette comments. */\n path: string;\n /** Present for block palette warnings. */\n commentId?: string;\n message?: string;\n target?: string;\n}\n\nexport interface UnpackedSb3 {\n files: Map<string, Uint8Array>;\n warnings: UnpackWarning[];\n}\n\nconst archiveLimits = {\n maxArchiveBytes: 100 * 1024 * 1024,\n maxEntryBytes: 100 * 1024 * 1024,\n maxExpandedBytes: 512 * 1024 * 1024,\n maxEntries: 20_000,\n};\n\nfunction validateEditorProject(project: ProjectJson) {\n if (project.turboWarpPlus !== undefined) {\n throw new Sb3SourceError(\n 'unsupported-project',\n 'Plus extension manifests are not supported in project folders.',\n );\n }\n assert(Array.isArray(project.targets), 'Missing project targets.');\n const targetNames = new Set<string>();\n let stages = 0;\n for (const target of project.targets) {\n assert(\n isObject(target) && typeof target.isStage === 'boolean' && typeof target.name === 'string',\n 'Invalid project target.',\n );\n if (target.isStage) {\n stages++;\n } else {\n assert(!targetNames.has(target.name), `Duplicate sprite name: ${target.name}`);\n targetNames.add(target.name);\n }\n assert(target.blocks === undefined || isObject(target.blocks), 'Invalid target blocks.');\n assert(target.comments === undefined || isObject(target.comments), 'Invalid target comments.');\n }\n assert(stages === 1, 'Expected exactly one stage.');\n assert(\n project.extensionURLs === undefined ||\n (isObject(project.extensionURLs) &&\n Object.values(project.extensionURLs).every((url) => typeof url === 'string')),\n 'Invalid project extensionURLs.',\n );\n}\n\nfunction validatedAssetReferences(project: ProjectJson) {\n try {\n validateEditorProject(project);\n return collectSourceAssetReferences(project);\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-project', errorMessage(cause), {cause});\n }\n}\n\n/** Validate the layout and asset bytes of a project folder in memory. */\nexport function validateSourceFiles(files: ReadonlyMap<string, Uint8Array>): void {\n const json = (filename: string): unknown => {\n const bytes = files.get(filename);\n assert(bytes, `Missing source file: ${filename}`);\n return JSON.parse(strFromU8(bytes));\n };\n\n try {\n const manifest = json('sb3-source.json');\n validateSourceManifest(manifest);\n const project = json(manifest.project);\n assert(isObject(project), 'project.source.json must contain an object.');\n const references = validatedAssetReferences(project);\n\n const assetEntries = manifest.archiveEntries.filter(\n (name) => name !== 'project.json' && name !== screenStateEntry,\n );\n // The Editor's screen state is optional and opaque here; it only has to be JSON.\n if (files.has(screenStateFile)) {\n try {\n json(screenStateFile);\n } catch (cause) {\n throw new Sb3SourceError(\n 'invalid-source',\n `${screenStateFile} is not valid JSON: ${errorMessage(cause)}`,\n {cause},\n );\n }\n }\n assertSameFileSet(\n assetEntries,\n references.map(({filename}) => filename),\n 'Asset manifest',\n );\n const seen = new Set<string>();\n for (const {filename, description} of references) {\n if (seen.has(filename)) continue;\n seen.add(filename);\n const asset = files.get(`assets/${filename}`);\n if (!asset) {\n throw new Sb3SourceError(\n 'missing-asset',\n `Referenced asset is missing for ${description}: ${filename}`,\n );\n }\n if (bytesToHex(md5(asset)) !== filename.slice(0, 32)) {\n throw new Sb3SourceError(\n 'invalid-asset',\n `Asset content hash mismatch for ${description}: ${filename}`,\n );\n }\n }\n\n try {\n const blockPalette =\n manifest.blockPalette === undefined\n ? null\n : validateBlockPaletteDocument(json(manifest.blockPalette));\n resolveBlockPaletteReferences(project, blockPalette);\n } catch (cause) {\n throw new Sb3SourceError('invalid-block-palette', errorMessage(cause), {cause});\n }\n\n const extensionFiles: string[] = [];\n const expected = new Set([\n 'sb3-source.json',\n manifest.project,\n manifest.embeddedExtensions,\n screenStateFile,\n ...(manifest.blockPalette === undefined ? [] : [manifest.blockPalette]),\n ...assetEntries.map((name) => `assets/${name}`),\n ]);\n for (const name of files.keys()) {\n try {\n validateArchiveEntryName(name);\n } catch (cause) {\n throw new Sb3SourceError('unsafe-path', errorMessage(cause), {cause});\n }\n if (name.startsWith('extensions/')) {\n extensionFiles.push(name.slice('extensions/'.length));\n } else {\n assert(expected.has(name), `Unexpected source file: ${name}`);\n }\n }\n try {\n validateExtensionLayout(json(manifest.embeddedExtensions), project, extensionFiles);\n } catch (cause) {\n throw new Sb3SourceError('invalid-extension', errorMessage(cause), {cause});\n }\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError('invalid-source', errorMessage(cause), {cause});\n }\n}\n\n/** Expand an SB3 into files suitable for opening as an Editor project folder. */\nexport function unpackSb3(bytes: Uint8Array): UnpackedSb3 {\n const expanded = expandArchive(bytes, archiveLimits);\n const references = new Set(\n validatedAssetReferences(expanded.project).map(({filename}) => filename),\n );\n for (const name of references) {\n if (!expanded.assets.has(name)) {\n throw new Sb3SourceError('missing-asset', `Referenced asset is missing: ${name}`);\n }\n }\n const warnings: UnpackWarning[] = [];\n expanded.archiveEntries = expanded.archiveEntries.filter((name) => {\n if (name === 'project.json' || name === screenStateEntry || references.has(name)) return true;\n if (name.endsWith('/')) {\n warnings.push({code: 'directory-entry', path: name});\n } else if (/^[a-f0-9]{32}\\.[A-Za-z0-9]+$/u.test(name)) {\n expanded.assets.delete(name);\n warnings.push({code: 'unreferenced-asset', path: name});\n } else {\n throw new Sb3SourceError('unsupported-project', `Unsupported SB3 attachment: ${name}`);\n }\n return false;\n });\n const files = formatSourceFiles(expanded);\n validateSourceFiles(files);\n return {files, warnings};\n}\n"],"mappings":";;;;;;;;;;AAqEA,IAAM,gBAAgB;CACpB,iBAAiB;CACjB,eAAe;CACf,kBAAkB;CAClB,YAAY;AACd;AAEA,SAAS,sBAAsB,SAAsB;CACnD,IAAI,QAAQ,kBAAkB,KAAA,GAC5B,MAAM,IAAI,eACR,uBACA,gEACF;CAEF,OAAO,MAAM,QAAQ,QAAQ,OAAO,GAAG,0BAA0B;CACjE,MAAM,8BAAc,IAAI,IAAY;CACpC,IAAI,SAAS;CACb,KAAK,MAAM,UAAU,QAAQ,SAAS;EACpC,OACE,SAAS,MAAM,KAAK,OAAO,OAAO,YAAY,aAAa,OAAO,OAAO,SAAS,UAClF,yBACF;EACA,IAAI,OAAO,SACT;OACK;GACL,OAAO,CAAC,YAAY,IAAI,OAAO,IAAI,GAAG,0BAA0B,OAAO,MAAM;GAC7E,YAAY,IAAI,OAAO,IAAI;EAC7B;EACA,OAAO,OAAO,WAAW,KAAA,KA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AAiB,gBAAgB,MAAM;EAC3C,MAAM,IAAI,eAAe,kBAAkB,aAAa,KAAK,GAAG,EAAC,MAAK,CAAC;CACzE;AACF;;AAGA,SAAgB,UAAU,OAAgC;CACxD,MAAM,WAAW,cAAc,OAAO,aAAa;CACnD,MAAM,aAAa,IAAI,IACrB,yBAAyB,SAAS,OAAO,CAAC,CAAC,KAAK,EAAC,eAAc,QAAQ,CACzE;CACA,KAAK,MAAM,QAAQ,YACjB,IAAI,CAAC,SAAS,OAAO,IAAI,IAAI,GAC3B,MAAM,IAAI,eAAe,iBAAiB,gCAAgC,MAAM;CAGpF,MAAM,WAA4B,CAAC;CACnC,SAAS,iBAAiB,SAAS,eAAe,QAAQ,SAAS;EACjE,IAAI,SAAS,kBAAkB,SAAA,4BAA6B,WAAW,IAAI,IAAI,GAAG,OAAO;EACzF,IAAI,KAAK,SAAS,GAAG,GACnB,SAAS,KAAK;GAAC,MAAM;GAAmB,MAAM;EAAI,CAAC;OAC9C,IAAI,gCAAgC,KAAK,IAAI,GAAG;GACrD,SAAS,OAAO,OAAO,IAAI;GAC3B,SAAS,KAAK;IAAC,MAAM;IAAsB,MAAM;GAAI,CAAC;EACxD,OACE,MAAM,IAAI,eAAe,uBAAuB,+BAA+B,MAAM;EAEvF,OAAO;CACT,CAAC;CACD,MAAM,QAAQ,kBAAkB,QAAQ;CACxC,oBAAoB,KAAK;CACzB,OAAO;EAAC;EAAO;CAAQ;AACzB"}
|
package/dist/constants.d.ts
CHANGED
|
@@ -1,2 +1,2 @@
|
|
|
1
1
|
export declare const packageName = "@kubohiroya/sb3-toolchain";
|
|
2
|
-
export declare const packageVersion = "0.
|
|
2
|
+
export declare const packageVersion = "0.26.0";
|
package/dist/constants.js
CHANGED
package/dist/constants.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nexport const packageName = '@kubohiroya/sb3-toolchain';\nexport const packageVersion = '0.
|
|
1
|
+
{"version":3,"file":"constants.js","names":[],"sources":["../src/constants.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nexport const packageName = '@kubohiroya/sb3-toolchain';\nexport const packageVersion = '0.26.0';\n"],"mappings":";AAEA,IAAa,cAAc;AAC3B,IAAa,iBAAiB"}
|
package/dist/expand-archive.d.ts
CHANGED
|
@@ -1,4 +1,3 @@
|
|
|
1
|
-
import { BlockPaletteDocument, BlockPaletteWarning } from './block-palette.js';
|
|
2
1
|
import { EmbeddedExtension, ExtensionEncoding, ProjectJson } from './types.js';
|
|
3
2
|
export type Sb3SourceErrorCode = 'invalid-archive' | 'archive-limit' | 'unsafe-path' | 'invalid-project' | 'invalid-extension' | 'missing-asset' | 'invalid-asset' | 'invalid-source' | 'invalid-block-palette' | 'unsupported-project';
|
|
4
3
|
export declare class Sb3SourceError extends Error {
|
|
@@ -14,11 +13,11 @@ interface ArchiveLimits {
|
|
|
14
13
|
interface ExpandedArchive {
|
|
15
14
|
archiveEntries: string[];
|
|
16
15
|
assets: Map<string, Uint8Array>;
|
|
17
|
-
blockPalette: BlockPaletteDocument | null;
|
|
18
|
-
blockPaletteWarnings: BlockPaletteWarning[];
|
|
19
16
|
embeddedExtensions: EmbeddedExtension[];
|
|
20
17
|
extensionFiles: Map<string, Uint8Array>;
|
|
21
18
|
project: ProjectJson;
|
|
19
|
+
/** The Editor's screen state, or null for an SB3 without one. */
|
|
20
|
+
screenState: Uint8Array | null;
|
|
22
21
|
}
|
|
23
22
|
export declare function decodeExtensionBytes(dataUrl: unknown): {
|
|
24
23
|
encoding: ExtensionEncoding;
|
|
@@ -28,5 +27,5 @@ export declare function decodeExtensionBytes(dataUrl: unknown): {
|
|
|
28
27
|
};
|
|
29
28
|
/** Parse and extract the archive once. Callers choose the rules for extra ZIP entries. */
|
|
30
29
|
export declare function expandArchive(bytes: Uint8Array, limits?: ArchiveLimits): ExpandedArchive;
|
|
31
|
-
export declare function formatSourceFiles({ archiveEntries, assets,
|
|
30
|
+
export declare function formatSourceFiles({ archiveEntries, assets, embeddedExtensions, extensionFiles, project, screenState, }: ExpandedArchive): Map<string, Uint8Array>;
|
|
32
31
|
export {};
|
package/dist/expand-archive.js
CHANGED
|
@@ -1,7 +1,6 @@
|
|
|
1
1
|
import { assert, errorMessage } from "./assert.js";
|
|
2
|
-
import { blockPaletteFile, extractBlockPalette, serializeBlockPaletteDocument } from "./block-palette.js";
|
|
3
2
|
import { validateArchiveEntryName } from "./archive.js";
|
|
4
|
-
import { isObject } from "./source-format.js";
|
|
3
|
+
import { isObject, screenStateFile } from "./source-format.js";
|
|
5
4
|
import { strFromU8, strToU8, unzipSync } from "fflate";
|
|
6
5
|
//#region src/expand-archive.ts
|
|
7
6
|
var Sb3SourceError = class extends Error {
|
|
@@ -99,25 +98,19 @@ function expandArchive(bytes, limits) {
|
|
|
99
98
|
throw new Sb3SourceError("invalid-extension", errorMessage(cause), { cause });
|
|
100
99
|
}
|
|
101
100
|
}
|
|
102
|
-
|
|
103
|
-
try {
|
|
104
|
-
blockPalette = extractBlockPalette(project);
|
|
105
|
-
} catch (cause) {
|
|
106
|
-
throw new Sb3SourceError("invalid-project", errorMessage(cause), { cause });
|
|
107
|
-
}
|
|
101
|
+
const screenState = archive["tw-plus/workspace.json"] ?? null;
|
|
108
102
|
const assets = /* @__PURE__ */ new Map();
|
|
109
|
-
for (const name of archiveEntries) if (name !== "project.json" && !name.endsWith("/")) assets.set(name, archive[name]);
|
|
103
|
+
for (const name of archiveEntries) if (name !== "project.json" && name !== "tw-plus/workspace.json" && !name.endsWith("/")) assets.set(name, archive[name]);
|
|
110
104
|
return {
|
|
111
105
|
archiveEntries,
|
|
112
106
|
assets,
|
|
113
|
-
blockPalette: blockPalette.document,
|
|
114
|
-
blockPaletteWarnings: blockPalette.warnings,
|
|
115
107
|
embeddedExtensions,
|
|
116
108
|
extensionFiles,
|
|
117
|
-
project
|
|
109
|
+
project,
|
|
110
|
+
screenState
|
|
118
111
|
};
|
|
119
112
|
}
|
|
120
|
-
function formatSourceFiles({ archiveEntries, assets,
|
|
113
|
+
function formatSourceFiles({ archiveEntries, assets, embeddedExtensions, extensionFiles, project, screenState }) {
|
|
121
114
|
const files = /* @__PURE__ */ new Map();
|
|
122
115
|
for (const [name, bytes] of assets) files.set(`assets/${name}`, bytes);
|
|
123
116
|
for (const [name, bytes] of extensionFiles) files.set(name, bytes);
|
|
@@ -128,16 +121,15 @@ function formatSourceFiles({ archiveEntries, assets, blockPalette, embeddedExten
|
|
|
128
121
|
extensions: embeddedExtensions
|
|
129
122
|
},
|
|
130
123
|
"sb3-source.json": {
|
|
131
|
-
formatVersion:
|
|
124
|
+
formatVersion: 1,
|
|
132
125
|
project: "project.source.json",
|
|
133
126
|
embeddedExtensions: "embedded-extensions.json",
|
|
134
127
|
assetsDirectory: "assets",
|
|
135
|
-
archiveEntries
|
|
136
|
-
...blockPalette ? { blockPalette: blockPaletteFile } : {}
|
|
128
|
+
archiveEntries
|
|
137
129
|
}
|
|
138
130
|
};
|
|
139
131
|
for (const [name, value] of Object.entries(documents)) files.set(name, strToU8(`${JSON.stringify(value, null, 2)}\n`));
|
|
140
|
-
if (
|
|
132
|
+
if (screenState) files.set(screenStateFile, screenState);
|
|
141
133
|
return files;
|
|
142
134
|
}
|
|
143
135
|
//#endregion
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"expand-archive.js","names":[],"sources":["../src/expand-archive.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {strFromU8, strToU8, unzipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {\n blockPaletteFile,\n extractBlockPalette,\n serializeBlockPaletteDocument,\n} from './block-palette';\nimport type {BlockPaletteDocument, BlockPaletteWarning} from './block-palette';\nimport {\n blockPaletteSourceFormatVersion,\n embeddedExtensionManifestFormatVersion,\n isObject,\n sourceFormatVersion,\n} from './source-format';\nimport type {EmbeddedExtension, ExtensionEncoding, ProjectJson} from './types';\n\nexport type Sb3SourceErrorCode =\n | 'invalid-archive'\n | 'archive-limit'\n | 'unsafe-path'\n | 'invalid-project'\n | 'invalid-extension'\n | 'missing-asset'\n | 'invalid-asset'\n | 'invalid-source'\n | 'invalid-block-palette'\n | 'unsupported-project';\n\nexport class Sb3SourceError extends Error {\n constructor(\n readonly code: Sb3SourceErrorCode,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'Sb3SourceError';\n }\n}\n\ninterface ArchiveLimits {\n maxArchiveBytes: number;\n maxEntryBytes: number;\n maxEntries: number;\n maxExpandedBytes: number;\n}\n\ninterface ExpandedArchive {\n archiveEntries: string[];\n assets: Map<string, Uint8Array>;\n blockPalette: BlockPaletteDocument | null;\n blockPaletteWarnings: BlockPaletteWarning[];\n embeddedExtensions: EmbeddedExtension[];\n extensionFiles: Map<string, Uint8Array>;\n project: ProjectJson;\n}\n\nexport function decodeExtensionBytes(dataUrl: unknown): {\n encoding: ExtensionEncoding;\n mediaType: string;\n parameters: string[];\n source: Uint8Array;\n} {\n assert(\n typeof dataUrl === 'string' && dataUrl.startsWith('data:'),\n 'Embedded extension URL must be a data URL.',\n );\n const commaIndex = dataUrl.indexOf(',');\n assert(commaIndex >= 0, 'Embedded extension data URL has no payload separator.');\n\n const metadata = dataUrl.slice('data:'.length, commaIndex).split(';');\n const mediaType = metadata.shift() || 'text/plain';\n const base64Index = metadata.indexOf('base64');\n const encoding: ExtensionEncoding = base64Index >= 0 ? 'base64' : 'percent';\n if (base64Index >= 0) metadata.splice(base64Index, 1);\n\n const payload = dataUrl.slice(commaIndex + 1);\n let source: Uint8Array;\n if (encoding === 'base64') {\n assert(\n /^[A-Za-z0-9+/]*={0,2}$/u.test(payload),\n 'Embedded extension data URL contains invalid base64.',\n );\n const unpaddedPayload = payload.replace(/=+$/u, '');\n assert(\n unpaddedPayload.length % 4 !== 1,\n 'Embedded extension data URL contains invalid base64.',\n );\n const padded = unpaddedPayload.padEnd(Math.ceil(unpaddedPayload.length / 4) * 4, '=');\n source = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));\n } else {\n try {\n source = strToU8(decodeURIComponent(payload));\n } catch {\n throw new Error('Embedded extension data URL contains invalid percent encoding.');\n }\n }\n\n return {encoding, mediaType, parameters: metadata, source};\n}\n\n/** Parse and extract the archive once. Callers choose the rules for extra ZIP entries. */\nexport function expandArchive(bytes: Uint8Array, limits?: ArchiveLimits): ExpandedArchive {\n if (limits && bytes.byteLength > limits.maxArchiveBytes) {\n throw new Sb3SourceError('archive-limit', 'SB3 exceeds the maximum archive size.');\n }\n\n const seen = new Set<string>();\n let expandedBytes = 0;\n let archive: Record<string, Uint8Array>;\n try {\n archive = unzipSync(bytes, {\n filter({name, originalSize}) {\n try {\n validateArchiveEntryName(name);\n } catch (cause) {\n throw new Sb3SourceError('unsafe-path', errorMessage(cause), {cause});\n }\n if (seen.has(name)) {\n throw new Sb3SourceError('invalid-archive', `Duplicate SB3 archive entry: ${name}`);\n }\n seen.add(name);\n expandedBytes += originalSize;\n if (\n limits &&\n (seen.size > limits.maxEntries ||\n originalSize > limits.maxEntryBytes ||\n expandedBytes > limits.maxExpandedBytes)\n ) {\n throw new Sb3SourceError('archive-limit', 'Expanded SB3 exceeds the archive limits.');\n }\n return true;\n },\n });\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError(\n 'invalid-archive',\n `SB3 archive is not a valid ZIP: ${errorMessage(cause)}`,\n {cause},\n );\n }\n const archiveEntries = Object.keys(archive);\n if (archiveEntries.length === 0) {\n throw new Sb3SourceError('invalid-archive', 'SB3 archive is empty.');\n }\n if (archiveEntries.length !== seen.size) {\n throw new Sb3SourceError('invalid-archive', 'SB3 archive contains an unsupported entry name.');\n }\n\n const projectEntry = archive['project.json'];\n if (!projectEntry) {\n throw new Sb3SourceError('invalid-project', 'SB3 archive does not contain project.json.');\n }\n let project: unknown;\n try {\n project = JSON.parse(strFromU8(projectEntry));\n } catch (cause) {\n throw new Sb3SourceError(\n 'invalid-project',\n `SB3 project.json is invalid JSON: ${errorMessage(cause)}`,\n {cause},\n );\n }\n if (!isObject(project)) {\n throw new Sb3SourceError('invalid-project', 'SB3 project.json must contain a JSON object.');\n }\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n if (!isObject(extensionUrls)) {\n throw new Sb3SourceError(\n 'invalid-project',\n 'SB3 project.json extensionURLs must be an object when present.',\n );\n }\n const embeddedExtensions: EmbeddedExtension[] = [];\n const extensionFiles = new Map<string, Uint8Array>();\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n if (typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:')) continue;\n if (!/^[A-Za-z0-9._-]+$/u.test(extensionId)) {\n throw new Sb3SourceError(\n 'unsafe-path',\n `Embedded extension ID cannot be used as a filename: ${JSON.stringify(extensionId)}`,\n );\n }\n try {\n const {source, ...metadata} = decodeExtensionBytes(extensionUrl);\n const path = `extensions/${extensionId}.js`;\n extensionUrls[extensionId] = `embedded-extension:${path}`;\n embeddedExtensions.push({\n id: extensionId,\n path,\n mediaType: metadata.mediaType,\n parameters: metadata.parameters,\n encoding: metadata.encoding,\n });\n extensionFiles.set(path, source);\n } catch (cause) {\n throw new Sb3SourceError('invalid-extension', errorMessage(cause), {cause});\n }\n }\n\n let blockPalette: ReturnType<typeof extractBlockPalette>;\n try {\n blockPalette = extractBlockPalette(project);\n } catch (cause) {\n throw new Sb3SourceError('invalid-project', errorMessage(cause), {cause});\n }\n\n const assets = new Map<string, Uint8Array>();\n for (const name of archiveEntries) {\n if (name !== 'project.json' && !name.endsWith('/')) assets.set(name, archive[name]);\n }\n return {\n archiveEntries,\n assets,\n blockPalette: blockPalette.document,\n blockPaletteWarnings: blockPalette.warnings,\n embeddedExtensions,\n extensionFiles,\n project,\n };\n}\n\nexport function formatSourceFiles({\n archiveEntries,\n assets,\n blockPalette,\n embeddedExtensions,\n extensionFiles,\n project,\n}: ExpandedArchive): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>();\n for (const [name, bytes] of assets) files.set(`assets/${name}`, bytes);\n for (const [name, bytes] of extensionFiles) files.set(name, bytes);\n\n const documents = {\n 'project.source.json': project,\n 'embedded-extensions.json': {\n formatVersion: embeddedExtensionManifestFormatVersion,\n extensions: embeddedExtensions,\n },\n 'sb3-source.json': {\n formatVersion: blockPalette ? blockPaletteSourceFormatVersion : sourceFormatVersion,\n project: 'project.source.json',\n embeddedExtensions: 'embedded-extensions.json',\n assetsDirectory: 'assets',\n archiveEntries,\n ...(blockPalette ? {blockPalette: blockPaletteFile} : {}),\n },\n };\n for (const [name, value] of Object.entries(documents)) {\n files.set(name, strToU8(`${JSON.stringify(value, null, 2)}\\n`));\n }\n if (blockPalette) {\n files.set(blockPaletteFile, strToU8(serializeBlockPaletteDocument(blockPalette)));\n }\n return files;\n}\n"],"mappings":";;;;;;AAgCA,IAAa,iBAAb,cAAoC,MAAM;CAE7B;CADX,YACE,MACA,SACA,SACA;EACA,MAAM,SAAS,OAAO;EAJb,KAAA,OAAA;EAKT,KAAK,OAAO;CACd;AACF;AAmBA,SAAgB,qBAAqB,SAKnC;CACA,OACE,OAAO,YAAY,YAAY,QAAQ,WAAW,OAAO,GACzD,4CACF;CACA,MAAM,aAAa,QAAQ,QAAQ,GAAG;CACtC,OAAO,cAAc,GAAG,uDAAuD;CAE/E,MAAM,WAAW,QAAQ,MAAM,GAAgB,UAAU,CAAC,CAAC,MAAM,GAAG;CACpE,MAAM,YAAY,SAAS,MAAM,KAAK;CACtC,MAAM,cAAc,SAAS,QAAQ,QAAQ;CAC7C,MAAM,WAA8B,eAAe,IAAI,WAAW;CAClE,IAAI,eAAe,GAAG,SAAS,OAAO,aAAa,CAAC;CAEpD,MAAM,UAAU,QAAQ,MAAM,aAAa,CAAC;CAC5C,IAAI;CACJ,IAAI,aAAa,UAAU;EACzB,OACE,0BAA0B,KAAK,OAAO,GACtC,sDACF;EACA,M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EACd,MAAM,IAAI,eAAe,mBAAmB,aAAa,KAAK,GAAG,EAAC,MAAK,CAAC;CAC1E;CAEA,MAAM,yBAAS,IAAI,IAAwB;CAC3C,KAAK,MAAM,QAAQ,gBACjB,IAAI,SAAS,kBAAkB,CAAC,KAAK,SAAS,GAAG,GAAG,OAAO,IAAI,MAAM,QAAQ,KAAK;CAEpF,OAAO;EACL;EACA;EACA,cAAc,aAAa;EAC3B,sBAAsB,aAAa;EACnC;EACA;EACA;CACF;AACF;AAEA,SAAgB,kBAAkB,EAChC,gBACA,QACA,cACA,oBACA,gBACA,WAC2C;CAC3C,MAAM,wBAAQ,IAAI,IAAwB;CAC1C,KAAK,MAAM,CAAC,MAAM,UAAU,QAAQ,MAAM,IAAI,UAAU,QAAQ,KAAK;CACrE,KAAK,MAAM,CAAC,MAAM,UAAU,gBAAgB,MAAM,IAAI,MAAM,KAAK;CAEjE,MAAM,YAAY;EAChB,uBAAuB;EACvB,4BAA4B;GAC1B,eAAA;GACA,YAAY;EACd;EACA,mBAAmB;GACjB,eAAe,eAAA,IAAA;GACf,SAAS;GACT,oBAAoB;GACpB,iBAAiB;GACjB;GACA,GAAI,eAAe,EAAC,cAAc,iBAAgB,IAAI,CAAC;EACzD;CACF;CACA,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,SAAS,GAClD,MAAM,IAAI,MAAM,QAAQ,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE,GAAG,CAAC;CAEhE,IAAI,cACF,MAAM,IAAI,kBAAkB,QAAQ,8BAA8B,YAAY,CAAC,CAAC;CAElF,OAAO;AACT"}
|
|
1
|
+
{"version":3,"file":"expand-archive.js","names":[],"sources":["../src/expand-archive.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {strFromU8, strToU8, unzipSync} from 'fflate';\n\nimport {validateArchiveEntryName} from './archive';\nimport {assert, errorMessage} from './assert';\nimport {\n embeddedExtensionManifestFormatVersion,\n isObject,\n screenStateEntry,\n screenStateFile,\n sourceFormatVersion,\n} from './source-format';\nimport type {EmbeddedExtension, ExtensionEncoding, ProjectJson} from './types';\n\nexport type Sb3SourceErrorCode =\n | 'invalid-archive'\n | 'archive-limit'\n | 'unsafe-path'\n | 'invalid-project'\n | 'invalid-extension'\n | 'missing-asset'\n | 'invalid-asset'\n | 'invalid-source'\n | 'invalid-block-palette'\n | 'unsupported-project';\n\nexport class Sb3SourceError extends Error {\n constructor(\n readonly code: Sb3SourceErrorCode,\n message: string,\n options?: ErrorOptions,\n ) {\n super(message, options);\n this.name = 'Sb3SourceError';\n }\n}\n\ninterface ArchiveLimits {\n maxArchiveBytes: number;\n maxEntryBytes: number;\n maxEntries: number;\n maxExpandedBytes: number;\n}\n\ninterface ExpandedArchive {\n archiveEntries: string[];\n assets: Map<string, Uint8Array>;\n embeddedExtensions: EmbeddedExtension[];\n extensionFiles: Map<string, Uint8Array>;\n project: ProjectJson;\n /** The Editor's screen state, or null for an SB3 without one. */\n screenState: Uint8Array | null;\n}\n\nexport function decodeExtensionBytes(dataUrl: unknown): {\n encoding: ExtensionEncoding;\n mediaType: string;\n parameters: string[];\n source: Uint8Array;\n} {\n assert(\n typeof dataUrl === 'string' && dataUrl.startsWith('data:'),\n 'Embedded extension URL must be a data URL.',\n );\n const commaIndex = dataUrl.indexOf(',');\n assert(commaIndex >= 0, 'Embedded extension data URL has no payload separator.');\n\n const metadata = dataUrl.slice('data:'.length, commaIndex).split(';');\n const mediaType = metadata.shift() || 'text/plain';\n const base64Index = metadata.indexOf('base64');\n const encoding: ExtensionEncoding = base64Index >= 0 ? 'base64' : 'percent';\n if (base64Index >= 0) metadata.splice(base64Index, 1);\n\n const payload = dataUrl.slice(commaIndex + 1);\n let source: Uint8Array;\n if (encoding === 'base64') {\n assert(\n /^[A-Za-z0-9+/]*={0,2}$/u.test(payload),\n 'Embedded extension data URL contains invalid base64.',\n );\n const unpaddedPayload = payload.replace(/=+$/u, '');\n assert(\n unpaddedPayload.length % 4 !== 1,\n 'Embedded extension data URL contains invalid base64.',\n );\n const padded = unpaddedPayload.padEnd(Math.ceil(unpaddedPayload.length / 4) * 4, '=');\n source = Uint8Array.from(atob(padded), (character) => character.charCodeAt(0));\n } else {\n try {\n source = strToU8(decodeURIComponent(payload));\n } catch {\n throw new Error('Embedded extension data URL contains invalid percent encoding.');\n }\n }\n\n return {encoding, mediaType, parameters: metadata, source};\n}\n\n/** Parse and extract the archive once. Callers choose the rules for extra ZIP entries. */\nexport function expandArchive(bytes: Uint8Array, limits?: ArchiveLimits): ExpandedArchive {\n if (limits && bytes.byteLength > limits.maxArchiveBytes) {\n throw new Sb3SourceError('archive-limit', 'SB3 exceeds the maximum archive size.');\n }\n\n const seen = new Set<string>();\n let expandedBytes = 0;\n let archive: Record<string, Uint8Array>;\n try {\n archive = unzipSync(bytes, {\n filter({name, originalSize}) {\n try {\n validateArchiveEntryName(name);\n } catch (cause) {\n throw new Sb3SourceError('unsafe-path', errorMessage(cause), {cause});\n }\n if (seen.has(name)) {\n throw new Sb3SourceError('invalid-archive', `Duplicate SB3 archive entry: ${name}`);\n }\n seen.add(name);\n expandedBytes += originalSize;\n if (\n limits &&\n (seen.size > limits.maxEntries ||\n originalSize > limits.maxEntryBytes ||\n expandedBytes > limits.maxExpandedBytes)\n ) {\n throw new Sb3SourceError('archive-limit', 'Expanded SB3 exceeds the archive limits.');\n }\n return true;\n },\n });\n } catch (cause) {\n if (cause instanceof Sb3SourceError) throw cause;\n throw new Sb3SourceError(\n 'invalid-archive',\n `SB3 archive is not a valid ZIP: ${errorMessage(cause)}`,\n {cause},\n );\n }\n const archiveEntries = Object.keys(archive);\n if (archiveEntries.length === 0) {\n throw new Sb3SourceError('invalid-archive', 'SB3 archive is empty.');\n }\n if (archiveEntries.length !== seen.size) {\n throw new Sb3SourceError('invalid-archive', 'SB3 archive contains an unsupported entry name.');\n }\n\n const projectEntry = archive['project.json'];\n if (!projectEntry) {\n throw new Sb3SourceError('invalid-project', 'SB3 archive does not contain project.json.');\n }\n let project: unknown;\n try {\n project = JSON.parse(strFromU8(projectEntry));\n } catch (cause) {\n throw new Sb3SourceError(\n 'invalid-project',\n `SB3 project.json is invalid JSON: ${errorMessage(cause)}`,\n {cause},\n );\n }\n if (!isObject(project)) {\n throw new Sb3SourceError('invalid-project', 'SB3 project.json must contain a JSON object.');\n }\n\n const extensionUrls: unknown = project.extensionURLs ?? {};\n if (!isObject(extensionUrls)) {\n throw new Sb3SourceError(\n 'invalid-project',\n 'SB3 project.json extensionURLs must be an object when present.',\n );\n }\n const embeddedExtensions: EmbeddedExtension[] = [];\n const extensionFiles = new Map<string, Uint8Array>();\n for (const [extensionId, extensionUrl] of Object.entries(extensionUrls)) {\n if (typeof extensionUrl !== 'string' || !extensionUrl.startsWith('data:')) continue;\n if (!/^[A-Za-z0-9._-]+$/u.test(extensionId)) {\n throw new Sb3SourceError(\n 'unsafe-path',\n `Embedded extension ID cannot be used as a filename: ${JSON.stringify(extensionId)}`,\n );\n }\n try {\n const {source, ...metadata} = decodeExtensionBytes(extensionUrl);\n const path = `extensions/${extensionId}.js`;\n extensionUrls[extensionId] = `embedded-extension:${path}`;\n embeddedExtensions.push({\n id: extensionId,\n path,\n mediaType: metadata.mediaType,\n parameters: metadata.parameters,\n encoding: metadata.encoding,\n });\n extensionFiles.set(path, source);\n } catch (cause) {\n throw new Sb3SourceError('invalid-extension', errorMessage(cause), {cause});\n }\n }\n\n // The Editor's screen state goes to its own file, byte for byte; every other entry is an asset.\n const screenState = archive[screenStateEntry] ?? null;\n const assets = new Map<string, Uint8Array>();\n for (const name of archiveEntries) {\n if (name !== 'project.json' && name !== screenStateEntry && !name.endsWith('/')) {\n assets.set(name, archive[name]);\n }\n }\n return {\n archiveEntries,\n assets,\n embeddedExtensions,\n extensionFiles,\n project,\n screenState,\n };\n}\n\nexport function formatSourceFiles({\n archiveEntries,\n assets,\n embeddedExtensions,\n extensionFiles,\n project,\n screenState,\n}: ExpandedArchive): Map<string, Uint8Array> {\n const files = new Map<string, Uint8Array>();\n for (const [name, bytes] of assets) files.set(`assets/${name}`, bytes);\n for (const [name, bytes] of extensionFiles) files.set(name, bytes);\n\n const documents = {\n 'project.source.json': project,\n 'embedded-extensions.json': {\n formatVersion: embeddedExtensionManifestFormatVersion,\n extensions: embeddedExtensions,\n },\n 'sb3-source.json': {\n formatVersion: sourceFormatVersion,\n project: 'project.source.json',\n embeddedExtensions: 'embedded-extensions.json',\n assetsDirectory: 'assets',\n archiveEntries,\n },\n };\n for (const [name, value] of Object.entries(documents)) {\n files.set(name, strToU8(`${JSON.stringify(value, null, 2)}\\n`));\n }\n if (screenState) files.set(screenStateFile, screenState);\n return files;\n}\n"],"mappings":";;;;;AA2BA,IAAa,iBAAb,cAAoC,MAAM;CAE7B;CADX,YACE,MACA,SACA,SACA;EACA,MAAM,SAAS,OAAO;EAJb,KAAA,OAAA;EAKT,KAAK,OAAO;CACd;AACF;AAmBA,SAAgB,qBAAqB,SAKnC;CACA,OACE,OAAO,YAAY,YAAY,QAAQ,WAAW,OAAO,GACzD,4CACF;CACA,MAAM,aAAa,QAAQ,QAAQ,GAAG;CACtC,OAAO,cAAc,GAAG,uDAAuD;CAE/E,MAAM,WAAW,QAAQ,MAAM,GAAgB,UAAU,CAAC,CAAC,MAAM,GAAG;CACpE,MAAM,YAAY,SAAS,MAAM,KAAK;CACtC,MAAM,cAAc,SAAS,QAAQ,QAAQ;CAC7C,MAAM,WAA8B,eAAe,IAAI,WAAW;CAClE,IAAI,eAAe,GAAG,SAAS,OAAO,aAAa,CAAC;CAEpD,MAAM,UAAU,QAAQ,MAAM,aAAa,CAAC;CAC5C,IAAI;CACJ,IAAI,aAAa,UAAU;EACzB,OACE,0BAA0B,KAAK,OAAO,GACtC,sDACF;EACA,MAAM,kBAAkB,QAAQ,QAAQ,QAAQ,EAAE;EAClD,OACE,gBAAgB,SAAS,MAAM,GAC/B,sDACF;EACA,MAAM,SAAS,gBAAgB,OAAO,KAAK,KAAK,gBAAgB,SAAS,CAAC,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;EACA;EACA;EACA;EACA;CACF;AACF;AAEA,SAAgB,kBAAkB,EAChC,gBACA,QACA,oBACA,gBACA,SACA,eAC2C;CAC3C,MAAM,wBAAQ,IAAI,IAAwB;CAC1C,KAAK,MAAM,CAAC,MAAM,UAAU,QAAQ,MAAM,IAAI,UAAU,QAAQ,KAAK;CACrE,KAAK,MAAM,CAAC,MAAM,UAAU,gBAAgB,MAAM,IAAI,MAAM,KAAK;CAEjE,MAAM,YAAY;EAChB,uBAAuB;EACvB,4BAA4B;GAC1B,eAAA;GACA,YAAY;EACd;EACA,mBAAmB;GACjB,eAAA;GACA,SAAS;GACT,oBAAoB;GACpB,iBAAiB;GACjB;EACF;CACF;CACA,KAAK,MAAM,CAAC,MAAM,UAAU,OAAO,QAAQ,SAAS,GAClD,MAAM,IAAI,MAAM,QAAQ,GAAG,KAAK,UAAU,OAAO,MAAM,CAAC,EAAE,GAAG,CAAC;CAEhE,IAAI,aAAa,MAAM,IAAI,iBAAiB,WAAW;CACvD,OAAO;AACT"}
|
package/dist/import.js
CHANGED
|
@@ -151,7 +151,7 @@ async function importSb3({ inputPath, outputDirectory, protectedRoot = process.c
|
|
|
151
151
|
inputPath: resolvedInputPath,
|
|
152
152
|
outputDirectory: resolvedOutputDirectory,
|
|
153
153
|
rollbackCleanupWarning,
|
|
154
|
-
warnings:
|
|
154
|
+
warnings: []
|
|
155
155
|
};
|
|
156
156
|
}
|
|
157
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, 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,sBAAsB,iBAAiB,WAAW,iBAAiB;CAC1F,OACE,SAAS,SACT,6EAA6E,gBAAgB,+EAE/F;CACA,OACE,SAAS,SAAS,qBAClB,mFACK,oBAAoB,QAAQ,EAAE,yEAErC;CAEA,MAAM,UAAU;EACd;EACA;EACA;EACA;CACF;CACA,IAAI,KACF,OAAO;EAAC,QAAQ;EAAW,GAAG;CAAO;CAEvC,OACE,OAAO,mBAAmB,YAC1B,oCAAoC,gBAAgB,mFAEtD;CACA,OACE,M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E,KAAK,MAAM,CAAC,MAAM,aAAa,kBAAkB,QAAQ,GAAG;GAC1D,MAAM,aAAa,KAAK,QAAQ,oBAAoB,IAAI;GACxD,OACE,WAAW,WAAW,GAAG,qBAAqB,KAAK,KAAK,GACxD,mDAAmD,KAAK,UAAU,IAAI,GACxE;GACA,MAAM,MAAM,KAAK,QAAQ,UAAU,GAAG,EAAC,WAAW,KAAI,CAAC;GACvD,MAAM,UAAU,YAAY,QAAQ;EACtC;EACA,WAAW,MAAM,2BAA2B;GAC1C,oBAAoB;GACpB;GACA;GACA,iBAAiB;GACjB;EACF,CAAC;EACD,IAAI,SAAS,WAAW,aACtB,MAAM,GAAG,oBAAoB;GAAC,WAAW;GAAM,OAAO;EAAI,CAAC;OACtD;GACL,IAAI,SAAS,WAAW,WACtB,MAAM,4BAA4B;IAChC,oBAAoB;IACV;IACV;IACA,iBAAiB;GACnB,CAAC;GAEH,CAAC,CAAC,0BAA0B,MAAM,gCAChC,oBACA,uBACF;EACF;CACF,SAAS,OAAO;EACd,MAAM,GAAG,oBAAoB;GAAC,WAAW;GAAM,OAAO;EAAI,CAAC;EAC3D,MAAM;CACR;CAEA,OAAO;EACL,mBAAmB,SAAS,eAAe;EAC3C,YAAY,SAAS,OAAO;EAC5B,wBAAwB,SAAS,mBAAmB;EACpD,SAAS,SAAS,WAAW;EAC7B,kBAAkB,SAAS,aACvB;GACE,OAAO,SAAS,WAAW,YAAY,MAAM;GAC7C,UAAU,SAAS,WAAW,YAAY,SAAS;GACnD,SAAS,SAAS,WAAW,YAAY,QAAQ;EACnD,IACA;EACJ,WAAW;EACX,iBAAiB;EACjB;EACA,UAAU,SAAS;CACrB;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 // Import no longer moves palette comments, so it has no palette warnings; the field stays for callers.\n warnings: [],\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,sBAAsB,iBAAiB,WAAW,iBAAiB;CAC1F,OACE,SAAS,SACT,6EAA6E,gBAAgB,+EAE/F;CACA,OACE,SAAS,SAAS,qBAClB,mFACK,oBAAoB,QAAQ,EAAE,yEAErC;CAEA,MAAM,UAAU;EACd;EACA;EACA;EACA;CAC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ion = 2;
|
|
|
7
7
|
export declare const supportedSourceFormatVersions: readonly number[];
|
|
8
8
|
/** `embedded-extensions.json` keeps its own version, independent of the source format. */
|
|
9
9
|
export declare const embeddedExtensionManifestFormatVersion = 1;
|
|
10
|
+
/**
|
|
11
|
+
* The screen state TurboWarp Plus Editor saves with a project (its tab layout, block palette settings and so on).
|
|
12
|
+
* An SB3 carries it as this ZIP entry; Scratch and TurboWarp ignore it.
|
|
13
|
+
*/
|
|
14
|
+
export declare const screenStateEntry = "tw-plus/workspace.json";
|
|
15
|
+
/** Where a source folder keeps the screen state: the same file the Editor writes in a project folder. */
|
|
16
|
+
export declare const screenStateFile = ".tw-plus/workspace.json";
|
|
10
17
|
export declare function isObject(value: unknown): value is UnknownRecord;
|
|
11
18
|
export declare function assertSameFileSet(actualFiles: string[], expectedFiles: string[], description: string): void;
|
|
12
19
|
export declare function validateSourceManifest(manifest: unknown): asserts manifest is Sb3SourceManifest;
|
package/dist/source-format.js
CHANGED
|
@@ -8,6 +8,13 @@ var sourceFormatVersion = 1;
|
|
|
8
8
|
var blockPaletteSourceFormatVersion = 2;
|
|
9
9
|
/** Every source format version that readers accept. */
|
|
10
10
|
var supportedSourceFormatVersions = [1, 2];
|
|
11
|
+
/**
|
|
12
|
+
* The screen state TurboWarp Plus Editor saves with a project (its tab layout, block palette settings and so on).
|
|
13
|
+
* An SB3 carries it as this ZIP entry; Scratch and TurboWarp ignore it.
|
|
14
|
+
*/
|
|
15
|
+
var screenStateEntry = "tw-plus/workspace.json";
|
|
16
|
+
/** Where a source folder keeps the screen state: the same file the Editor writes in a project folder. */
|
|
17
|
+
var screenStateFile = ".tw-plus/workspace.json";
|
|
11
18
|
function isObject(value) {
|
|
12
19
|
return typeof value === "object" && value !== null && !Array.isArray(value);
|
|
13
20
|
}
|
|
@@ -129,6 +136,6 @@ function collectSourceAssetReferences(project) {
|
|
|
129
136
|
});
|
|
130
137
|
}
|
|
131
138
|
//#endregion
|
|
132
|
-
export { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest };
|
|
139
|
+
export { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, screenStateEntry, screenStateFile, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest };
|
|
133
140
|
|
|
134
141
|
//# 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 {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,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,EAC3C;AACF;AAEA,SAAgB,uBAAuB,UAA0D;CAC/F,OAAO,SAAS,QAAQ,GAAG,yCAAyC;CACpE,OACE,8B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,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"}
|
|
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\n/**\n * The screen state TurboWarp Plus Editor saves with a project (its tab layout, block palette settings and so on).\n * An SB3 carries it as this ZIP entry; Scratch and TurboWarp ignore it.\n */\nexport const screenStateEntry = 'tw-plus/workspace.json';\n/** Where a source folder keeps the screen state: the same file the Editor writes in a project folder. */\nexport const screenStateFile = '.tw-plus/workspace.json';\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;;;;;AAQrE,IAAa,mBAAmB;;AAEhC,IAAa,kBAAkB;AAE/B,SAAgB,SAAS,OAAwC;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iBAAiB,QAAQ,MAAM,QACzF;EACA,OAAO;GAAC,UAAU;GAAkB;EAAW;CACjD,CAAC;AACH"}
|
package/dist/source.d.ts
CHANGED
|
@@ -15,6 +15,8 @@ export interface InspectedSb3Source {
|
|
|
15
15
|
extensionContents: Map<string, Uint8Array>;
|
|
16
16
|
project: ProjectJson;
|
|
17
17
|
resolvedSourceDirectory: string;
|
|
18
|
+
/** The Editor's screen state (`.tw-plus/workspace.json`), or null when the folder has none. */
|
|
19
|
+
screenState: Uint8Array | null;
|
|
18
20
|
sourceManifest: Sb3SourceManifest;
|
|
19
21
|
}
|
|
20
22
|
export interface BlockCleanUpSummary {
|
package/dist/source.js
CHANGED
|
@@ -6,7 +6,7 @@ import { validateExtensionBundleConfigurations } from "./extension-bundle.js";
|
|
|
6
6
|
import { buildExtensionBundlesWithModules } from "./extension-module-bundle.js";
|
|
7
7
|
import { applyProjectAssetAdditions } from "./project-asset-additions.js";
|
|
8
8
|
import { cleanUpTurboWarpBlocks } from "./turbowarp-clean-up.js";
|
|
9
|
-
import { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest } from "./source-format.js";
|
|
9
|
+
import { assertSameFileSet, blockPaletteSourceFormatVersion, collectSourceAssetReferences, isObject, screenStateEntry, screenStateFile, sourceFormatVersion, supportedSourceFormatVersions, validateExtensionLayout, validateSourceManifest } from "./source-format.js";
|
|
10
10
|
import path from "node:path";
|
|
11
11
|
import { createHash } from "node:crypto";
|
|
12
12
|
import { lstat, readFile, readdir } from "node:fs/promises";
|
|
@@ -64,7 +64,18 @@ async function inspectSb3Source(sourceDirectory, validateManagedExtensions) {
|
|
|
64
64
|
await assertDirectory(resolvedSourceDirectory, "SB3 source");
|
|
65
65
|
const sourceManifest = await readJson(path.join(resolvedSourceDirectory, "sb3-source.json"), "SB3 source manifest");
|
|
66
66
|
validateSourceManifest(sourceManifest);
|
|
67
|
-
const assetEntries = sourceManifest.archiveEntries.filter((entryName) => entryName !== "project.json");
|
|
67
|
+
const assetEntries = sourceManifest.archiveEntries.filter((entryName) => entryName !== "project.json" && entryName !== "tw-plus/workspace.json");
|
|
68
|
+
let screenState = null;
|
|
69
|
+
try {
|
|
70
|
+
screenState = await readFile(path.join(resolvedSourceDirectory, screenStateFile));
|
|
71
|
+
} catch (error) {
|
|
72
|
+
if (error.code !== "ENOENT") throw error;
|
|
73
|
+
}
|
|
74
|
+
if (screenState) try {
|
|
75
|
+
JSON.parse(new TextDecoder("utf-8", { fatal: true }).decode(screenState));
|
|
76
|
+
} catch (cause) {
|
|
77
|
+
throw new Error(`${screenStateFile} is not valid JSON: ${errorMessage(cause)}`, { cause });
|
|
78
|
+
}
|
|
68
79
|
const project = await readJson(path.join(resolvedSourceDirectory, sourceManifest.project), "SB3 project source");
|
|
69
80
|
assert(isObject(project), "project.source.json must contain an object.");
|
|
70
81
|
const blockPalette = sourceManifest.blockPalette === void 0 ? null : validateBlockPaletteDocument(await readJson(path.join(resolvedSourceDirectory, sourceManifest.blockPalette), "Block palette settings"));
|
|
@@ -115,6 +126,7 @@ async function inspectSb3Source(sourceDirectory, validateManagedExtensions) {
|
|
|
115
126
|
extensionContents,
|
|
116
127
|
project,
|
|
117
128
|
resolvedSourceDirectory,
|
|
129
|
+
screenState,
|
|
118
130
|
sourceManifest
|
|
119
131
|
};
|
|
120
132
|
}
|
|
@@ -179,11 +191,17 @@ async function createDeterministicSb3(sourceDirectory, options = {}) {
|
|
|
179
191
|
}
|
|
180
192
|
project.extensionURLs = extensionUrls;
|
|
181
193
|
const archiveEntries = {};
|
|
182
|
-
|
|
194
|
+
const entryNames = [...projectAssets.archiveEntries];
|
|
195
|
+
if (source.screenState && !entryNames.includes("tw-plus/workspace.json")) entryNames.push(screenStateEntry);
|
|
196
|
+
for (const entryName of entryNames) {
|
|
183
197
|
if (entryName === "project.json") {
|
|
184
198
|
archiveEntries[entryName] = strToU8(`${JSON.stringify(project)}\n`);
|
|
185
199
|
continue;
|
|
186
200
|
}
|
|
201
|
+
if (entryName === "tw-plus/workspace.json") {
|
|
202
|
+
if (source.screenState) archiveEntries[entryName] = source.screenState;
|
|
203
|
+
continue;
|
|
204
|
+
}
|
|
187
205
|
const contents = projectAssets.assetContents.get(entryName);
|
|
188
206
|
assert(contents, `Archive entry has no contents: ${entryName}`);
|
|
189
207
|
archiveEntries[entryName] = contents;
|
|
@@ -198,7 +216,7 @@ async function createDeterministicSb3(sourceDirectory, options = {}) {
|
|
|
198
216
|
blockCleanUp,
|
|
199
217
|
bundlePlans: bundled.bundlePlans,
|
|
200
218
|
embeddedExtensionCount: bundled.extensions.length,
|
|
201
|
-
entryCount:
|
|
219
|
+
entryCount: Object.keys(archiveEntries).length,
|
|
202
220
|
projectAssetAdditions: projectAssets.summary,
|
|
203
221
|
source
|
|
204
222
|
};
|
package/dist/source.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"source.js","names":[],"sources":["../src/source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {lstat, readdir, readFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strToU8, zipSync} from 'fflate';\n\nimport {assert, errorMessage} from './assert';\nimport {\n applyBlockPaletteComments,\n resolveBlockPaletteReferences,\n validateBlockPaletteDocument,\n} from './block-palette';\nimport type {BlockPaletteDocument} from './block-palette';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateExtensionBundleConfigurations} from './extension-bundle';\nimport {buildExtensionBundlesWithModules} from './extension-module-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n validateExtensionSourceMetadata,\n validateManagedExtensionContents,\n} from './extension-dependencies';\nimport {applyProjectAssetAdditions} from './project-asset-additions';\nimport type {ProjectAssetAdditionsSummary} from './project-asset-additions';\nimport {cleanUpTurboWarpBlocks} from './turbowarp-clean-up';\nimport {\n assertSameFileSet,\n collectSourceAssetReferences,\n isObject,\n validateExtensionLayout,\n validateSourceManifest,\n} from './source-format';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectJson,\n Sb3SourceManifest,\n} from './types';\n\nexport {\n blockPaletteSourceFormatVersion,\n sourceFormatVersion,\n supportedSourceFormatVersions,\n} from './source-format';\nexport const fixedZipTimestamp = new Date(1980, 0, 1, 0, 0, 0, 0);\n\nexport interface InspectedSb3Source {\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n /** `block-palette.json` in source format 2, otherwise null. */\n blockPalette: BlockPaletteDocument | null;\n extensions: EmbeddedExtension[];\n extensionApiManifestContents: Map<string, Uint8Array>;\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n project: ProjectJson;\n resolvedSourceDirectory: string;\n sourceManifest: Sb3SourceManifest;\n}\n\nexport interface BlockCleanUpSummary {\n movedCommentCount: number;\n movedScriptCount: number;\n scriptCount: number;\n targetCount: number;\n}\n\nexport interface DeterministicSb3Options {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n projectAssetsPath?: string;\n}\n\nexport interface DeterministicSb3 {\n archive: Uint8Array;\n assetCount: number;\n assetReferenceCount: number;\n blockCleanUp: BlockCleanUpSummary | null;\n bundlePlans: ExtensionBundlePlan[];\n embeddedExtensionCount: number;\n entryCount: number;\n projectAssetAdditions: Readonly<ProjectAssetAdditionsSummary> | null;\n source: InspectedSb3Source;\n}\n\nasync function readJson(filePath: string, description: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(filePath, 'utf8'));\n } catch (error) {\n throw new Error(`${description} is not valid JSON: ${filePath} (${errorMessage(error)})`, {\n cause: error,\n });\n }\n}\n\nasync function assertDirectory(directoryPath: string, description: string): Promise<void> {\n const stats = await lstat(directoryPath);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `${description} must be a directory, not a file or symbolic link: ${directoryPath}`,\n );\n}\n\nasync function listRegularFiles(rootDirectory: string, description: string): Promise<string[]> {\n try {\n await assertDirectory(rootDirectory, description);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n const files: string[] = [];\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 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 await visit(absolutePath, relativePath);\n } else {\n assert(\n entry.isFile(),\n `${description} contains a symbolic link or unsupported entry: ${relativePath}`,\n );\n files.push(relativePath);\n }\n }\n }\n\n await visit(rootDirectory, '');\n return files;\n}\n\nfunction md5(contents: Uint8Array | string): string {\n return createHash('md5').update(contents).digest('hex');\n}\n\nfunction percentEncode(contents: Uint8Array): string {\n return [...contents]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction encodeExtensionDataUrl(extension: EmbeddedExtension, contents: Uint8Array): string {\n const metadata = [extension.mediaType, ...extension.parameters].join(';');\n if (extension.encoding === 'base64') {\n return `data:${metadata};base64,${Buffer.from(contents).toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(contents)}`;\n}\n\nasync function inspectSb3Source(\n sourceDirectory: string,\n validateManagedExtensions: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n await assertDirectory(resolvedSourceDirectory, 'SB3 source');\n const sourceManifest = await readJson(\n path.join(resolvedSourceDirectory, 'sb3-source.json'),\n 'SB3 source manifest',\n );\n validateSourceManifest(sourceManifest);\n const assetEntries = sourceManifest.archiveEntries.filter(\n (entryName) => entryName !== 'project.json',\n );\n const project: unknown = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.project),\n 'SB3 project source',\n );\n assert(isObject(project), 'project.source.json must contain an object.');\n const blockPalette =\n sourceManifest.blockPalette === undefined\n ? null\n : validateBlockPaletteDocument(\n await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.blockPalette),\n 'Block palette settings',\n ),\n );\n resolveBlockPaletteReferences(project, blockPalette);\n const extensionManifest = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.embeddedExtensions),\n 'Embedded extension manifest',\n );\n\n const assetsDirectory = path.join(resolvedSourceDirectory, sourceManifest.assetsDirectory);\n const extensionsDirectory = path.join(resolvedSourceDirectory, 'extensions');\n const [assetFiles, extensionFiles] = await Promise.all([\n listRegularFiles(assetsDirectory, 'Assets directory'),\n listRegularFiles(extensionsDirectory, 'Extensions directory'),\n ]);\n assertSameFileSet(assetFiles, assetEntries, 'Asset files');\n const {extensionBundles: bundleConfiguration, extensions} = validateExtensionLayout(\n extensionManifest,\n project,\n extensionFiles,\n validateExtensionSourceMetadata,\n );\n const extensionBundles = validateExtensionBundleConfigurations(bundleConfiguration, extensions);\n\n const assetContents = new Map<string, Uint8Array>();\n await Promise.all(\n assetFiles.map(async (assetPath) => {\n assetContents.set(assetPath, await readFile(path.join(assetsDirectory, assetPath)));\n }),\n );\n const references = collectSourceAssetReferences(project);\n const referencedAssets = new Set<string>();\n for (const {filename, description} of references) {\n if (referencedAssets.has(filename)) continue;\n const contents = assetContents.get(filename);\n assert(contents, `Referenced asset is missing for ${description}: ${filename}`);\n const assetId = filename.slice(0, 32);\n const actualAssetId = md5(contents);\n assert(\n actualAssetId === assetId,\n `Asset content hash mismatch for ${description}: expected ${assetId}, got ${actualAssetId}`,\n );\n referencedAssets.add(filename);\n }\n const unreferencedAssets = assetFiles.filter((assetPath) => !referencedAssets.has(assetPath));\n assert(\n unreferencedAssets.length === 0,\n `Asset manifest contains unreferenced files: ${unreferencedAssets.join(', ')}`,\n );\n\n const extensionContents = new Map<string, Uint8Array>();\n const extensionApiManifestContents = new Map<string, Uint8Array>();\n await Promise.all(\n extensions.map(async (extension) => {\n const contents = await readFile(path.join(resolvedSourceDirectory, extension.path));\n if (validateManagedExtensions) {\n validateManagedExtensionContents(extension, contents);\n }\n extensionContents.set(extension.id, contents);\n if (extension.source?.apiManifest) {\n const apiManifestContents = await readFile(\n path.join(resolvedSourceDirectory, extension.source.apiManifest.path),\n );\n if (validateManagedExtensions) {\n validateManagedExtensionApiManifest(extension, apiManifestContents);\n }\n extensionApiManifestContents.set(extension.id, apiManifestContents);\n }\n }),\n );\n\n return {\n assetContents,\n assetReferenceCount: references.length,\n blockPalette,\n extensions,\n extensionApiManifestContents,\n extensionBundles,\n extensionContents,\n project,\n resolvedSourceDirectory,\n sourceManifest,\n };\n}\n\nexport async function inspectSb3SourceForExtensionSync(\n sourceDirectory: string,\n): Promise<InspectedSb3Source> {\n return inspectSb3Source(sourceDirectory, false);\n}\n\nexport async function validateSb3Source(sourceDirectory: string): Promise<InspectedSb3Source> {\n const source = await inspectSb3Source(sourceDirectory, true);\n await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n return source;\n}\n\nexport async function createDeterministicSb3(\n sourceDirectory: string,\n options: DeterministicSb3Options = {},\n): Promise<DeterministicSb3> {\n const {allowedAssetRoots = [], cleanUpBlocks = false, projectAssetsPath} = options;\n assert(typeof cleanUpBlocks === 'boolean', 'cleanUpBlocks must be a boolean.');\n assert(Array.isArray(allowedAssetRoots), 'allowedAssetRoots must be an array.');\n assert(\n projectAssetsPath === undefined || typeof projectAssetsPath === 'string',\n 'projectAssetsPath must be a string when provided.',\n );\n const source = await inspectSb3Source(sourceDirectory, true);\n const projectAssets: {\n archiveEntries: string[];\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n project: ProjectJson;\n summary: Readonly<ProjectAssetAdditionsSummary> | null;\n } = projectAssetsPath\n ? await applyProjectAssetAdditions({\n allowedAssetRoots,\n assetContents: source.assetContents,\n archiveEntries: source.sourceManifest.archiveEntries,\n manifestPath: projectAssetsPath,\n project: source.project,\n })\n : {\n archiveEntries: source.sourceManifest.archiveEntries,\n assetContents: source.assetContents,\n assetReferenceCount: 0,\n project: source.project,\n summary: null,\n };\n const bundled = await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: projectAssets.project,\n });\n let project = structuredClone(bundled.project);\n let blockCleanUp: BlockCleanUpSummary | null = null;\n if (cleanUpBlocks) {\n const cleaned = cleanUpTurboWarpBlocks(project);\n project = cleaned.project;\n blockCleanUp = {\n movedCommentCount: cleaned.movedCommentCount,\n movedScriptCount: cleaned.movedScriptCount,\n scriptCount: cleaned.scriptCount,\n targetCount: cleaned.targetCount,\n };\n }\n applyBlockPaletteComments(project, source.blockPalette);\n const extensionUrls: Record<string, unknown> = project.extensionURLs ?? {};\n for (const extension of bundled.extensions) {\n const contents = bundled.extensionContents.get(extension.id);\n assert(contents, `Embedded extension has no contents: ${extension.id}`);\n extensionUrls[extension.id] = encodeExtensionDataUrl(extension, contents);\n }\n project.extensionURLs = extensionUrls;\n\n const archiveEntries: Record<string, Uint8Array> = {};\n for (const entryName of projectAssets.archiveEntries) {\n if (entryName === 'project.json') {\n archiveEntries[entryName] = strToU8(`${JSON.stringify(project)}\\n`);\n continue;\n }\n const contents = projectAssets.assetContents.get(entryName);\n assert(contents, `Archive entry has no contents: ${entryName}`);\n archiveEntries[entryName] = contents;\n }\n const archive = zipSync(archiveEntries, {\n level: 6,\n mtime: fixedZipTimestamp,\n });\n\n return {\n archive,\n assetCount: projectAssets.assetContents.size,\n assetReferenceCount: source.assetReferenceCount + projectAssets.assetReferenceCount,\n blockCleanUp,\n bundlePlans: bundled.bundlePlans,\n embeddedExtensionCount: bundled.extensions.length,\n entryCount: projectAssets.archiveEntries.length,\n projectAssetAdditions: projectAssets.summary,\n source,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA6CA,IAAa,oBAA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EAC1B,YAAY,OAAO;EACnB,SAAS,cAAc;CACzB,CAAC;CACD,IAAI,UAAU,gBAAgB,QAAQ,OAAO;CAC7C,IAAI,eAA2C;CAC/C,IAAI,eAAe;EACjB,MAAM,UAAU,uBAAuB,OAAO;EAC9C,UAAU,QAAQ;EAClB,eAAe;GACb,mBAAmB,QAAQ;GAC3B,kBAAkB,QAAQ;GAC1B,aAAa,QAAQ;GACrB,aAAa,QAAQ;EACvB;CACF;CACA,0BAA0B,SAAS,OAAO,YAAY;CACtD,MAAM,gBAAyC,QAAQ,iBAAiB,CAAC;CACzE,KAAK,MAAM,aAAa,QAAQ,YAAY;EAC1C,MAAM,WAAW,QAAQ,kBAAkB,IAAI,UAAU,EAAE;EAC3D,OAAO,UAAU,uCAAuC,UAAU,IAAI;EACtE,cAAc,UAAU,MAAM,uBAAuB,WAAW,QAAQ;CAC1E;CACA,QAAQ,gBAAgB;CAExB,MAAM,iBAA6C,CAAC;CACpD,KAAK,MAAM,aAAa,cAAc,gBAAgB;EACpD,IAAI,cAAc,gBAAgB;GAChC,eAAe,aAAa,QAAQ,GAAG,KAAK,UAAU,OAAO,EAAE,GAAG;GAClE;EACF;EACA,MAAM,WAAW,cAAc,cAAc,IAAI,SAAS;EAC1D,OAAO,UAAU,kCAAkC,WAAW;EAC9D,eAAe,aAAa;CAC9B;CAMA,OAAO;EACL,SANc,QAAQ,gBAAgB;GACtC,OAAO;GACP,OAAO;EACT,CAGE;EACA,YAAY,cAAc,cAAc;EACxC,qBAAqB,OAAO,sBAAsB,cAAc;EAChE;EACA,aAAa,QAAQ;EACrB,wBAAwB,QAAQ,WAAW;EAC3C,YAAY,cAAc,eAAe;EACzC,uBAAuB,cAAc;EACrC;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"source.js","names":[],"sources":["../src/source.ts"],"sourcesContent":["// SPDX-License-Identifier: MPL-2.0\n\nimport {createHash} from 'node:crypto';\nimport {lstat, readdir, readFile} from 'node:fs/promises';\nimport path from 'node:path';\n\nimport {strToU8, zipSync} from 'fflate';\n\nimport {assert, errorMessage} from './assert';\nimport {\n applyBlockPaletteComments,\n resolveBlockPaletteReferences,\n validateBlockPaletteDocument,\n} from './block-palette';\nimport type {BlockPaletteDocument} from './block-palette';\nimport {validateManagedExtensionApiManifest} from './extension-api-manifest';\nimport {validateExtensionBundleConfigurations} from './extension-bundle';\nimport {buildExtensionBundlesWithModules} from './extension-module-bundle';\nimport type {ExtensionBundlePlan} from './extension-bundle';\nimport {\n validateExtensionSourceMetadata,\n validateManagedExtensionContents,\n} from './extension-dependencies';\nimport {applyProjectAssetAdditions} from './project-asset-additions';\nimport type {ProjectAssetAdditionsSummary} from './project-asset-additions';\nimport {cleanUpTurboWarpBlocks} from './turbowarp-clean-up';\nimport {\n assertSameFileSet,\n collectSourceAssetReferences,\n isObject,\n screenStateEntry,\n screenStateFile,\n validateExtensionLayout,\n validateSourceManifest,\n} from './source-format';\nimport type {\n EmbeddedExtension,\n ExtensionBundleConfiguration,\n ProjectJson,\n Sb3SourceManifest,\n} from './types';\n\nexport {\n blockPaletteSourceFormatVersion,\n sourceFormatVersion,\n supportedSourceFormatVersions,\n} from './source-format';\nexport const fixedZipTimestamp = new Date(1980, 0, 1, 0, 0, 0, 0);\n\nexport interface InspectedSb3Source {\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n /** `block-palette.json` in source format 2, otherwise null. */\n blockPalette: BlockPaletteDocument | null;\n extensions: EmbeddedExtension[];\n extensionApiManifestContents: Map<string, Uint8Array>;\n extensionBundles: ExtensionBundleConfiguration[];\n extensionContents: Map<string, Uint8Array>;\n project: ProjectJson;\n resolvedSourceDirectory: string;\n /** The Editor's screen state (`.tw-plus/workspace.json`), or null when the folder has none. */\n screenState: Uint8Array | null;\n sourceManifest: Sb3SourceManifest;\n}\n\nexport interface BlockCleanUpSummary {\n movedCommentCount: number;\n movedScriptCount: number;\n scriptCount: number;\n targetCount: number;\n}\n\nexport interface DeterministicSb3Options {\n allowedAssetRoots?: string[];\n cleanUpBlocks?: boolean;\n projectAssetsPath?: string;\n}\n\nexport interface DeterministicSb3 {\n archive: Uint8Array;\n assetCount: number;\n assetReferenceCount: number;\n blockCleanUp: BlockCleanUpSummary | null;\n bundlePlans: ExtensionBundlePlan[];\n embeddedExtensionCount: number;\n entryCount: number;\n projectAssetAdditions: Readonly<ProjectAssetAdditionsSummary> | null;\n source: InspectedSb3Source;\n}\n\nasync function readJson(filePath: string, description: string): Promise<unknown> {\n try {\n return JSON.parse(await readFile(filePath, 'utf8'));\n } catch (error) {\n throw new Error(`${description} is not valid JSON: ${filePath} (${errorMessage(error)})`, {\n cause: error,\n });\n }\n}\n\nasync function assertDirectory(directoryPath: string, description: string): Promise<void> {\n const stats = await lstat(directoryPath);\n assert(\n stats.isDirectory() && !stats.isSymbolicLink(),\n `${description} must be a directory, not a file or symbolic link: ${directoryPath}`,\n );\n}\n\nasync function listRegularFiles(rootDirectory: string, description: string): Promise<string[]> {\n try {\n await assertDirectory(rootDirectory, description);\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code === 'ENOENT') return [];\n throw error;\n }\n const files: string[] = [];\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 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 await visit(absolutePath, relativePath);\n } else {\n assert(\n entry.isFile(),\n `${description} contains a symbolic link or unsupported entry: ${relativePath}`,\n );\n files.push(relativePath);\n }\n }\n }\n\n await visit(rootDirectory, '');\n return files;\n}\n\nfunction md5(contents: Uint8Array | string): string {\n return createHash('md5').update(contents).digest('hex');\n}\n\nfunction percentEncode(contents: Uint8Array): string {\n return [...contents]\n .map((byte) => `%${byte.toString(16).padStart(2, '0').toUpperCase()}`)\n .join('');\n}\n\nfunction encodeExtensionDataUrl(extension: EmbeddedExtension, contents: Uint8Array): string {\n const metadata = [extension.mediaType, ...extension.parameters].join(';');\n if (extension.encoding === 'base64') {\n return `data:${metadata};base64,${Buffer.from(contents).toString('base64')}`;\n }\n return `data:${metadata},${percentEncode(contents)}`;\n}\n\nasync function inspectSb3Source(\n sourceDirectory: string,\n validateManagedExtensions: boolean,\n): Promise<InspectedSb3Source> {\n const resolvedSourceDirectory = path.resolve(sourceDirectory);\n await assertDirectory(resolvedSourceDirectory, 'SB3 source');\n const sourceManifest = await readJson(\n path.join(resolvedSourceDirectory, 'sb3-source.json'),\n 'SB3 source manifest',\n );\n validateSourceManifest(sourceManifest);\n const assetEntries = sourceManifest.archiveEntries.filter(\n (entryName) => entryName !== 'project.json' && entryName !== screenStateEntry,\n );\n // The Editor writes its screen state into the folder whenever it saves; it is optional and only has to be JSON.\n let screenState: Uint8Array | null = null;\n try {\n screenState = await readFile(path.join(resolvedSourceDirectory, screenStateFile));\n } catch (error) {\n if ((error as NodeJS.ErrnoException).code !== 'ENOENT') throw error;\n }\n if (screenState) {\n try {\n JSON.parse(new TextDecoder('utf-8', {fatal: true}).decode(screenState));\n } catch (cause) {\n throw new Error(`${screenStateFile} is not valid JSON: ${errorMessage(cause)}`, {cause});\n }\n }\n const project: unknown = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.project),\n 'SB3 project source',\n );\n assert(isObject(project), 'project.source.json must contain an object.');\n const blockPalette =\n sourceManifest.blockPalette === undefined\n ? null\n : validateBlockPaletteDocument(\n await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.blockPalette),\n 'Block palette settings',\n ),\n );\n resolveBlockPaletteReferences(project, blockPalette);\n const extensionManifest = await readJson(\n path.join(resolvedSourceDirectory, sourceManifest.embeddedExtensions),\n 'Embedded extension manifest',\n );\n\n const assetsDirectory = path.join(resolvedSourceDirectory, sourceManifest.assetsDirectory);\n const extensionsDirectory = path.join(resolvedSourceDirectory, 'extensions');\n const [assetFiles, extensionFiles] = await Promise.all([\n listRegularFiles(assetsDirectory, 'Assets directory'),\n listRegularFiles(extensionsDirectory, 'Extensions directory'),\n ]);\n assertSameFileSet(assetFiles, assetEntries, 'Asset files');\n const {extensionBundles: bundleConfiguration, extensions} = validateExtensionLayout(\n extensionManifest,\n project,\n extensionFiles,\n validateExtensionSourceMetadata,\n );\n const extensionBundles = validateExtensionBundleConfigurations(bundleConfiguration, extensions);\n\n const assetContents = new Map<string, Uint8Array>();\n await Promise.all(\n assetFiles.map(async (assetPath) => {\n assetContents.set(assetPath, await readFile(path.join(assetsDirectory, assetPath)));\n }),\n );\n const references = collectSourceAssetReferences(project);\n const referencedAssets = new Set<string>();\n for (const {filename, description} of references) {\n if (referencedAssets.has(filename)) continue;\n const contents = assetContents.get(filename);\n assert(contents, `Referenced asset is missing for ${description}: ${filename}`);\n const assetId = filename.slice(0, 32);\n const actualAssetId = md5(contents);\n assert(\n actualAssetId === assetId,\n `Asset content hash mismatch for ${description}: expected ${assetId}, got ${actualAssetId}`,\n );\n referencedAssets.add(filename);\n }\n const unreferencedAssets = assetFiles.filter((assetPath) => !referencedAssets.has(assetPath));\n assert(\n unreferencedAssets.length === 0,\n `Asset manifest contains unreferenced files: ${unreferencedAssets.join(', ')}`,\n );\n\n const extensionContents = new Map<string, Uint8Array>();\n const extensionApiManifestContents = new Map<string, Uint8Array>();\n await Promise.all(\n extensions.map(async (extension) => {\n const contents = await readFile(path.join(resolvedSourceDirectory, extension.path));\n if (validateManagedExtensions) {\n validateManagedExtensionContents(extension, contents);\n }\n extensionContents.set(extension.id, contents);\n if (extension.source?.apiManifest) {\n const apiManifestContents = await readFile(\n path.join(resolvedSourceDirectory, extension.source.apiManifest.path),\n );\n if (validateManagedExtensions) {\n validateManagedExtensionApiManifest(extension, apiManifestContents);\n }\n extensionApiManifestContents.set(extension.id, apiManifestContents);\n }\n }),\n );\n\n return {\n assetContents,\n assetReferenceCount: references.length,\n blockPalette,\n extensions,\n extensionApiManifestContents,\n extensionBundles,\n extensionContents,\n project,\n resolvedSourceDirectory,\n screenState,\n sourceManifest,\n };\n}\n\nexport async function inspectSb3SourceForExtensionSync(\n sourceDirectory: string,\n): Promise<InspectedSb3Source> {\n return inspectSb3Source(sourceDirectory, false);\n}\n\nexport async function validateSb3Source(sourceDirectory: string): Promise<InspectedSb3Source> {\n const source = await inspectSb3Source(sourceDirectory, true);\n await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: source.project,\n });\n return source;\n}\n\nexport async function createDeterministicSb3(\n sourceDirectory: string,\n options: DeterministicSb3Options = {},\n): Promise<DeterministicSb3> {\n const {allowedAssetRoots = [], cleanUpBlocks = false, projectAssetsPath} = options;\n assert(typeof cleanUpBlocks === 'boolean', 'cleanUpBlocks must be a boolean.');\n assert(Array.isArray(allowedAssetRoots), 'allowedAssetRoots must be an array.');\n assert(\n projectAssetsPath === undefined || typeof projectAssetsPath === 'string',\n 'projectAssetsPath must be a string when provided.',\n );\n const source = await inspectSb3Source(sourceDirectory, true);\n const projectAssets: {\n archiveEntries: string[];\n assetContents: Map<string, Uint8Array>;\n assetReferenceCount: number;\n project: ProjectJson;\n summary: Readonly<ProjectAssetAdditionsSummary> | null;\n } = projectAssetsPath\n ? await applyProjectAssetAdditions({\n allowedAssetRoots,\n assetContents: source.assetContents,\n archiveEntries: source.sourceManifest.archiveEntries,\n manifestPath: projectAssetsPath,\n project: source.project,\n })\n : {\n archiveEntries: source.sourceManifest.archiveEntries,\n assetContents: source.assetContents,\n assetReferenceCount: 0,\n project: source.project,\n summary: null,\n };\n const bundled = await buildExtensionBundlesWithModules({\n sourceDirectory: source.resolvedSourceDirectory,\n extensionBundles: source.extensionBundles,\n extensionContents: source.extensionContents,\n extensions: source.extensions,\n project: projectAssets.project,\n });\n let project = structuredClone(bundled.project);\n let blockCleanUp: BlockCleanUpSummary | null = null;\n if (cleanUpBlocks) {\n const cleaned = cleanUpTurboWarpBlocks(project);\n project = cleaned.project;\n blockCleanUp = {\n movedCommentCount: cleaned.movedCommentCount,\n movedScriptCount: cleaned.movedScriptCount,\n scriptCount: cleaned.scriptCount,\n targetCount: cleaned.targetCount,\n };\n }\n applyBlockPaletteComments(project, source.blockPalette);\n const extensionUrls: Record<string, unknown> = project.extensionURLs ?? {};\n for (const extension of bundled.extensions) {\n const contents = bundled.extensionContents.get(extension.id);\n assert(contents, `Embedded extension has no contents: ${extension.id}`);\n extensionUrls[extension.id] = encodeExtensionDataUrl(extension, contents);\n }\n project.extensionURLs = extensionUrls;\n\n const archiveEntries: Record<string, Uint8Array> = {};\n // The screen state keeps its place in the archive; one the Editor wrote after the import goes last.\n const entryNames = [...projectAssets.archiveEntries];\n if (source.screenState && !entryNames.includes(screenStateEntry))\n entryNames.push(screenStateEntry);\n for (const entryName of entryNames) {\n if (entryName === 'project.json') {\n archiveEntries[entryName] = strToU8(`${JSON.stringify(project)}\\n`);\n continue;\n }\n if (entryName === screenStateEntry) {\n if (source.screenState) archiveEntries[entryName] = source.screenState;\n continue;\n }\n const contents = projectAssets.assetContents.get(entryName);\n assert(contents, `Archive entry has no contents: ${entryName}`);\n archiveEntries[entryName] = contents;\n }\n const archive = zipSync(archiveEntries, {\n level: 6,\n mtime: fixedZipTimestamp,\n });\n\n return {\n archive,\n assetCount: projectAssets.assetContents.size,\n assetReferenceCount: source.assetReferenceCount + projectAssets.assetReferenceCount,\n blockCleanUp,\n bundlePlans: bundled.bundlePlans,\n embeddedExtensionCount: bundled.extensions.length,\n entryCount: Object.keys(archiveEntries).length,\n projectAssetAdditions: projectAssets.summary,\n source,\n };\n}\n"],"mappings":";;;;;;;;;;;;;;AA+CA,IAAa,oBAAoB,IAAI,KAAK,MAAM,GAAG,GAAG,GAAG,GAAG,GAAG,CAAC;AA2ChE,eAAe,SAAS,UAAkB,aAAuC;CAC/E,IAAI;EACF,OAAO,KAAK,MAAM,MAAM,SAAS,UAAU,MAAM,CAAC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e,aAAa;CAC9B;CAMA,OAAO;EACL,SANc,QAAQ,gBAAgB;GACtC,OAAO;GACP,OAAO;EACT,CAGE;EACA,YAAY,cAAc,cAAc;EACxC,qBAAqB,OAAO,sBAAsB,cAAc;EAChE;EACA,aAAa,QAAQ;EACrB,wBAAwB,QAAQ,WAAW;EAC3C,YAAY,OAAO,KAAK,cAAc,CAAC,CAAC;EACxC,uBAAuB,cAAc;EACrC;CACF;AACF"}
|
package/docs/index.html
CHANGED
|
@@ -69,7 +69,7 @@
|
|
|
69
69
|
<body>
|
|
70
70
|
<header>
|
|
71
71
|
<h1>SB3 Toolchain</h1>
|
|
72
|
-
<p><code>@kubohiroya/sb3-toolchain@0.
|
|
72
|
+
<p><code>@kubohiroya/sb3-toolchain@0.26.0</code></p>
|
|
73
73
|
<nav aria-label="Documentation">
|
|
74
74
|
<a href="#scope">責務</a><a href="#usage">使い方</a><a href="#api">API</a
|
|
75
75
|
><a href="#schemas">Schema</a><a href="#guides">関連文書</a>
|
|
@@ -90,7 +90,7 @@
|
|
|
90
90
|
<section id="usage">
|
|
91
91
|
<h2>使い方</h2>
|
|
92
92
|
<p>公開済みの完全固定versionを使います。</p>
|
|
93
|
-
<pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.
|
|
93
|
+
<pre><code>npm install --save-exact @kubohiroya/sb3-toolchain@0.26.0</code></pre>
|
|
94
94
|
<pre><code>sb3-toolchain import tmp/project.sb3 --output app
|
|
95
95
|
sb3-toolchain check app
|
|
96
96
|
sb3-toolchain build app --output dist/project.sb3</code></pre>
|
|
@@ -2,7 +2,7 @@
|
|
|
2
2
|
|
|
3
3
|
[English](../source-format-v1.md)
|
|
4
4
|
|
|
5
|
-
|
|
5
|
+
import と unpack は、いつも v1 で書く。0.25 がブロックパレットのコメントのある作品に書いた[形式 v2](source-format-v2.md)の作品フォルダも、引き続き読んで build できる。
|
|
6
6
|
|
|
7
7
|
## レイアウト
|
|
8
8
|
|
|
@@ -11,12 +11,16 @@ SOURCE_DIR/
|
|
|
11
11
|
├── sb3-source.json
|
|
12
12
|
├── project.source.json
|
|
13
13
|
├── embedded-extensions.json
|
|
14
|
+
├── .tw-plus/
|
|
15
|
+
│ └── workspace.json (任意)
|
|
14
16
|
├── assets/
|
|
15
17
|
│ └── <assetId>.<dataFormat>
|
|
16
18
|
└── extensions/
|
|
17
19
|
└── <extensionId>.js
|
|
18
20
|
```
|
|
19
21
|
|
|
22
|
+
`.tw-plus/workspace.json` は、TurboWarp Plus Editor が作品と一緒に保存する画面状態である。タブの配置や、スプライトごとにパレットに出すブロックグループなどが入る。SB3 では ZIP のエントリ `tw-plus/workspace.json` で、Scratch と TurboWarp はこれを無視する。import はこのエントリをバイト列のままこのファイルに写し、`archiveEntries` にも記録する。build は同じ位置に戻す。エディターは作品フォルダを保存するときにこのファイルを自分で書く。`archiveEntries` に載っていないこのファイルは、SB3 の最後のエントリになる。toolchain は JSON であることだけを確かめ、ファイルのない作品フォルダはこのエントリなしで build する。
|
|
23
|
+
|
|
20
24
|
`sb3-source.json`は、形式のバージョン、各構成要素へのパス、元のSB3におけるZIPエントリ順を記録します。
|
|
21
25
|
|
|
22
26
|
```json
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
[English](../source-format-v2.md)
|
|
4
4
|
|
|
5
|
+
> **今は書かない。** 0.26 から、import と unpack は[形式 v1](source-format-v1.md) で書き、パレットのコメントは普通のコメントのまま残す。TurboWarp Plus Editor は、ブロックパレットの設定をコメントではなく画面状態(`.tw-plus/workspace.json`)に保存するようになった。この形式の作品フォルダも、引き続き読んで build できる。
|
|
6
|
+
|
|
5
7
|
形式 v2 は、[形式 v1](source-format-v1.md) にブロックパレットの設定を足したものである。設定とは、スプライト・背景ごとに、ブロックパレットにどのブロックグループを表示するかである。ここに書いていないことは v1 と同じ。
|
|
6
8
|
|
|
7
9
|
## どちらの版で書くか
|
package/docs/source-format-v1.md
CHANGED
|
@@ -2,8 +2,8 @@
|
|
|
2
2
|
|
|
3
3
|
[日本語版](ja/source-format-v1.md)
|
|
4
4
|
|
|
5
|
-
|
|
6
|
-
|
|
5
|
+
Import and unpack always write v1. Folders in [format v2](source-format-v2.md), which 0.25 wrote for
|
|
6
|
+
projects with block palette comments, are still read and built.
|
|
7
7
|
|
|
8
8
|
## Layout
|
|
9
9
|
|
|
@@ -12,12 +12,21 @@ SOURCE_DIR/
|
|
|
12
12
|
├── sb3-source.json
|
|
13
13
|
├── project.source.json
|
|
14
14
|
├── embedded-extensions.json
|
|
15
|
+
├── .tw-plus/
|
|
16
|
+
│ └── workspace.json (optional)
|
|
15
17
|
├── assets/
|
|
16
18
|
│ └── <assetId>.<dataFormat>
|
|
17
19
|
└── extensions/
|
|
18
20
|
└── <extensionId>.js
|
|
19
21
|
```
|
|
20
22
|
|
|
23
|
+
`.tw-plus/workspace.json` is the screen state TurboWarp Plus Editor saves with a project: its tab layout,
|
|
24
|
+
the block groups each sprite shows in the palette, and so on. An SB3 carries it as the ZIP entry
|
|
25
|
+
`tw-plus/workspace.json`, which Scratch and TurboWarp ignore. Import copies the entry to this file byte for
|
|
26
|
+
byte and lists it in `archiveEntries`; build puts the file back in the same place. The Editor writes the file
|
|
27
|
+
itself when it saves a project folder; such a file, not listed in `archiveEntries`, becomes the last entry of
|
|
28
|
+
the SB3. The toolchain only checks that it is JSON, and a folder without it builds without the entry.
|
|
29
|
+
|
|
21
30
|
`sb3-source.json` records the format version, paths to each component, and the ZIP entry order of the
|
|
22
31
|
original SB3.
|
|
23
32
|
|
package/docs/source-format-v2.md
CHANGED
|
@@ -2,6 +2,10 @@
|
|
|
2
2
|
|
|
3
3
|
[日本語版](ja/source-format-v2.md)
|
|
4
4
|
|
|
5
|
+
> **No longer written.** Since 0.26, import and unpack write [format v1](source-format-v1.md) and keep
|
|
6
|
+
> palette comments as plain comments. TurboWarp Plus Editor now saves block palette settings in its screen
|
|
7
|
+
> state (`.tw-plus/workspace.json`), not in comments. Folders in this format are still read and built.
|
|
8
|
+
|
|
5
9
|
Format v2 is [format v1](source-format-v1.md) plus block palette settings: which block groups the
|
|
6
10
|
block palette shows for each sprite and for the stage. Everything not described here is the same as
|
|
7
11
|
in v1.
|
package/package.json
CHANGED