@kubohiroya/sb3-toolchain 0.5.0 → 0.6.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/README.ja.md CHANGED
@@ -15,6 +15,7 @@ Scratch 3およびTurboWarpの`.sb3`プロジェクトを、Gitで差分を確
15
15
  - 元のJavaScriptを削除せず、複数の機能拡張を1つの権限単位へ静的にbundleし、展開ソースまたは
16
16
  bundle済みSB3から復元
17
17
  - ZIPエントリ順、タイムスタンプ、圧縮設定を固定した決定的ビルド
18
+ - 展開済みbase sourceを変更せず、JSON/YAML build manifestからsprite、backdrop、costume、soundを追加
18
19
  - 全ターゲットのスクリプトをTurboWarp風の決定的な「きれいにする」配置へ任意で整理
19
20
  - import時に未コミットのGit変更を保護
20
21
  - トランザクションによる置換とロールバックで既存出力を保護
@@ -30,7 +31,7 @@ Scratch 3およびTurboWarpの`.sb3`プロジェクトを、Gitで差分を確
30
31
  再現可能なインストールのため、検証済みのnpmバージョンを固定します。
31
32
 
32
33
  ```bash
33
- pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.5.0
34
+ pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.6.0
34
35
  ```
35
36
 
36
37
  ## クイックスタート
@@ -132,6 +133,7 @@ await unbundleSb3({
132
133
 
133
134
  - [`docs/ja/workflows.md`](docs/ja/workflows.md): SB3ソースと機能拡張を管理するワークフロー
134
135
  - [`docs/ja/source-format-v1.md`](docs/ja/source-format-v1.md): 展開ソース形式と決定的出力
136
+ - [`docs/ja/project-asset-additions.md`](docs/ja/project-asset-additions.md): `--project-assets`のJSON/YAML、backdrop、編集/strict lock仕様
135
137
  - [`docs/ja/extension-id-migration.md`](docs/ja/extension-id-migration.md): プロジェクトで使用中の機能拡張IDの移行
136
138
  - [`docs/ja/extension-api-compatibility.md`](docs/ja/extension-api-compatibility.md): 機能拡張更新時の任意の静的API互換性検査
137
139
  - [`docs/ja/extension-bundles.md`](docs/ja/extension-bundles.md): 1つの権限単位への静的bundleと可逆的なunbundle
package/README.md CHANGED
@@ -15,6 +15,8 @@ expanded sources and rebuilding bit-for-bit identical SB3 files from the same in
15
15
  - Statically bundle multiple extensions into one permission unit without deleting their original
16
16
  JavaScript, then restore them from either the expanded source or the bundled SB3
17
17
  - Produce deterministic builds with fixed ZIP entry order, timestamps, and compression settings
18
+ - Add sprites, backdrops, costumes, and sounds from an optional JSON or YAML build manifest without
19
+ modifying the expanded base source
18
20
  - Optionally lay out every target's scripts in a deterministic TurboWarp-style cleaned arrangement
19
21
  - Protect uncommitted Git changes when importing
20
22
  - Protect existing output through transactional replacement and rollback
@@ -30,7 +32,7 @@ expanded sources and rebuilding bit-for-bit identical SB3 files from the same in
30
32
  Pin the verified npm version for reproducible installation.
31
33
 
32
34
  ```bash
33
- pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.5.0
35
+ pnpm add --save-dev --save-exact @kubohiroya/sb3-toolchain@0.6.0
34
36
  ```
35
37
 
36
38
  ## Quick start
@@ -132,6 +134,7 @@ await unbundleSb3({
132
134
 
133
135
  - [`docs/workflows.md`](docs/workflows.md): SB3 source and extension management workflows
134
136
  - [`docs/source-format-v1.md`](docs/source-format-v1.md): expanded source format and deterministic output
137
+ - [`docs/project-asset-additions.md`](docs/project-asset-additions.md): JSON/YAML `--project-assets`, backdrops, and editable or strict locks
135
138
  - [`docs/extension-id-migration.md`](docs/extension-id-migration.md): migration of extension IDs already used by a project
136
139
  - [`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
137
140
  - [`docs/extension-bundles.md`](docs/extension-bundles.md): static bundling into one permission unit and reversible unbundling
@@ -0,0 +1,200 @@
1
+ # `--project-assets`: project asset追加build入力
2
+
3
+ `--project-assets`は、展開済みSB3 sourceを編集せず、生成するSB3にStage backdrop、sprite costume、
4
+ stage/sprite sound、新規spriteを追加するためのbuild入力です。JSONとYAMLを使用できます。
5
+
6
+ ```bash
7
+ sb3-toolchain check app \
8
+ --project-assets stories/my-story/project-assets.yml \
9
+ --allow-asset-root resources
10
+
11
+ sb3-toolchain build app \
12
+ --project-assets stories/my-story/project-assets.yml \
13
+ --allow-asset-root resources \
14
+ --output dist/my-story.sb3
15
+ ```
16
+
17
+ `check`はSB3を書き出さず、base sourceとproject assetsをメモリ上で合成して検証します。`build`だけが
18
+ 出力SB3を生成します。どちらもbase sourceの`project.source.json`、`sb3-source.json`、`assets/`を
19
+ 変更しません。
20
+
21
+ ## YAML形式(推奨)
22
+
23
+ `.yml`または`.yaml`は、DSL 4.0の`assets:`と同様に、asset IDをmapping key、`kind`をasset種別として
24
+ 記述します。新規spriteの表示属性だけを`sprites:`へ分離します。
25
+
26
+ ```yaml
27
+ formatVersion: 1
28
+
29
+ sprites:
30
+ Princess:
31
+ layerOrder: 6
32
+ visible: false
33
+ x: 4
34
+ y: -16
35
+ size: 70
36
+ direction: 90
37
+ draggable: false
38
+ rotationStyle: all around
39
+ volume: 100
40
+
41
+ assets:
42
+ Princess:
43
+ kind: costume
44
+ target: Princess
45
+ file: ../../resources/Princess.png
46
+ bitmapResolution: 2
47
+ rotationCenterX: 507
48
+ rotationCenterY: 507
49
+ license: 'CC-BY-SA-4.0: ../../LICENSES.md'
50
+
51
+ DragonCastle:
52
+ kind: backdrop
53
+ file: ../../resources/DragonCastle.svg
54
+ rotationCenterX: 240
55
+ rotationCenterY: 180
56
+
57
+ OpeningSound:
58
+ kind: sound
59
+ file: ../../resources/OpeningSound.mp3
60
+
61
+ PrincessVoice:
62
+ kind: sound
63
+ target: Princess
64
+ file: ../../resources/PrincessVoice.wav
65
+ ```
66
+
67
+ - `backdrop`は常にStageの`costumes`へ追加します。`target`は指定しません。
68
+ - `costume`は`target`で指定したspriteの`costumes`へ追加します。
69
+ - `sound`は`target`省略時にStage、指定時にそのspriteの`sounds`へ追加します。
70
+ - 既存spriteへ追加する場合、そのspriteを`sprites:`へ重ねて宣言する必要はありません。
71
+ - 新規spriteは`sprites:`で宣言し、`assets:`から1件以上のcostumeを割り当てます。
72
+ - asset ID(例: `Princess`)がScratch内のcostume/backdrop/sound名になります。別名にする場合だけ
73
+ `name`を指定します。
74
+
75
+ YAMLは1.2として解釈します。duplicate key、複数document、anchor、alias、merge key、custom tag、
76
+ `__proto__`/`constructor`/`prototype` keyを拒否します。YAMLコメントは使用できます。
77
+
78
+ ## JSON形式
79
+
80
+ `.json`はYAMLと同じfield構成です。次は上のPrincess部分と等価です。
81
+
82
+ ```json
83
+ {
84
+ "formatVersion": 1,
85
+ "sprites": {
86
+ "Princess": {
87
+ "layerOrder": 6,
88
+ "visible": false,
89
+ "x": 4,
90
+ "y": -16,
91
+ "size": 70,
92
+ "direction": 90,
93
+ "draggable": false,
94
+ "rotationStyle": "all around",
95
+ "volume": 100
96
+ }
97
+ },
98
+ "assets": {
99
+ "Princess": {
100
+ "kind": "costume",
101
+ "target": "Princess",
102
+ "file": "../../resources/Princess.png",
103
+ "bitmapResolution": 2,
104
+ "rotationCenterX": 507,
105
+ "rotationCenterY": 507
106
+ }
107
+ }
108
+ }
109
+ ```
110
+
111
+ JSONでもduplicate keyを拒否します。`.json`、`.yml`、`.yaml`以外の拡張子は受け付けません。
112
+
113
+ ## 編集用の通常モード
114
+
115
+ 画像を描き直したり、音声を録り直したりしながら同じファイルへ上書きする場合、`size`と`sha256`は
116
+ 記述しません。`file`の現在のbyte列を正本として、buildごとにScratch用MD5 `assetId`を再計算します。
117
+
118
+ 画像では次を指定します。
119
+
120
+ | field | 必須 | 内容 |
121
+ | ------------------------------------ | --------------- | --------------------------------- |
122
+ | `kind` | 必須 | `backdrop`または`costume` |
123
+ | `target` | costumeだけ必須 | 追加先sprite名 |
124
+ | `file` | 必須 | manifestからの相対path |
125
+ | `rotationCenterX`, `rotationCenterY` | 必須 | Scratchの回転中心 |
126
+ | `bitmapResolution` | 任意 | `1`(既定)または`2` |
127
+ | `name` | 任意 | Scratch内の名前。省略時はasset ID |
128
+
129
+ 音声では通常、`kind: sound`と`file`だけで足ります。open-sourceの`music-metadata`を使ってMP3/WAVを
130
+ 解析し、`rate`と`sampleCount`を自動取得します。sprite soundだけは`target`も指定します。`dataFormat`は画像・音声ともfile拡張子から
131
+ 取得します。
132
+
133
+ ## 配布用のstrict lock
134
+
135
+ 再現対象の入力byte列を固定する場合だけ、次のfieldを追加します。fieldごとに独立して検証するため、
136
+ 必要なものだけ指定できます。
137
+
138
+ ```yaml
139
+ assets:
140
+ Princess:
141
+ kind: costume
142
+ target: Princess
143
+ file: ../../resources/Princess.png
144
+ rotationCenterX: 507
145
+ rotationCenterY: 507
146
+ size: 220534
147
+ sha256: e9d1857528a619e4a56ebd232fea4767fd6bdd00b20ac67a90c859c6b3598e83
148
+ dataFormat: png
149
+ ```
150
+
151
+ | strict field | 検証内容 |
152
+ | --------------------- | -------------------------------------- |
153
+ | `size` | fileのbyte数と一致すること |
154
+ | `sha256` | fileのSHA-256と一致すること |
155
+ | `dataFormat` | file拡張子から得たformatと一致すること |
156
+ | `rate`, `sampleCount` | 音声から自動取得した値と一致すること |
157
+
158
+ 指定していないstrict fieldは不一致判定に使用しません。`license`は任意の1行の出典・ライセンス情報として
159
+ 検証しますが、Scratchの`project.json`にはコピーしません。
160
+
161
+ 同じbase source、manifest、asset byte列、toolchain versionからはbit-for-bit同一のSB3を生成します。
162
+ 通常モードでasset fileを上書きすれば、次のbuild結果が変わるのは意図した動作です。配布時に意図しない
163
+ 上書きを検出する必要があれば`size`と`sha256`を指定します。
164
+
165
+ ## pathと入力の安全性
166
+
167
+ asset fileは既定でmanifest directory内に限定します。共有素材directoryを参照する場合だけ、
168
+ repeatableな`--allow-asset-root`で明示的に許可します。
169
+
170
+ ```bash
171
+ sb3-toolchain build app \
172
+ --project-assets stories/my-story/project-assets.yml \
173
+ --allow-asset-root resources/images \
174
+ --allow-asset-root resources/sounds \
175
+ --output dist/my-story.sb3
176
+ ```
177
+
178
+ 絶対path、許可rootからの逸脱、symlink経由、通常file以外、拡張子と指定`dataFormat`の不一致、既存の
179
+ target/costume/backdrop/sound名との衝突はfail-closedで拒否します。manifest自体は1 MiB以下の
180
+ 通常fileである必要があります。
181
+
182
+ ## JavaScript API
183
+
184
+ CLIと同じ入力を`createDeterministicSb3`または`buildSb3`へ渡せます。
185
+
186
+ ```js
187
+ await createDeterministicSb3('app', {
188
+ projectAssetsPath: 'stories/my-story/project-assets.yml',
189
+ allowedAssetRoots: ['resources'],
190
+ });
191
+
192
+ await buildSb3({
193
+ sourceDirectory: 'app',
194
+ projectAssetsPath: 'stories/my-story/project-assets.yml',
195
+ allowedAssetRoots: ['resources'],
196
+ outputPath: 'dist/my-story.sb3',
197
+ });
198
+ ```
199
+
200
+ `projectAssetsPath`を指定しなければ、project assetを追加しない従来のbuildへ戻ります。
@@ -0,0 +1,165 @@
1
+ # `--project-assets`: project asset build input
2
+
3
+ `--project-assets` adds Stage backdrops, sprite costumes, Stage or sprite sounds, and new sprites to
4
+ a generated SB3 without editing its expanded base source. Both JSON and YAML are supported.
5
+
6
+ ```bash
7
+ sb3-toolchain check app \
8
+ --project-assets stories/my-story/project-assets.yml \
9
+ --allow-asset-root resources
10
+
11
+ sb3-toolchain build app \
12
+ --project-assets stories/my-story/project-assets.yml \
13
+ --allow-asset-root resources \
14
+ --output dist/my-story.sb3
15
+ ```
16
+
17
+ `check` composes and validates the base source and project assets in memory. Only `build` writes an
18
+ SB3. Neither command modifies `project.source.json`, `sb3-source.json`, or the expanded `assets/`.
19
+
20
+ ## YAML format (recommended)
21
+
22
+ Like DSL 4.0 `assets:`, `.yml` and `.yaml` use the asset ID as a mapping key and `kind` as the asset
23
+ type. Display properties for newly created sprites are kept separately under `sprites:`.
24
+
25
+ ```yaml
26
+ formatVersion: 1
27
+
28
+ sprites:
29
+ Princess:
30
+ layerOrder: 6
31
+ visible: false
32
+ x: 4
33
+ y: -16
34
+ size: 70
35
+ direction: 90
36
+ draggable: false
37
+ rotationStyle: all around
38
+ volume: 100
39
+
40
+ assets:
41
+ Princess:
42
+ kind: costume
43
+ target: Princess
44
+ file: ../../resources/Princess.png
45
+ bitmapResolution: 2
46
+ rotationCenterX: 507
47
+ rotationCenterY: 507
48
+ license: 'CC-BY-SA-4.0: ../../LICENSES.md'
49
+
50
+ DragonCastle:
51
+ kind: backdrop
52
+ file: ../../resources/DragonCastle.svg
53
+ rotationCenterX: 240
54
+ rotationCenterY: 180
55
+
56
+ OpeningSound:
57
+ kind: sound
58
+ file: ../../resources/OpeningSound.mp3
59
+
60
+ PrincessVoice:
61
+ kind: sound
62
+ target: Princess
63
+ file: ../../resources/PrincessVoice.wav
64
+ ```
65
+
66
+ - A `backdrop` is added to the Stage `costumes` and does not accept `target`.
67
+ - A `costume` is added to the sprite named by `target`.
68
+ - A `sound` is added to the Stage when `target` is omitted, or to the named sprite otherwise.
69
+ - An existing sprite does not need a duplicate declaration under `sprites:`.
70
+ - A new sprite is declared under `sprites:` and must receive at least one costume from `assets:`.
71
+ - The asset ID becomes its Scratch costume, backdrop, or sound name. Set `name` only to override it.
72
+
73
+ YAML uses version 1.2. Duplicate keys, multiple documents, anchors, aliases, merge keys, custom
74
+ tags, and `__proto__`, `constructor`, or `prototype` keys are rejected. YAML comments are allowed.
75
+
76
+ ## JSON format
77
+
78
+ `.json` uses the same fields. The following is equivalent to the Princess part above.
79
+
80
+ ```json
81
+ {
82
+ "formatVersion": 1,
83
+ "sprites": {
84
+ "Princess": {
85
+ "layerOrder": 6,
86
+ "visible": false,
87
+ "x": 4,
88
+ "y": -16,
89
+ "size": 70,
90
+ "direction": 90,
91
+ "draggable": false,
92
+ "rotationStyle": "all around",
93
+ "volume": 100
94
+ }
95
+ },
96
+ "assets": {
97
+ "Princess": {
98
+ "kind": "costume",
99
+ "target": "Princess",
100
+ "file": "../../resources/Princess.png",
101
+ "bitmapResolution": 2,
102
+ "rotationCenterX": 507,
103
+ "rotationCenterY": 507
104
+ }
105
+ }
106
+ }
107
+ ```
108
+
109
+ Duplicate JSON keys are rejected. Manifest filenames must end in `.json`, `.yml`, or `.yaml`.
110
+
111
+ ## Editable mode
112
+
113
+ Omit `size` and `sha256` while repeatedly overwriting an image or audio file. The current file
114
+ bytes are authoritative and the Scratch MD5 `assetId` is recomputed for every build.
115
+
116
+ Images require `kind`, `file`, `rotationCenterX`, and `rotationCenterY`; costumes also require
117
+ `target`. `bitmapResolution` is optional and defaults to `1`. `dataFormat` is inferred from the
118
+ filename extension.
119
+
120
+ Sounds normally require only `kind: sound` and `file`. The open-source `music-metadata` library
121
+ parses MP3 and WAV files to infer `rate` and `sampleCount`. Only a sprite sound also requires
122
+ `target`.
123
+
124
+ ## Optional strict locks
125
+
126
+ Add any of these fields when a distribution build must verify its reviewed input:
127
+
128
+ | Field | Check |
129
+ | --------------------- | --------------------------------------- |
130
+ | `size` | Exact file byte length |
131
+ | `sha256` | Exact file SHA-256 |
132
+ | `dataFormat` | Format inferred from the file extension |
133
+ | `rate`, `sampleCount` | Values inferred from an audio file |
134
+
135
+ Each supplied field is checked independently. Omitted fields do not lock content. Optional
136
+ single-line `license` provenance is validated but is not copied into Scratch `project.json`.
137
+
138
+ Identical base source, manifest, asset bytes, and toolchain version produce a bit-for-bit identical
139
+ SB3. Overwriting an asset in editable mode intentionally changes the next build. Add `size` and
140
+ `sha256` when accidental overwrites must fail instead.
141
+
142
+ ## Path safety
143
+
144
+ Files are confined to the manifest directory by default. Use repeatable `--allow-asset-root` only
145
+ for intentional shared directories. Absolute paths, escaping an allowed root, symlink traversal,
146
+ special files, format mismatches, and target or asset name collisions are rejected. The manifest
147
+ itself must be a regular file no larger than 1 MiB.
148
+
149
+ ## JavaScript API and rollback
150
+
151
+ ```js
152
+ await createDeterministicSb3('app', {
153
+ projectAssetsPath: 'stories/my-story/project-assets.yml',
154
+ allowedAssetRoots: ['resources'],
155
+ });
156
+
157
+ await buildSb3({
158
+ sourceDirectory: 'app',
159
+ projectAssetsPath: 'stories/my-story/project-assets.yml',
160
+ allowedAssetRoots: ['resources'],
161
+ outputPath: 'dist/my-story.sb3',
162
+ });
163
+ ```
164
+
165
+ Omit `projectAssetsPath` to return to the existing build behavior without project additions.
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/sb3-toolchain",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "description": "Git-friendly source management and deterministic builds for Scratch 3 and TurboWarp SB3 projects",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -45,7 +45,9 @@
45
45
  "prepack": "pnpm check"
46
46
  },
47
47
  "dependencies": {
48
- "fflate": "0.8.3"
48
+ "fflate": "0.8.3",
49
+ "music-metadata": "11.14.0",
50
+ "yaml": "2.9.0"
49
51
  },
50
52
  "devDependencies": {
51
53
  "@types/node": "^24.0.0",
package/src/build.js CHANGED
@@ -152,15 +152,32 @@ export async function writeSb3Archive({
152
152
  };
153
153
  }
154
154
 
155
+ /**
156
+ * @param {{
157
+ * allowedAssetRoots?: string[],
158
+ * cleanUpBlocks?: boolean,
159
+ * confirmReplace?: (outputPath: string) => Promise<boolean>,
160
+ * outputPath: string,
161
+ * projectAssetsPath?: string,
162
+ * sourceDirectory: string,
163
+ * yes?: boolean,
164
+ * }} options
165
+ */
155
166
  export async function buildSb3({
167
+ allowedAssetRoots = [],
156
168
  cleanUpBlocks = false,
157
169
  confirmReplace,
158
170
  outputPath,
171
+ projectAssetsPath,
159
172
  sourceDirectory,
160
173
  yes = false,
161
174
  }) {
162
175
  assert(typeof sourceDirectory === 'string', 'SB3 source directory is required.');
163
- const built = await createDeterministicSb3(sourceDirectory, {cleanUpBlocks});
176
+ const built = await createDeterministicSb3(sourceDirectory, {
177
+ allowedAssetRoots,
178
+ cleanUpBlocks,
179
+ projectAssetsPath,
180
+ });
164
181
  const written = await writeSb3Archive({
165
182
  archive: built.archive,
166
183
  confirmReplace,
package/src/cli.js CHANGED
@@ -11,8 +11,13 @@ import {unbundleSb3} from './extension-bundle-archive.js';
11
11
  import {migrateExtensionId} from './extension-id-migration.js';
12
12
  import {extensionStatus, syncExtensions, updateExtensions} from './extension-sync.js';
13
13
  import {importSb3} from './import.js';
14
- import {validateSb3Source} from './source.js';
14
+ import {createDeterministicSb3, validateSb3Source} from './source.js';
15
15
 
16
+ /**
17
+ * @param {unknown} condition
18
+ * @param {string} message
19
+ * @returns {asserts condition}
20
+ */
16
21
  function assert(condition, message) {
17
22
  if (!condition) {
18
23
  throw new Error(message);
@@ -22,8 +27,8 @@ function assert(condition, message) {
22
27
  export function usage() {
23
28
  return `Usage:
24
29
  sb3-toolchain import INPUT.sb3 --output SOURCE_DIR [--yes] [--discard-local-changes]
25
- sb3-toolchain check SOURCE_DIR
26
- sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--clean-up-blocks] [--yes]
30
+ sb3-toolchain check SOURCE_DIR [--project-assets MANIFEST.json] [--allow-asset-root DIR ...]
31
+ sb3-toolchain build SOURCE_DIR --output OUTPUT.sb3 [--project-assets MANIFEST.json] [--allow-asset-root DIR ...] [--clean-up-blocks] [--yes]
27
32
  sb3-toolchain extensions status SOURCE_DIR
28
33
  sb3-toolchain extensions sync SOURCE_DIR [--yes]
29
34
  sb3-toolchain extensions update SOURCE_DIR [EXTENSION_ID] [--migrate-id NEW_ID] [--artifact PATH] [--api-manifest-artifact PATH] [--allow-breaking-api --yes]
@@ -44,6 +49,11 @@ Build layout cleanup:
44
49
  variables, lists, or comments. The expanded source is unchanged, but the
45
50
  generated SB3 might not be able to undo the coordinate changes.
46
51
 
52
+ Project asset additions:
53
+ --project-assets validates a JSON or YAML manifest and adds its sprites,
54
+ backdrops, costumes, and sounds only to the generated SB3. Input files are confined to the
55
+ manifest directory unless --allow-asset-root explicitly permits another root.
56
+
47
57
  Replacement safety:
48
58
  Differing outputs require interactive confirmation or --yes.
49
59
  Import refuses to discard uncommitted Git changes unless
@@ -88,24 +98,63 @@ function parseImportArguments(arguments_) {
88
98
  return {command: 'import', discardLocalChanges, inputPath, outputDirectory, yes};
89
99
  }
90
100
 
101
+ /**
102
+ * @param {string[]} arguments_
103
+ * @returns {{allowedAssetRoots?: string[], command: 'check', projectAssetsPath?: string, sourceDirectory: string}}
104
+ */
91
105
  function parseCheckArguments(arguments_) {
106
+ const allowedAssetRoots = [];
107
+ let projectAssetsPath;
108
+ let sourceDirectory;
109
+ for (let index = 0; index < arguments_.length; index += 1) {
110
+ const argument = arguments_[index];
111
+ if (argument === '--project-assets') {
112
+ projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));
113
+ index += 1;
114
+ } else if (argument === '--allow-asset-root') {
115
+ allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));
116
+ index += 1;
117
+ } else {
118
+ assert(!argument.startsWith('-'), `Unknown option: ${argument}`);
119
+ assert(!sourceDirectory, 'Only one SB3 source directory may be specified.');
120
+ sourceDirectory = path.resolve(argument);
121
+ }
122
+ }
123
+ assert(sourceDirectory, 'The check command requires SOURCE_DIR.');
92
124
  assert(
93
- arguments_.length === 1 && !arguments_[0].startsWith('-'),
94
- 'The check command requires exactly one SOURCE_DIR.',
125
+ allowedAssetRoots.length === 0 || projectAssetsPath,
126
+ '--allow-asset-root requires --project-assets.',
95
127
  );
96
- return {command: 'check', sourceDirectory: path.resolve(arguments_[0])};
128
+ return {
129
+ ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),
130
+ command: 'check',
131
+ ...(projectAssetsPath ? {projectAssetsPath} : {}),
132
+ sourceDirectory,
133
+ };
97
134
  }
98
135
 
136
+ /**
137
+ * @param {string[]} arguments_
138
+ * @returns {{allowedAssetRoots?: string[], cleanUpBlocks?: boolean, command: 'build', outputPath: string, projectAssetsPath?: string, sourceDirectory: string, yes: boolean}}
139
+ */
99
140
  function parseBuildArguments(arguments_) {
141
+ const allowedAssetRoots = [];
100
142
  let cleanUpBlocks = false;
101
143
  let sourceDirectory;
102
144
  let outputPath;
145
+ let projectAssetsPath;
103
146
  let yes = false;
104
147
 
105
148
  for (let index = 0; index < arguments_.length; index += 1) {
106
149
  const argument = arguments_[index];
107
150
  if (argument === '--clean-up-blocks') {
108
151
  cleanUpBlocks = true;
152
+ } else if (argument === '--project-assets') {
153
+ projectAssetsPath = path.resolve(takeValue(arguments_, index, '--project-assets'));
154
+ index += 1;
155
+ } else if (argument === '--allow-asset-root') {
156
+ allowedAssetRoots.push(path.resolve(takeValue(arguments_, index, '--allow-asset-root')));
157
+ index += 1;
109
158
  } else if (argument === '--output') {
110
159
  outputPath = path.resolve(takeValue(arguments_, index, '--output'));
111
160
  index += 1;
@@ -120,10 +169,16 @@ function parseBuildArguments(arguments_) {
120
169
 
121
170
  assert(sourceDirectory, 'The build command requires SOURCE_DIR.');
122
171
  assert(outputPath, 'The build command requires --output OUTPUT.sb3.');
172
+ assert(
173
+ allowedAssetRoots.length === 0 || projectAssetsPath,
174
+ '--allow-asset-root requires --project-assets.',
175
+ );
123
176
  return {
177
+ ...(allowedAssetRoots.length > 0 ? {allowedAssetRoots} : {}),
124
178
  ...(cleanUpBlocks ? {cleanUpBlocks} : {}),
125
179
  command: 'build',
126
180
  outputPath,
181
+ ...(projectAssetsPath ? {projectAssetsPath} : {}),
127
182
  sourceDirectory,
128
183
  yes,
129
184
  };
@@ -485,6 +540,22 @@ export async function runCli(
485
540
  return;
486
541
  }
487
542
  if (options.command === 'check') {
543
+ assert(
544
+ 'sourceDirectory' in options && !('action' in options),
545
+ 'Internal CLI check command routing error.',
546
+ );
547
+ if (options.projectAssetsPath) {
548
+ const result = await createDeterministicSb3(options.sourceDirectory, {
549
+ allowedAssetRoots: options.allowedAssetRoots,
550
+ projectAssetsPath: options.projectAssetsPath,
551
+ });
552
+ log(
553
+ `Valid SB3 source with project assets: ${result.source.resolvedSourceDirectory} ` +
554
+ `(${result.entryCount} entries, ${result.assetCount} assets, ` +
555
+ `${result.assetReferenceCount} references, ${result.embeddedExtensionCount} embedded extensions).`,
556
+ );
557
+ return;
558
+ }
488
559
  const result = await validateSb3Source(options.sourceDirectory);
489
560
  log(
490
561
  `Valid SB3 source: ${result.resolvedSourceDirectory} ` +
@@ -494,11 +565,18 @@ export async function runCli(
494
565
  );
495
566
  return;
496
567
  }
497
- if (options.command === 'build' && 'outputPath' in options) {
568
+ if (
569
+ options.command === 'build' &&
570
+ 'outputPath' in options &&
571
+ 'sourceDirectory' in options &&
572
+ !('action' in options)
573
+ ) {
498
574
  const result = await buildSb3({
575
+ allowedAssetRoots: options.allowedAssetRoots,
499
576
  cleanUpBlocks: options.cleanUpBlocks,
500
577
  confirmReplace: confirmBuildReplacement,
501
578
  outputPath: options.outputPath,
579
+ projectAssetsPath: options.projectAssetsPath,
502
580
  sourceDirectory: options.sourceDirectory,
503
581
  yes: options.yes,
504
582
  });
package/src/constants.js CHANGED
@@ -1,4 +1,4 @@
1
1
  // SPDX-License-Identifier: MPL-2.0
2
2
 
3
3
  export const packageName = '@kubohiroya/sb3-toolchain';
4
- export const packageVersion = '0.5.0';
4
+ export const packageVersion = '0.6.0';
package/src/index.js CHANGED
@@ -57,4 +57,8 @@ export {
57
57
  sourceFormatVersion,
58
58
  validateSb3Source,
59
59
  } from './source.js';
60
+ export {
61
+ applyProjectAssetAdditions,
62
+ projectAssetAdditionsFormatVersion,
63
+ } from './project-asset-additions.js';
60
64
  export {cleanUpTurboWarpBlocks, turboWarpCleanUpLayout} from './turbowarp-clean-up.js';
@@ -0,0 +1,560 @@
1
+ // SPDX-License-Identifier: MPL-2.0
2
+
3
+ import {createHash} from 'node:crypto';
4
+ import {lstat, readFile, realpath} from 'node:fs/promises';
5
+ import path from 'node:path';
6
+
7
+ import {parseBuffer} from 'music-metadata';
8
+ import {isAlias, isPair, parseAllDocuments, visit} from 'yaml';
9
+
10
+ export const projectAssetAdditionsFormatVersion = 1;
11
+
12
+ const maximumManifestBytes = 1024 * 1024;
13
+ const forbiddenMappingKeys = new Set(['__proto__', 'constructor', 'prototype']);
14
+ const lockedAssetKeys = new Set(['name', 'file', 'size', 'sha256', 'dataFormat', 'license']);
15
+ const imageAssetKeys = new Set([
16
+ ...lockedAssetKeys,
17
+ 'kind',
18
+ 'target',
19
+ 'bitmapResolution',
20
+ 'rotationCenterX',
21
+ 'rotationCenterY',
22
+ ]);
23
+ const soundAssetKeys = new Set([...lockedAssetKeys, 'kind', 'target', 'rate', 'sampleCount']);
24
+ const imageFormats = new Set(['svg', 'png', 'jpg', 'jpeg', 'gif']);
25
+ const soundFormats = new Map([
26
+ ['wav', 'audio/wav'],
27
+ ['mp3', 'audio/mpeg'],
28
+ ]);
29
+
30
+ function assert(condition, message) {
31
+ if (!condition) throw new Error(message);
32
+ }
33
+
34
+ function isRecord(value) {
35
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
36
+ }
37
+
38
+ function exactKeys(value, allowed, description) {
39
+ const unknown = Object.keys(value).filter((key) => !allowed.has(key));
40
+ assert(unknown.length === 0, `${description} has unknown properties: ${unknown.join(', ')}`);
41
+ }
42
+
43
+ function nonEmptyString(value, description) {
44
+ assert(
45
+ typeof value === 'string' &&
46
+ value.length > 0 &&
47
+ value === value.normalize('NFC') &&
48
+ !/[\u0000-\u001f\u007f]/u.test(value),
49
+ `${description} must be a non-empty NFC string without control characters.`,
50
+ );
51
+ assert(!forbiddenMappingKeys.has(value), `${description} is not supported: ${value}`);
52
+ return value;
53
+ }
54
+
55
+ function finiteNumber(value, description) {
56
+ assert(typeof value === 'number' && Number.isFinite(value), `${description} must be finite.`);
57
+ return value;
58
+ }
59
+
60
+ function safeInteger(value, description, minimum = 0) {
61
+ assert(
62
+ Number.isSafeInteger(value) && value >= minimum,
63
+ `${description} must be a safe integer greater than or equal to ${minimum}.`,
64
+ );
65
+ return value;
66
+ }
67
+
68
+ function sha256(contents) {
69
+ return createHash('sha256').update(contents).digest('hex');
70
+ }
71
+
72
+ function md5(contents) {
73
+ return createHash('md5').update(contents).digest('hex');
74
+ }
75
+
76
+ function parseRestrictedYaml(source, manifestPath) {
77
+ const documents = parseAllDocuments(source, {
78
+ prettyErrors: false,
79
+ strict: true,
80
+ uniqueKeys: true,
81
+ version: '1.2',
82
+ });
83
+ const parserIssues = documents.flatMap((document) => [...document.errors, ...document.warnings]);
84
+ assert(
85
+ parserIssues.length === 0,
86
+ `Project asset additions manifest is not valid YAML: ${manifestPath} ` +
87
+ `(${parserIssues[0]?.message})`,
88
+ );
89
+ assert(
90
+ documents.length === 1,
91
+ `Project asset additions manifest must contain exactly one YAML document: ${manifestPath}`,
92
+ );
93
+ let restrictedFeature;
94
+ visit(documents[0], (_key, node) => {
95
+ if (restrictedFeature) return visit.BREAK;
96
+ const yamlNode = /** @type {any} */ (node);
97
+ if (isAlias(node) || yamlNode?.anchor) restrictedFeature = 'aliases and anchors';
98
+ else if (isPair(node) && yamlNode.key?.value === '<<') restrictedFeature = 'merge keys';
99
+ else if (yamlNode?.tag) restrictedFeature = 'custom tags';
100
+ else if (isPair(node) && forbiddenMappingKeys.has(String(yamlNode.key?.value))) {
101
+ restrictedFeature = `mapping key ${String(yamlNode.key.value)}`;
102
+ }
103
+ return undefined;
104
+ });
105
+ assert(
106
+ !restrictedFeature,
107
+ `Project asset additions YAML does not support ${restrictedFeature}: ${manifestPath}`,
108
+ );
109
+ return documents[0].toJS({maxAliasCount: 0});
110
+ }
111
+
112
+ async function readManifestFile(filePath) {
113
+ let stats;
114
+ try {
115
+ stats = await lstat(filePath);
116
+ } catch (error) {
117
+ throw new Error(`Project asset additions manifest is not readable: ${filePath}`, {
118
+ cause: error,
119
+ });
120
+ }
121
+ assert(
122
+ stats.isFile() && !stats.isSymbolicLink(),
123
+ `Project asset additions manifest must be a regular file, not a symbolic link: ${filePath}`,
124
+ );
125
+ assert(
126
+ stats.size <= maximumManifestBytes,
127
+ `Project asset additions manifest exceeds ${maximumManifestBytes} bytes: ${filePath}`,
128
+ );
129
+ const source = await readFile(filePath, 'utf8');
130
+ const extension = path.extname(filePath).toLowerCase();
131
+ assert(
132
+ extension === '.json' || extension === '.yml' || extension === '.yaml',
133
+ `Project asset additions manifest must use .json, .yml, or .yaml: ${filePath}`,
134
+ );
135
+ if (extension === '.json') {
136
+ let value;
137
+ try {
138
+ value = JSON.parse(source);
139
+ } catch (error) {
140
+ throw new Error(`Project asset additions manifest is not valid JSON: ${filePath}`, {
141
+ cause: error,
142
+ });
143
+ }
144
+ parseRestrictedYaml(source, filePath);
145
+ return value;
146
+ }
147
+ return parseRestrictedYaml(source, filePath);
148
+ }
149
+
150
+ function isContained(root, candidate) {
151
+ const relative = path.relative(root, candidate);
152
+ return relative === '' || (!relative.startsWith(`..${path.sep}`) && relative !== '..');
153
+ }
154
+
155
+ async function validateAllowedRoots(manifestDirectory, allowedAssetRoots) {
156
+ assert(Array.isArray(allowedAssetRoots), 'allowedAssetRoots must be an array.');
157
+ const roots = [manifestDirectory, ...allowedAssetRoots].map((root) => {
158
+ assert(typeof root === 'string', 'Every allowed project asset root must be a string.');
159
+ return path.resolve(root);
160
+ });
161
+ const uniqueRoots = [...new Set(roots)];
162
+ return Promise.all(
163
+ uniqueRoots.map(async (root) => {
164
+ const stats = await lstat(root);
165
+ assert(
166
+ stats.isDirectory() && !stats.isSymbolicLink(),
167
+ `Allowed project asset root must be a directory, not a symbolic link: ${root}`,
168
+ );
169
+ return {lexical: root, real: await realpath(root)};
170
+ }),
171
+ );
172
+ }
173
+
174
+ async function assertNoSymlinkPath(root, candidate, description) {
175
+ const relative = path.relative(root, candidate);
176
+ assert(isContained(root, candidate), `${description} escapes its allowed root: ${candidate}`);
177
+ let current = root;
178
+ for (const segment of relative.split(path.sep).filter(Boolean)) {
179
+ current = path.join(current, segment);
180
+ const stats = await lstat(current);
181
+ assert(!stats.isSymbolicLink(), `${description} must not traverse a symbolic link: ${current}`);
182
+ }
183
+ }
184
+
185
+ async function readAssetFile(manifestDirectory, allowedRoots, specification, description) {
186
+ const file = nonEmptyString(specification.file, `${description}.file`);
187
+ assert(!path.isAbsolute(file) && !file.includes('\\'), `${description}.file must be relative.`);
188
+ const resolved = path.resolve(manifestDirectory, file);
189
+ const lexicalRoot = allowedRoots.find(({lexical}) => isContained(lexical, resolved));
190
+ assert(lexicalRoot, `${description}.file is outside the allowed project asset roots: ${file}`);
191
+ await assertNoSymlinkPath(lexicalRoot.lexical, resolved, `${description}.file`);
192
+ const stats = await lstat(resolved);
193
+ assert(stats.isFile(), `${description}.file must be a regular file: ${resolved}`);
194
+ const resolvedRealPath = await realpath(resolved);
195
+ assert(
196
+ allowedRoots.some(({real}) => isContained(real, resolvedRealPath)),
197
+ `${description}.file resolves outside the allowed project asset roots: ${file}`,
198
+ );
199
+ const contents = await readFile(resolved);
200
+ if (specification.size !== undefined) {
201
+ const expectedSize = safeInteger(specification.size, `${description}.size`);
202
+ assert(
203
+ contents.length === expectedSize,
204
+ `${description}.size differs: expected ${expectedSize}, got ${contents.length}`,
205
+ );
206
+ }
207
+ if (specification.sha256 !== undefined) {
208
+ assert(
209
+ typeof specification.sha256 === 'string' && /^[a-f0-9]{64}$/u.test(specification.sha256),
210
+ `${description}.sha256 must be a lowercase SHA-256 hex digest.`,
211
+ );
212
+ const actualSha256 = sha256(contents);
213
+ assert(
214
+ actualSha256 === specification.sha256,
215
+ `${description}.sha256 differs: expected ${specification.sha256}, got ${actualSha256}`,
216
+ );
217
+ }
218
+ const inferredDataFormat = path.extname(file).slice(1).toLowerCase();
219
+ assert(
220
+ /^[a-z0-9]+$/u.test(inferredDataFormat),
221
+ `${description}.file extension is invalid: ${file}`,
222
+ );
223
+ if (specification.dataFormat !== undefined) {
224
+ const expectedDataFormat = nonEmptyString(
225
+ specification.dataFormat,
226
+ `${description}.dataFormat`,
227
+ );
228
+ assert(
229
+ expectedDataFormat === inferredDataFormat,
230
+ `${description}.dataFormat differs: expected ${expectedDataFormat}, got ${inferredDataFormat}`,
231
+ );
232
+ }
233
+ if (specification.license !== undefined) {
234
+ nonEmptyString(specification.license, `${description}.license`);
235
+ }
236
+ return {
237
+ contents,
238
+ dataFormat: inferredDataFormat,
239
+ file,
240
+ name: specification.name,
241
+ };
242
+ }
243
+
244
+ async function inferSoundMetadata(contents, dataFormat, description) {
245
+ const mimeType = soundFormats.get(dataFormat);
246
+ assert(mimeType, `${description}.file uses unsupported sound format: ${dataFormat}`);
247
+ let metadata;
248
+ try {
249
+ metadata = await parseBuffer(
250
+ contents,
251
+ {mimeType, size: contents.length},
252
+ {duration: true, skipCovers: true},
253
+ );
254
+ } catch (error) {
255
+ throw new Error(`${description}.file is not valid ${dataFormat} audio.`, {cause: error});
256
+ }
257
+ const rate = metadata.format.sampleRate;
258
+ const sampleCount =
259
+ metadata.format.numberOfSamples ??
260
+ (typeof metadata.format.duration === 'number' && typeof rate === 'number'
261
+ ? Math.round(metadata.format.duration * rate)
262
+ : undefined);
263
+ safeInteger(rate, `${description} inferred sample rate`, 1);
264
+ safeInteger(sampleCount, `${description} inferred sample count`);
265
+ return {rate, sampleCount};
266
+ }
267
+
268
+ function validateSprite(specification, name) {
269
+ const description = `Project asset sprite ${JSON.stringify(name)}`;
270
+ assert(isRecord(specification), `${description} must be an object.`);
271
+ exactKeys(
272
+ specification,
273
+ new Set([
274
+ 'layerOrder',
275
+ 'visible',
276
+ 'x',
277
+ 'y',
278
+ 'size',
279
+ 'direction',
280
+ 'draggable',
281
+ 'rotationStyle',
282
+ 'volume',
283
+ ]),
284
+ description,
285
+ );
286
+ safeInteger(specification.layerOrder, `${description}.layerOrder`);
287
+ assert(typeof specification.visible === 'boolean', `${description}.visible must be boolean.`);
288
+ finiteNumber(specification.x, `${description}.x`);
289
+ finiteNumber(specification.y, `${description}.y`);
290
+ const size = finiteNumber(specification.size, `${description}.size`);
291
+ assert(size > 0, `${description}.size must be greater than zero.`);
292
+ finiteNumber(specification.direction, `${description}.direction`);
293
+ assert(typeof specification.draggable === 'boolean', `${description}.draggable must be boolean.`);
294
+ assert(
295
+ ['all around', 'left-right', "don't rotate"].includes(specification.rotationStyle),
296
+ `${description}.rotationStyle is invalid: ${specification.rotationStyle}`,
297
+ );
298
+ const volume = finiteNumber(specification.volume, `${description}.volume`);
299
+ assert(volume >= 0 && volume <= 100, `${description}.volume must be between 0 and 100.`);
300
+ }
301
+
302
+ function validateAsset(specification, assetId) {
303
+ const description = `Project asset ${JSON.stringify(assetId)}`;
304
+ assert(isRecord(specification), `${description} must be an object.`);
305
+ assert(
306
+ specification.kind === 'backdrop' ||
307
+ specification.kind === 'costume' ||
308
+ specification.kind === 'sound',
309
+ `${description}.kind must be backdrop, costume, or sound.`,
310
+ );
311
+ exactKeys(
312
+ specification,
313
+ specification.kind === 'sound' ? soundAssetKeys : imageAssetKeys,
314
+ description,
315
+ );
316
+ if (specification.kind === 'backdrop') {
317
+ assert(
318
+ specification.target === undefined,
319
+ `${description}.target is not valid for a backdrop.`,
320
+ );
321
+ } else if (specification.kind === 'costume') {
322
+ nonEmptyString(specification.target, `${description}.target`);
323
+ } else if (specification.target !== undefined) {
324
+ nonEmptyString(specification.target, `${description}.target`);
325
+ }
326
+ if (specification.name !== undefined) nonEmptyString(specification.name, `${description}.name`);
327
+ return description;
328
+ }
329
+
330
+ function addAssetContents(assetContents, archiveEntries, contents, filename, description) {
331
+ const existing = assetContents.get(filename);
332
+ if (existing) {
333
+ assert(
334
+ Buffer.from(existing).equals(contents),
335
+ `${description} collides with different contents: ${filename}`,
336
+ );
337
+ return false;
338
+ }
339
+ assetContents.set(filename, contents);
340
+ archiveEntries.push(filename);
341
+ return true;
342
+ }
343
+
344
+ /**
345
+ * Validate a JSON or YAML project-assets manifest and compose it into one in-memory build.
346
+ * The expanded source and all manifest inputs remain unchanged.
347
+ */
348
+ export async function applyProjectAssetAdditions({
349
+ allowedAssetRoots = [],
350
+ assetContents,
351
+ archiveEntries,
352
+ manifestPath,
353
+ project,
354
+ }) {
355
+ assert(typeof manifestPath === 'string', 'projectAssetsPath must be a string.');
356
+ assert(isRecord(project), 'Project asset additions require a project object.');
357
+ assert(assetContents instanceof Map, 'Project asset additions require an asset contents Map.');
358
+ assert(Array.isArray(archiveEntries), 'Project asset additions require archive entries.');
359
+ const resolvedManifestPath = path.resolve(manifestPath);
360
+ const manifestDirectory = path.dirname(resolvedManifestPath);
361
+ const [manifest, allowedRoots] = await Promise.all([
362
+ readManifestFile(resolvedManifestPath),
363
+ validateAllowedRoots(manifestDirectory, allowedAssetRoots),
364
+ ]);
365
+ assert(isRecord(manifest), 'Project asset additions manifest must be an object.');
366
+ exactKeys(
367
+ manifest,
368
+ new Set(['formatVersion', 'sprites', 'assets']),
369
+ 'Project asset additions manifest',
370
+ );
371
+ assert(
372
+ manifest.formatVersion === projectAssetAdditionsFormatVersion,
373
+ `Unsupported project asset additions formatVersion: ${manifest.formatVersion}`,
374
+ );
375
+ assert(
376
+ manifest.sprites === undefined || isRecord(manifest.sprites),
377
+ 'Project asset additions sprites must be an object when present.',
378
+ );
379
+ assert(
380
+ isRecord(manifest.assets) && Object.keys(manifest.assets).length > 0,
381
+ 'Project asset additions assets must be a non-empty object.',
382
+ );
383
+ assert(Array.isArray(project.targets), 'Project asset additions require project.targets.');
384
+
385
+ const composedProject = structuredClone(project);
386
+ const composedAssetContents = new Map(assetContents);
387
+ const composedArchiveEntries = [...archiveEntries];
388
+ const targetByName = new Map();
389
+ for (const target of composedProject.targets) {
390
+ const targetName = nonEmptyString(target.name, 'Existing project target name');
391
+ assert(!targetByName.has(targetName), `Project has duplicate target name: ${targetName}`);
392
+ assert(
393
+ Array.isArray(target.costumes),
394
+ `Project target ${targetName}.costumes must be an array.`,
395
+ );
396
+ assert(Array.isArray(target.sounds), `Project target ${targetName}.sounds must be an array.`);
397
+ targetByName.set(targetName, target);
398
+ }
399
+ const stages = composedProject.targets.filter(({isStage}) => isStage);
400
+ assert(stages.length === 1, 'Project asset additions require exactly one Stage target.');
401
+ const stage = stages[0];
402
+ const newSpriteNames = [];
403
+
404
+ for (const [rawName, specification] of Object.entries(manifest.sprites ?? {})) {
405
+ const name = nonEmptyString(rawName, 'Project asset sprite name');
406
+ validateSprite(specification, name);
407
+ assert(!targetByName.has(name), `Project asset sprite already exists in the project: ${name}`);
408
+ const target = {
409
+ isStage: false,
410
+ name,
411
+ variables: {},
412
+ lists: {},
413
+ broadcasts: {},
414
+ blocks: {},
415
+ comments: {},
416
+ currentCostume: 0,
417
+ costumes: [],
418
+ sounds: [],
419
+ volume: specification.volume,
420
+ layerOrder: specification.layerOrder,
421
+ visible: specification.visible,
422
+ x: specification.x,
423
+ y: specification.y,
424
+ size: specification.size,
425
+ direction: specification.direction,
426
+ draggable: specification.draggable,
427
+ rotationStyle: specification.rotationStyle,
428
+ };
429
+ composedProject.targets.push(target);
430
+ targetByName.set(name, target);
431
+ newSpriteNames.push(name);
432
+ }
433
+
434
+ let backdropCount = 0;
435
+ let costumeCount = 0;
436
+ let soundCount = 0;
437
+ let assetFileCount = 0;
438
+
439
+ for (const [rawAssetId, specification] of Object.entries(manifest.assets)) {
440
+ const assetId = nonEmptyString(rawAssetId, 'Project asset ID');
441
+ const description = validateAsset(specification, assetId);
442
+ const asset = await readAssetFile(manifestDirectory, allowedRoots, specification, description);
443
+ if (specification.kind !== 'sound') {
444
+ assert(
445
+ imageFormats.has(asset.dataFormat),
446
+ `${description}.file uses unsupported image format: ${asset.dataFormat}`,
447
+ );
448
+ }
449
+ const scratchName = asset.name ?? assetId;
450
+ const owner =
451
+ specification.kind === 'backdrop' || specification.target === undefined
452
+ ? stage
453
+ : targetByName.get(specification.target);
454
+ assert(owner, `${description}.target does not exist in the project: ${specification.target}`);
455
+ assert(
456
+ specification.kind === 'backdrop' || !owner.isStage || specification.kind === 'sound',
457
+ `${description}.target must name a sprite.`,
458
+ );
459
+ assert(
460
+ specification.kind !== 'sound' || specification.target === undefined || !owner.isStage,
461
+ `${description}.target must be omitted for a Stage sound.`,
462
+ );
463
+ const collection = specification.kind === 'sound' ? owner.sounds : owner.costumes;
464
+ assert(
465
+ !collection.some(({name}) => name === scratchName),
466
+ `${description}.name already exists on target ${owner.name}: ${scratchName}`,
467
+ );
468
+ const contentAssetId = md5(asset.contents);
469
+ const filename = `${contentAssetId}.${asset.dataFormat}`;
470
+ if (
471
+ addAssetContents(
472
+ composedAssetContents,
473
+ composedArchiveEntries,
474
+ asset.contents,
475
+ filename,
476
+ description,
477
+ )
478
+ ) {
479
+ assetFileCount += 1;
480
+ }
481
+ if (specification.kind === 'sound') {
482
+ const inferred = await inferSoundMetadata(asset.contents, asset.dataFormat, description);
483
+ if (specification.rate !== undefined) {
484
+ const expectedRate = safeInteger(specification.rate, `${description}.rate`, 1);
485
+ assert(
486
+ inferred.rate === expectedRate,
487
+ `${description}.rate differs: expected ${expectedRate}, got ${inferred.rate}`,
488
+ );
489
+ }
490
+ if (specification.sampleCount !== undefined) {
491
+ const expectedSampleCount = safeInteger(
492
+ specification.sampleCount,
493
+ `${description}.sampleCount`,
494
+ );
495
+ assert(
496
+ inferred.sampleCount === expectedSampleCount,
497
+ `${description}.sampleCount differs: expected ${expectedSampleCount}, got ${inferred.sampleCount}`,
498
+ );
499
+ }
500
+ collection.push({
501
+ name: scratchName,
502
+ assetId: contentAssetId,
503
+ dataFormat: asset.dataFormat,
504
+ format: '',
505
+ md5ext: filename,
506
+ rate: inferred.rate,
507
+ sampleCount: inferred.sampleCount,
508
+ });
509
+ soundCount += 1;
510
+ } else {
511
+ const bitmapResolution =
512
+ specification.bitmapResolution === undefined
513
+ ? 1
514
+ : safeInteger(specification.bitmapResolution, `${description}.bitmapResolution`, 1);
515
+ assert(
516
+ bitmapResolution === 1 || bitmapResolution === 2,
517
+ `${description}.bitmapResolution must be 1 or 2.`,
518
+ );
519
+ collection.push({
520
+ name: scratchName,
521
+ bitmapResolution,
522
+ dataFormat: asset.dataFormat,
523
+ assetId: contentAssetId,
524
+ md5ext: filename,
525
+ rotationCenterX: finiteNumber(
526
+ specification.rotationCenterX,
527
+ `${description}.rotationCenterX`,
528
+ ),
529
+ rotationCenterY: finiteNumber(
530
+ specification.rotationCenterY,
531
+ `${description}.rotationCenterY`,
532
+ ),
533
+ });
534
+ if (specification.kind === 'backdrop') backdropCount += 1;
535
+ else costumeCount += 1;
536
+ }
537
+ }
538
+
539
+ for (const name of newSpriteNames) {
540
+ assert(
541
+ targetByName.get(name).costumes.length > 0,
542
+ `Project asset sprite must receive at least one costume: ${name}`,
543
+ );
544
+ }
545
+
546
+ return {
547
+ archiveEntries: composedArchiveEntries,
548
+ assetContents: composedAssetContents,
549
+ assetReferenceCount: backdropCount + costumeCount + soundCount,
550
+ manifestPath: resolvedManifestPath,
551
+ project: composedProject,
552
+ summary: Object.freeze({
553
+ assetFileCount,
554
+ backdropCount,
555
+ costumeCount,
556
+ soundCount,
557
+ spriteCount: newSpriteNames.length,
558
+ }),
559
+ };
560
+ }
package/src/source.js CHANGED
@@ -13,6 +13,7 @@ import {
13
13
  validateExtensionSourceMetadata,
14
14
  validateManagedExtensionContents,
15
15
  } from './extension-dependencies.js';
16
+ import {applyProjectAssetAdditions} from './project-asset-additions.js';
16
17
  import {cleanUpTurboWarpBlocks} from './turbowarp-clean-up.js';
17
18
 
18
19
  export const sourceFormatVersion = 1;
@@ -387,14 +388,39 @@ export async function validateSb3Source(sourceDirectory) {
387
388
  return source;
388
389
  }
389
390
 
390
- export async function createDeterministicSb3(sourceDirectory, {cleanUpBlocks = false} = {}) {
391
+ /**
392
+ * @param {string} sourceDirectory
393
+ * @param {{allowedAssetRoots?: string[], cleanUpBlocks?: boolean, projectAssetsPath?: string}} [options]
394
+ */
395
+ export async function createDeterministicSb3(sourceDirectory, options = {}) {
396
+ const {allowedAssetRoots = [], cleanUpBlocks = false, projectAssetsPath} = options;
391
397
  assert(typeof cleanUpBlocks === 'boolean', 'cleanUpBlocks must be a boolean.');
398
+ assert(Array.isArray(allowedAssetRoots), 'allowedAssetRoots must be an array.');
399
+ assert(
400
+ projectAssetsPath === undefined || typeof projectAssetsPath === 'string',
401
+ 'projectAssetsPath must be a string when provided.',
402
+ );
392
403
  const source = await validateSb3Source(sourceDirectory);
404
+ const projectAssets = projectAssetsPath
405
+ ? await applyProjectAssetAdditions({
406
+ allowedAssetRoots,
407
+ assetContents: source.assetContents,
408
+ archiveEntries: source.sourceManifest.archiveEntries,
409
+ manifestPath: projectAssetsPath,
410
+ project: source.project,
411
+ })
412
+ : {
413
+ archiveEntries: source.sourceManifest.archiveEntries,
414
+ assetContents: source.assetContents,
415
+ assetReferenceCount: 0,
416
+ project: source.project,
417
+ summary: null,
418
+ };
393
419
  const bundled = buildExtensionBundles({
394
420
  extensionBundles: source.extensionBundles,
395
421
  extensionContents: source.extensionContents,
396
422
  extensions: source.extensions,
397
- project: source.project,
423
+ project: projectAssets.project,
398
424
  });
399
425
  let project = structuredClone(bundled.project);
400
426
  let blockCleanUp = null;
@@ -417,11 +443,11 @@ export async function createDeterministicSb3(sourceDirectory, {cleanUpBlocks = f
417
443
 
418
444
  /** @type {Record<string, Uint8Array>} */
419
445
  const archiveEntries = {};
420
- for (const entryName of source.sourceManifest.archiveEntries) {
446
+ for (const entryName of projectAssets.archiveEntries) {
421
447
  archiveEntries[entryName] =
422
448
  entryName === 'project.json'
423
449
  ? strToU8(`${JSON.stringify(project)}\n`)
424
- : source.assetContents.get(entryName);
450
+ : projectAssets.assetContents.get(entryName);
425
451
  }
426
452
  const archive = zipSync(archiveEntries, {
427
453
  level: 6,
@@ -430,12 +456,13 @@ export async function createDeterministicSb3(sourceDirectory, {cleanUpBlocks = f
430
456
 
431
457
  return {
432
458
  archive,
433
- assetCount: source.assetContents.size,
434
- assetReferenceCount: source.assetReferenceCount,
459
+ assetCount: projectAssets.assetContents.size,
460
+ assetReferenceCount: source.assetReferenceCount + projectAssets.assetReferenceCount,
435
461
  blockCleanUp,
436
462
  bundlePlans: bundled.bundlePlans,
437
463
  embeddedExtensionCount: bundled.extensions.length,
438
- entryCount: source.sourceManifest.archiveEntries.length,
464
+ entryCount: projectAssets.archiveEntries.length,
465
+ projectAssetAdditions: projectAssets.summary,
439
466
  source,
440
467
  };
441
468
  }