@kubohiroya/turbowarp-plus-editor-project-folder 0.2.0 → 0.3.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
@@ -18,13 +18,13 @@ TurboWarp Plus Editor で既存の sb3-toolchain v1 の作品フォルダを開
18
18
 
19
19
  | Editor の状態 | 動作 |
20
20
  | --- | --- |
21
- | 未保存編集なし・実行停止中 | 既存ブロックの値と座標の変更は、2 回の確認でファイルが変わらなければその場で反映します。 |
21
+ | 未保存編集なし・実行停止中 | 2 回の確認でファイルが変わらなければ、既存のスプライトとステージのスクリプトの変更をその場で反映します。値と座標の変更はすべてのブロックを保ちます。ブロックの追加・削除・接続の変更は、ホストが `blockReload.deserializeBlocks` を渡す場合に、該当するスクリプトだけを置き換えます。 |
22
22
  | 作品の実行中 | 反映を保留します。値と座標の変更は停止後に反映します。 |
23
23
  | 未保存編集あり | 編集を保持します。**編集を破棄して再読み込み…** は確認してからフォルダの内容に置き換えます。 |
24
- | 作品 JSON のその他の変更、アセット・マニフェスト・拡張機能の変更 | **作品全体を再読み込み** で、開くときと同じ検証を経てフォルダを読み直します。自動では行いません。 |
24
+ | その他の変更(ターゲット・変数・コメントの変更、作品に無い変数や拡張機能を使うブロック、アセット・マニフェスト・拡張機能の変更) | **作品全体を再読み込み** で、開くときと同じ検証を経てフォルダを読み直します。自動では行いません。 |
25
25
  | JSON の途中など書き込み途中 | 更新待ちを表示し、間を置かずに再確認します。 |
26
26
 
27
- `mountProjectFolder` に `autoReload: false` を渡すと、すべての反映をボタン操作にします。確認はファイルの内容を読む前にサイズと更新時刻を比べるため、両方が変わらない上書きは検出できません。保存時はディスクのバイト列を照合し、変更されたフォルダへの上書きを拒否します。
27
+ スクリプトの置き換えは VM を変更する前に検証し、途中で VM が失敗した場合はすべてのターゲットを元に戻して **作品全体を再読み込み** を待ちます。`mountProjectFolder` に `autoReload: false` を渡すと、すべての反映をボタン操作にします。確認はファイルの内容を読む前にサイズと更新時刻を比べるため、両方が変わらない上書きは検出できません。保存時はディスクのバイト列を照合し、変更されたフォルダへの上書きを拒否します。
28
28
 
29
29
  ## 開発
30
30
 
@@ -33,3 +33,11 @@ Node.js 26 で `npm ci` と `npm test` を実行します。Vite で JavaScript
33
33
  Editor のヘッドレス統合テストは実ディスク上のフォルダを使い、選択画面の操作を差し替えます。OS のフォルダ選択画面を確認するときは、使い捨ての sb3-toolchain v1 作品を **ファイル → プロジェクトフォルダを開く…** から選び、読み書きを許可します。標準ブロックを変更し、**ファイル → プロジェクトフォルダに保存** を選びます。選んだフォルダの `project.source.json` が更新されたことを確かめ、同じフォルダを開き直して編集が反映されることを確認します。
34
34
 
35
35
  初期実装は MPL-2.0 の [TurboWarp Plus Editor d14d065](https://github.com/kubohiroya/turbowarp-plus-editor/tree/d14d0659f77f37328c855ecfeeae0927d81ae81a/packages/editor-project-folder) から分離しました。
36
+
37
+ ## 公開
38
+
39
+ npm への公開は `.github/workflows/release.yml` が行う。`package.json` の版と同じ `v<版>` のタグを
40
+ `main` のコミットに push すると、テストを通したうえで npm に入れるアーカイブを作り、GitHub Release に
41
+ 添付してから npm に公開し、`latest` と `next` をその版に向ける。認証はトークンではなく npm の
42
+ Trusted Publisher(OIDC)で、provenance を付けて公開する。npm 側の設定にはこのワークフローの
43
+ ファイル名をそのまま登録するため、改名するときは npm の設定も合わせる。
package/README.md CHANGED
@@ -18,13 +18,13 @@ When the host passes `host.blockReload`, the package checks the open folder ever
18
18
 
19
19
  | Editor state | Behavior |
20
20
  | --- | --- |
21
- | No unsaved edits, project stopped | Changes to values and positions of existing blocks are applied in place once the file has stayed the same across two checks. |
21
+ | No unsaved edits, project stopped | Once the file has stayed the same across two checks, changes to the scripts of existing sprites and the stage are applied in place. Value and position changes keep every block. Added, removed or reconnected blocks replace only the scripts they belong to, when the host passes `blockReload.deserializeBlocks`. |
22
22
  | Project running | The change is held. Value and position changes apply when the project stops. |
23
23
  | Unsaved edits | The edits are kept. **Discard Edits and Reload…** asks before replacing them with the folder contents. |
24
- | Other changes to the project JSON, assets, the manifest or extensions | **Reload Whole Project** reads the folder again with the same checks as opening it. This is never automatic. |
24
+ | Other changes: targets, variables, comments, blocks that need a variable or an extension the project lacks, assets, the manifest or extensions | **Reload Whole Project** reads the folder again with the same checks as opening it. This is never automatic. |
25
25
  | Incomplete write, such as truncated JSON | The notice waits and the folder is checked again shortly. |
26
26
 
27
- Pass `autoReload: false` to `mountProjectFolder` to keep every reload behind the button. Checks compare file size and modification time before reading contents, so an overwrite that keeps both unchanged is not detected. Saving still compares the bytes on disk and refuses to overwrite a folder that changed.
27
+ Script replacements are checked against the VM before any change, and every target is restored if the VM fails part way; the change then waits for **Reload Whole Project**. Pass `autoReload: false` to `mountProjectFolder` to keep every reload behind the button. Checks compare file size and modification time before reading contents, so an overwrite that keeps both unchanged is not detected. Saving still compares the bytes on disk and refuses to overwrite a folder that changed.
28
28
 
29
29
  ## Development
30
30
 
@@ -33,3 +33,11 @@ Use Node.js 26, then run `npm ci` and `npm test`. Vite builds the JavaScript lib
33
33
  The Editor's headless integration test uses an actual disk directory and substitutes the picker interaction. To verify the native picker separately, open a disposable sb3-toolchain v1 project with **File → Open Project Folder…**, accept read/write access, edit a standard block, and select **File → Save to Project Folder**. Check that `project.source.json` changed in the chosen directory and reopen the same folder to confirm the edit.
34
34
 
35
35
  The initial source was extracted from [TurboWarp Plus Editor at d14d065](https://github.com/kubohiroya/turbowarp-plus-editor/tree/d14d0659f77f37328c855ecfeeae0927d81ae81a/packages/editor-project-folder) under MPL-2.0.
36
+
37
+ ## Release
38
+
39
+ `.github/workflows/release.yml` publishes to npm. Push a `v<version>` tag that names the
40
+ `package.json` version on a `main` commit: the workflow runs the tests, packs the archive, attaches it
41
+ to the GitHub Release, publishes it to npm and points `latest` and `next` at it. It authenticates with
42
+ npm Trusted Publishing (OIDC), not a token, and publishes with provenance. The npm settings name this
43
+ workflow file, so rename both together.
@@ -0,0 +1,3 @@
1
+ # Licenses
2
+
3
+ The app does not bundle any dependencies with licenses.
package/dist/index.d.ts CHANGED
@@ -1,6 +1,7 @@
1
1
  import type { FolderHost, FolderVM } from './session.js';
2
2
  export type { FolderHost, FolderVM, OpenResult } from './session.js';
3
3
  export type { ReloadTarget } from './block-reload.js';
4
+ export type { DeserializeBlocks } from './script-reload.js';
4
5
  type MenuElement = (component: any, props: any, ...children: any[]) => any;
5
6
  interface MenuProps {
6
7
  vm: FolderVM;
package/dist/index.js CHANGED
@@ -212,7 +212,7 @@ async function A(e, t) {
212
212
  };
213
213
  }
214
214
  var j = (e, t) => e.length === t.length && e.every((e, n) => e === t[n]);
215
- async function M(e, t) {
215
+ async function ee(e, t) {
216
216
  let { directory: n, versions: r } = e;
217
217
  try {
218
218
  let [i, a, o] = await Promise.all([
@@ -234,7 +234,7 @@ async function M(e, t) {
234
234
  return e instanceof _ ? "structure" : "waiting";
235
235
  }
236
236
  }
237
- async function N(e) {
237
+ async function M(e) {
238
238
  try {
239
239
  let t = await e.directory.getDirectoryHandle("assets"), n = await e.directory.getDirectoryHandle("extensions");
240
240
  if (!O(await D(t), e.bytes.keys()) || (await D(n)).size) throw new _("conflict");
@@ -244,32 +244,32 @@ async function N(e) {
244
244
  throw e instanceof _ || e instanceof DOMException && ["NotFoundError", "TypeMismatchError"].includes(e.name) ? new _("conflict") : e;
245
245
  }
246
246
  }
247
- var P = (e, t) => {
247
+ var N = (e, t) => {
248
248
  if (e === t) return !0;
249
- if (Array.isArray(e) && Array.isArray(t)) return e.length === t.length && e.every((e, n) => P(e, t[n]));
249
+ if (Array.isArray(e) && Array.isArray(t)) return e.length === t.length && e.every((e, n) => N(e, t[n]));
250
250
  if (!y(e) || !y(t)) return !1;
251
251
  let n = Object.keys(e);
252
- return n.length === Object.keys(t).length && n.every((n) => Object.hasOwn(t, n) && P(e[n], t[n]));
253
- }, F = (e, t, n) => {
254
- if (P(t, n)) return e === void 0 ? n : e;
252
+ return n.length === Object.keys(t).length && n.every((n) => Object.hasOwn(t, n) && N(e[n], t[n]));
253
+ }, P = (e, t, n) => {
254
+ if (N(t, n)) return e === void 0 ? n : e;
255
255
  if (!y(t) || !y(n)) return n;
256
256
  let r = Object.assign(Object.create(null), y(e) ? e : {});
257
- for (let e of Object.keys(t)) Object.hasOwn(n, e) ? P(t[e], n[e]) || (r[e] = F(Object.hasOwn(r, e) ? r[e] : void 0, t[e], n[e])) : delete r[e];
257
+ for (let e of Object.keys(t)) Object.hasOwn(n, e) ? N(t[e], n[e]) || (r[e] = P(Object.hasOwn(r, e) ? r[e] : void 0, t[e], n[e])) : delete r[e];
258
258
  for (let e of Object.keys(n)) Object.hasOwn(t, e) || (r[e] = n[e]);
259
259
  return r;
260
260
  };
261
- function I(e, t, n) {
261
+ function te(e, t, n) {
262
262
  let { targets: i } = t, a = r(t, u), { targets: o } = n;
263
- if (!P(a, r(n, d)) || !P(i.map(x), o.map(x))) return v("This prototype saves block edits on existing targets only");
263
+ if (!N(a, r(n, d)) || !N(i.map(x), o.map(x))) return v("This prototype saves block edits on existing targets only");
264
264
  let s = /* @__PURE__ */ new Map(), c = new Map(e.targets.map((e) => [x(e), e]));
265
265
  for (let [e, t] of o.entries()) {
266
266
  let { blocks: n, comments: a } = t, o = r(t, f), l = i[e], { blocks: u, comments: d } = l;
267
- if (!P(o, r(l, p))) return v("This prototype saves block edits on existing targets only");
267
+ if (!N(o, r(l, p))) return v("This prototype saves block edits on existing targets only");
268
268
  let m = x(t), h = c.get(m);
269
269
  if (!h) return v("The original target could not be identified");
270
- if (!P(u, n) || !P(d, a)) {
270
+ if (!N(u, n) || !N(d, a)) {
271
271
  let e = {};
272
- P(u, n) || (e.blocks = F(h.blocks, u, n)), P(d, a) || (e.comments = F(h.comments, d, a)), s.set(m, e);
272
+ N(u, n) || (e.blocks = P(h.blocks, u, n)), N(d, a) || (e.comments = P(h.comments, d, a)), s.set(m, e);
273
273
  }
274
274
  }
275
275
  return s.size ? l(l({}, e), {}, { targets: e.targets.map((e) => {
@@ -278,17 +278,17 @@ function I(e, t, n) {
278
278
  }) }) : null;
279
279
  }
280
280
  // src/block-reload.ts
281
- var L = ["targets"], R = ["targets"], z = ["blocks"], B = ["blocks"], V = [
281
+ var ne = ["targets"], re = ["targets"], F = ["blocks"], ie = ["blocks"], ae = [
282
282
  "inputs",
283
283
  "fields",
284
284
  "x",
285
285
  "y"
286
- ], H = [
286
+ ], oe = [
287
287
  "inputs",
288
288
  "fields",
289
289
  "x",
290
290
  "y"
291
- ], U = (e) => typeof e == "string" || typeof e == "boolean" || typeof e == "number" && Number.isFinite(e), W = {
291
+ ], I = (e) => typeof e == "string" || typeof e == "boolean" || typeof e == "number" && Number.isFinite(e), L = {
292
292
  4: ["math_number", "NUM"],
293
293
  5: ["math_positive_number", "NUM"],
294
294
  6: ["math_whole_number", "NUM"],
@@ -296,28 +296,28 @@ var L = ["targets"], R = ["targets"], z = ["blocks"], B = ["blocks"], V = [
296
296
  8: ["math_angle", "NUM"],
297
297
  9: ["colour_picker", "COLOUR"],
298
298
  10: ["text", "TEXT"]
299
- }, G = () => v("Only values and coordinates of existing blocks can be reloaded"), K = (e, t) => P(Object.keys(e), Object.keys(t)), q = (e, t) => typeof e != "number" || typeof t != "number" || !Number.isSafeInteger(e) || !Number.isSafeInteger(t) ? G() : {
299
+ }, R = () => v("Only values and coordinates of existing blocks can be reloaded"), z = (e, t) => N(Object.keys(e), Object.keys(t)), B = (e, t) => typeof e != "number" || typeof t != "number" || !Number.isSafeInteger(e) || !Number.isSafeInteger(t) ? R() : {
300
300
  x: e,
301
301
  y: t
302
302
  };
303
- function J(e, t) {
304
- let { targets: n } = e, i = r(e, L), { targets: a } = t, o = r(t, R);
305
- if (n.length !== a.length || !P(i, o)) return G();
303
+ function V(e, t) {
304
+ let { targets: n } = e, i = r(e, ne), { targets: a } = t, o = r(t, re);
305
+ if (n.length !== a.length || !N(i, o)) return R();
306
306
  let s = [];
307
307
  for (let [e, t] of n.entries()) {
308
- let { blocks: n } = t, i = r(t, z), o = a[e], { blocks: c } = o;
309
- if (!P(i, r(o, B))) return G();
308
+ let { blocks: n } = t, i = r(t, F), o = a[e], { blocks: c } = o;
309
+ if (!N(i, r(o, ie))) return R();
310
310
  if (!y(n) || !y(c)) {
311
- if (P(n, c)) continue;
312
- return G();
311
+ if (N(n, c)) continue;
312
+ return R();
313
313
  }
314
- if (!K(n, c)) return G();
314
+ if (!z(n, c)) return R();
315
315
  for (let [e, i] of Object.entries(n)) {
316
316
  let n = c[e];
317
- if (P(i, n)) continue;
318
- if (!y(i) || !y(n)) return G();
319
- let { inputs: a, fields: o, x: u, y: d } = i, f = r(i, V), { inputs: p, fields: m, x: h, y: g } = n;
320
- if (!P(f, r(n, H)) || typeof f.opcode != "string") return G();
317
+ if (N(i, n)) continue;
318
+ if (!y(i) || !y(n)) return R();
319
+ let { inputs: a, fields: o, x: u, y: d } = i, f = r(i, ae), { inputs: p, fields: m, x: h, y: g } = n;
320
+ if (!N(f, r(n, oe)) || typeof f.opcode != "string") return R();
321
321
  let _ = {
322
322
  id: e,
323
323
  target: t.name,
@@ -325,23 +325,23 @@ function J(e, t) {
325
325
  opcode: f.opcode
326
326
  };
327
327
  if (u !== h || d !== g) {
328
- if (f.topLevel !== !0) return G();
328
+ if (f.topLevel !== !0) return R();
329
329
  s.push(l(l({}, _), {}, {
330
330
  kind: "position",
331
- before: q(u, d),
332
- after: q(h, g)
331
+ before: B(u, d),
332
+ after: B(h, g)
333
333
  }));
334
334
  }
335
- if (!P(o, m)) {
336
- if (!y(o) || !y(m) || !K(o, m)) return G();
335
+ if (!N(o, m)) {
336
+ if (!y(o) || !y(m) || !z(o, m)) return R();
337
337
  for (let [e, t] of Object.entries(o)) {
338
338
  let n = m[e];
339
- if (!P(t, n)) {
339
+ if (!N(t, n)) {
340
340
  if ([
341
341
  "VARIABLE",
342
342
  "LIST",
343
343
  "BROADCAST_OPTION"
344
- ].includes(e) || f.opcode === "sensing_of_object_menu" || !Array.isArray(t) || !Array.isArray(n) || t.length !== 1 || n.length !== 1 || !U(t[0]) || !U(n[0])) return G();
344
+ ].includes(e) || f.opcode === "sensing_of_object_menu" || !Array.isArray(t) || !Array.isArray(n) || t.length !== 1 || n.length !== 1 || !I(t[0]) || !I(n[0])) return R();
345
345
  s.push(l(l({}, _), {}, {
346
346
  kind: "field",
347
347
  name: e,
@@ -351,16 +351,16 @@ function J(e, t) {
351
351
  }
352
352
  }
353
353
  }
354
- if (!P(a, p)) {
355
- if (!y(a) || !y(p) || !K(a, p)) return G();
354
+ if (!N(a, p)) {
355
+ if (!y(a) || !y(p) || !z(a, p)) return R();
356
356
  for (let [e, t] of Object.entries(a)) {
357
357
  let n = p[e];
358
- if (P(t, n)) continue;
359
- if (!Array.isArray(t) || !Array.isArray(n) || t[0] !== n[0]) return G();
358
+ if (N(t, n)) continue;
359
+ if (!Array.isArray(t) || !Array.isArray(n) || t[0] !== n[0]) return R();
360
360
  let r = t[0] === 1 ? 1 : t[0] === 3 && typeof t[1] == "string" && t[1] === n[1] ? 2 : null;
361
- if (r === null || t.length !== r + 1 || n.length !== r + 1) return G();
361
+ if (r === null || t.length !== r + 1 || n.length !== r + 1) return R();
362
362
  let i = t[r], a = n[r];
363
- if (!Array.isArray(i) || !Array.isArray(a) || i.length !== 2 || a.length !== 2 || typeof i[0] != "number" || !Object.hasOwn(W, i[0]) || i[0] !== a[0] || !U(i[1]) || !U(a[1])) return G();
363
+ if (!Array.isArray(i) || !Array.isArray(a) || i.length !== 2 || a.length !== 2 || typeof i[0] != "number" || !Object.hasOwn(L, i[0]) || i[0] !== a[0] || !I(i[1]) || !I(a[1])) return R();
364
364
  let o = r === 2 ? t[1] : null;
365
365
  s.push(l(l({}, _), {}, {
366
366
  kind: "input",
@@ -376,15 +376,15 @@ function J(e, t) {
376
376
  }
377
377
  return s;
378
378
  }
379
- function Y(e, t) {
379
+ function H(e, t) {
380
380
  let n = /* @__PURE__ */ new Set(), r = t.map((t) => {
381
381
  let r = e.filter((e) => e.isStage === t.stage && (t.stage || e.isOriginal && e.getName() === t.target));
382
- if (r.length !== 1) return G();
382
+ if (r.length !== 1) return R();
383
383
  let i = r[0], a = i.blocks, o = a.getBlock(t.id);
384
- if (!o || o.opcode !== t.opcode) return G();
384
+ if (!o || o.opcode !== t.opcode) return R();
385
385
  if (n.add(i), t.kind === "position") {
386
386
  var s, c;
387
- return !o.topLevel || Math.round((s = o.x) == null ? 0 : s) !== t.before.x || Math.round((c = o.y) == null ? 0 : c) !== t.before.y ? G() : (e) => a.moveBlock({
387
+ return !o.topLevel || Math.round((s = o.x) == null ? 0 : s) !== t.before.x || Math.round((c = o.y) == null ? 0 : c) !== t.before.y ? R() : (e) => a.moveBlock({
388
388
  id: t.id,
389
389
  newCoordinate: t[e]
390
390
  });
@@ -393,13 +393,13 @@ function Y(e, t) {
393
393
  if (t.kind === "input") {
394
394
  var d;
395
395
  let e = o.inputs[t.name], n = e == null ? void 0 : e.shadow;
396
- if (!n || e.block !== ((d = t.connected) == null ? n : d)) return G();
397
- let r = a.getBlock(n), [i, s] = W[t.tag];
398
- if (!(r != null && r.shadow) || r.parent !== o.id || r.opcode !== i) return G();
396
+ if (!n || e.block !== ((d = t.connected) == null ? n : d)) return R();
397
+ let r = a.getBlock(n), [i, s] = L[t.tag];
398
+ if (!(r != null && r.shadow) || r.parent !== o.id || r.opcode !== i) return R();
399
399
  l = r, u = s;
400
400
  }
401
401
  let f = l.fields[u];
402
- return !f || f.id != null || f.value !== t.before || l.isMonitored || o.isMonitored ? G() : (e) => a.changeBlock({
402
+ return !f || f.id != null || f.value !== t.before || l.isMonitored || o.isMonitored ? R() : (e) => a.changeBlock({
403
403
  id: l.id,
404
404
  element: "field",
405
405
  name: u,
@@ -414,8 +414,131 @@ function Y(e, t) {
414
414
  }
415
415
  return [...n];
416
416
  }
417
+ // src/script-reload.ts
418
+ var U = ["targets"], W = ["targets"], G = ["blocks"], K = ["blocks"], q = (e = "Only changes to the scripts of existing targets can be reloaded in place") => v(e), se = /* @__PURE__ */ new Set([
419
+ "motion",
420
+ "looks",
421
+ "sound",
422
+ "event",
423
+ "control",
424
+ "sensing",
425
+ "operator",
426
+ "data",
427
+ "procedures",
428
+ "argument",
429
+ "math",
430
+ "text",
431
+ "colour"
432
+ ]), J = (e) => e.split("_", 1)[0], ce = /* @__PURE__ */ new Set([
433
+ "VARIABLE",
434
+ "LIST",
435
+ "BROADCAST_OPTION"
436
+ ]), le = (e) => y(e) && typeof e.parent == "string" ? e.parent : null;
437
+ function Y(e) {
438
+ let t = /* @__PURE__ */ new Map();
439
+ for (let n of Object.keys(e)) {
440
+ let r = n, i = /* @__PURE__ */ new Set();
441
+ for (;;) {
442
+ if (i.has(r)) return q("Blocks form a cycle");
443
+ i.add(r);
444
+ let t = le(e[r]);
445
+ if (t === null) break;
446
+ if (!Object.hasOwn(e, t)) return q("A block refers to a missing parent");
447
+ r = t;
448
+ }
449
+ t.set(n, r);
450
+ }
451
+ return t;
452
+ }
453
+ function ue(e, t) {
454
+ for (let n of Object.values(e)) y(n) && typeof n.opcode == "string" && t.add(J(n.opcode));
455
+ }
456
+ function de(e, t) {
457
+ let { targets: n } = e, i = r(e, U), { targets: a } = t, o = r(t, W);
458
+ if (n.length !== a.length || !N(i, o)) return q();
459
+ let s = new Set(se);
460
+ for (let e of n) y(e.blocks) && ue(e.blocks, s);
461
+ let c = [];
462
+ for (let [e, t] of n.entries()) {
463
+ let { blocks: n } = t, i = r(t, G), o = a[e], { blocks: l } = o;
464
+ if (!N(i, r(o, K))) return q();
465
+ if (N(n, l)) continue;
466
+ let u = y(n) ? n : {}, d = y(l) ? l : {}, f = Y(u), p = Y(d), m = /* @__PURE__ */ new Set(), h = /* @__PURE__ */ new Set(), g = (e) => {
467
+ let t = f.get(e), n = p.get(e), r = !1;
468
+ return t !== void 0 && !m.has(t) && (m.add(t), r = !0), n !== void 0 && !h.has(n) && (h.add(n), r = !0), r;
469
+ };
470
+ for (let e of /* @__PURE__ */ new Set([...Object.keys(u), ...Object.keys(d)])) N(u[e], d[e]) || g(e);
471
+ for (let e = !0; e;) {
472
+ e = !1;
473
+ for (let [t, n] of f) m.has(n) && g(t) && (e = !0);
474
+ for (let [t, n] of p) h.has(n) && g(t) && (e = !0);
475
+ }
476
+ let _ = {};
477
+ for (let [e, t] of p) h.has(t) && (_[e] = d[e]);
478
+ for (let e of Object.values(_)) if (y(e)) {
479
+ if (typeof e.opcode != "string") return q("A block has no opcode");
480
+ if (!s.has(J(e.opcode))) return q(`Blocks need an extension the project does not use: ${e.opcode}`);
481
+ }
482
+ c.push({
483
+ target: t.name,
484
+ stage: t.isStage,
485
+ remove: [...m],
486
+ blocks: _
487
+ });
488
+ }
489
+ return c;
490
+ }
491
+ var fe = (e, t) => {
492
+ let n = e.filter((e) => e.isStage === t.stage && (t.stage || e.isOriginal && e.getName() === t.target));
493
+ return n.length === 1 ? n[0] : q();
494
+ };
495
+ function pe(e, t, n) {
496
+ let r = t.map((t) => {
497
+ let r = fe(e, t), i = r.blocks;
498
+ for (let e of t.remove) {
499
+ let t = i.getBlock(e);
500
+ if (!t || !t.topLevel || !i._scripts.includes(e)) return q("The editor and the folder differ");
501
+ }
502
+ let a = Object.values(n(JSON.parse(JSON.stringify(t.blocks))));
503
+ for (let e of a) {
504
+ var o;
505
+ if (typeof e.id != "string" || typeof e.opcode != "string") return q("A block could not be read");
506
+ if (e.comment && !(r.comments && Object.hasOwn(r.comments, e.comment))) return q("A block refers to a missing comment");
507
+ for (let [t, n] of Object.entries((o = e.fields) == null ? {} : o)) {
508
+ var s;
509
+ if ((ce.has(t) || n.variableType) && (typeof n.id != "string" || !((s = r.lookupVariableById) != null && s.call(r, n.id)))) return q("A block refers to a variable, list or message the project does not have");
510
+ }
511
+ }
512
+ return {
513
+ target: r,
514
+ container: i,
515
+ edit: t,
516
+ created: a
517
+ };
518
+ }), i = r.map(({ container: e }) => ({
519
+ container: e,
520
+ blocks: l({}, e._blocks),
521
+ scripts: [...e._scripts],
522
+ tops: new Map(Object.entries(e._blocks).map(([e, t]) => [e, t.topLevel]))
523
+ }));
524
+ try {
525
+ for (let { container: e, edit: t, created: n } of r) {
526
+ for (let n of t.remove) e.deleteBlock(n);
527
+ for (let t of n) e.createBlock(t, !0), e._blocks[t.id] !== t && q("A block id is already in use");
528
+ e.resetCache();
529
+ }
530
+ } catch (e) {
531
+ for (let { container: e, blocks: t, scripts: n, tops: r } of i) {
532
+ e._blocks = t, e._scripts = n;
533
+ for (let [e, n] of r) t[e].topLevel = n;
534
+ e.resetCache();
535
+ }
536
+ throw e;
537
+ }
538
+ return r.map(({ target: e }) => e);
539
+ }
417
540
  // src/session.ts
418
- var X = /* @__PURE__ */ new WeakMap(), Z = (e) => {
541
+ var X = /* @__PURE__ */ new WeakMap(), me = (e) => {
419
542
  let t = X.get(e);
420
543
  if (t) return t;
421
544
  let n = { assets: null };
@@ -425,7 +548,7 @@ var X = /* @__PURE__ */ new WeakMap(), Z = (e) => {
425
548
  return a ? Promise.resolve(a) : null;
426
549
  } }, 101), X.set(e, n), n;
427
550
  };
428
- function ee(e, t) {
551
+ function he(e, t) {
429
552
  let n = null, r = !1, i = !1, a = 0, o = null, s = () => S(e.toJSON(void 0, { allowOptimization: !1 })), c = () => {
430
553
  a++;
431
554
  }, u = () => {
@@ -447,7 +570,7 @@ function ee(e, t) {
447
570
  let u = e.runtime.storage, d = await A(r, u);
448
571
  if (i || e.runtime.getTargetForStage() !== c || t.isProjectDirty() && !o()) return "cancelled";
449
572
  t.beforeLoad(), n = null;
450
- let f = Z(u), p = d.storageAssets;
573
+ let f = me(u), p = d.storageAssets;
451
574
  f.assets = p;
452
575
  let m;
453
576
  try {
@@ -464,33 +587,42 @@ function ee(e, t) {
464
587
  } finally {
465
588
  r = !1;
466
589
  }
467
- }, h = async (e) => {
468
- var t;
469
- let n = typeof e.pending == "object" ? e.pending : null, r = await M(e.source, (t = n == null ? void 0 : n.update) == null ? null : t);
470
- if (!r || typeof r == "string") return r;
471
- if ((n == null ? void 0 : n.update) === r) return l(l({}, n), {}, { stable: !0 });
590
+ }, h = (e, n) => {
591
+ var r;
472
592
  try {
473
593
  return {
474
- update: r,
475
- edits: J(e.source.project, r.project),
476
- stable: !1
594
+ kind: "values",
595
+ changes: V(e, n)
477
596
  };
478
597
  } catch (e) {
479
598
  if (!(e instanceof _)) throw e;
599
+ }
600
+ if (!((r = t.blockReload) != null && r.deserializeBlocks)) return null;
601
+ try {
480
602
  return {
481
- update: r,
482
- edits: null,
483
- stable: !1
603
+ kind: "scripts",
604
+ changes: de(e, n)
484
605
  };
606
+ } catch (e) {
607
+ if (!(e instanceof _)) throw e;
608
+ return null;
485
609
  }
486
- }, g = () => {
610
+ }, g = async (e) => {
611
+ var t;
612
+ let n = typeof e.pending == "object" ? e.pending : null, r = await ee(e.source, (t = n == null ? void 0 : n.update) == null ? null : t);
613
+ return !r || typeof r == "string" ? r : (n == null ? void 0 : n.update) === r ? l(l({}, n), {}, { stable: !0 }) : {
614
+ update: r,
615
+ edits: h(e.source.project, r.project),
616
+ stable: !1
617
+ };
618
+ }, v = () => {
487
619
  let e = n == null ? void 0 : n.pending;
488
620
  return !e || e === "waiting" ? null : e === "structure" || e.edits === null ? "full" : "partial";
489
- }, v = () => {
621
+ }, y = () => {
490
622
  var e;
491
623
  let i = n == null ? void 0 : n.pending;
492
- return i ? r ? "busy" : i === "waiting" ? "waiting" : t.isProjectDirty() ? "dirty" : (e = t.blockReload) != null && e.isRunning() ? "running" : g() === "full" ? "full" : "ready" : null;
493
- }, y = () => {
624
+ return i ? r ? "busy" : i === "waiting" ? "waiting" : t.isProjectDirty() ? "dirty" : (e = t.blockReload) != null && e.isRunning() ? "running" : v() === "full" ? "full" : "ready" : null;
625
+ }, b = () => {
494
626
  var e;
495
627
  return !t.isProjectDirty() && !((e = t.blockReload) != null && e.isRunning());
496
628
  };
@@ -505,14 +637,14 @@ function ee(e, t) {
505
637
  return r;
506
638
  },
507
639
  get reloadState() {
508
- return v();
640
+ return y();
509
641
  },
510
642
  get reloadKind() {
511
- return g();
643
+ return v();
512
644
  },
513
645
  get canAutoReload() {
514
646
  let e = n == null ? void 0 : n.pending;
515
- return v() === "ready" && typeof e == "object" && !!e && e.stable;
647
+ return y() === "ready" && typeof e == "object" && !!e && e.stable;
516
648
  },
517
649
  get settling() {
518
650
  let e = n == null ? void 0 : n.pending;
@@ -530,27 +662,28 @@ function ee(e, t) {
530
662
  if (i || r || !n || !t.blockReload) return Promise.resolve();
531
663
  if (o) return o;
532
664
  let e = n, a = e.baseline;
533
- return o = h(e).then((t) => {
665
+ return o = g(e).then((t) => {
534
666
  n === e && e.baseline === a && !r && (e.pending = t);
535
667
  }).finally(() => {
536
668
  o = null;
537
669
  }), o;
538
670
  },
539
671
  async reload() {
540
- if (!n || v() !== "ready" || !t.blockReload) return !1;
672
+ if (!n || y() !== "ready" || !t.blockReload) return !1;
541
673
  let o = n;
542
674
  d(o), r = !0;
543
675
  try {
544
- let r = a, u = await h(o);
545
- if (n !== o || i || e.runtime.getTargetForStage() !== o.stage || (o.pending = u, !u || typeof u == "string" || u.edits === null || r !== a || !y())) return !1;
546
- let d;
676
+ let r = a, d = await g(o);
677
+ if (n !== o || i || e.runtime.getTargetForStage() !== o.stage || (o.pending = d, !d || typeof d == "string" || d.edits === null || r !== a || !b())) return !1;
678
+ let f;
547
679
  try {
548
- var c;
549
- d = Y((c = e.runtime.targets) == null ? [] : c, u.edits);
680
+ var c, u;
681
+ let { edits: n } = d;
682
+ f = n.kind === "values" ? H((c = e.runtime.targets) == null ? [] : c, n.changes) : pe((u = e.runtime.targets) == null ? [] : u, n.changes, t.blockReload.deserializeBlocks);
550
683
  } catch (e) {
551
- throw e instanceof _ && (o.pending = l(l({}, u), {}, { edits: null })), e;
684
+ throw o.pending = l(l({}, d), {}, { edits: null }), e;
552
685
  }
553
- return o.baseline = s(), o.source.project = u.update.project, o.source.files.set(m, u.update.bytes), o.source.versions.set(m, u.update.version), o.pending = null, t.blockReload.onApplied(d), !0;
686
+ return o.baseline = s(), o.source.project = d.update.project, o.source.files.set(m, d.update.bytes), o.source.versions.set(m, d.update.version), o.pending = null, t.blockReload.onApplied(f), !0;
554
687
  } finally {
555
688
  r = !1;
556
689
  }
@@ -581,11 +714,11 @@ function ee(e, t) {
581
714
  let e = n;
582
715
  d(e), r = !0;
583
716
  try {
584
- let r = a, i = s(), o = I(e.source.project, e.baseline, i);
585
- if (await N(e.source), d(e), !o) return a === r && t.onSaved(), "unchanged";
717
+ let r = a, i = s(), o = te(e.source.project, e.baseline, i);
718
+ if (await M(e.source), d(e), !o) return a === r && t.onSaved(), "unchanged";
586
719
  let c = `${JSON.stringify(o, null, 2)}\n`, l = await (await e.source.directory.getFileHandle(m)).createWritable({ mode: "exclusive" });
587
720
  try {
588
- await l.write(c), await N(e.source), d(e), await l.close();
721
+ await l.write(c), await M(e.source), d(e), await l.close();
589
722
  } catch (e) {
590
723
  throw await l.abort().catch(() => {}), e;
591
724
  }
@@ -598,7 +731,7 @@ function ee(e, t) {
598
731
  };
599
732
  }
600
733
  // src/index.ts
601
- var Q = {
734
+ var Z = {
602
735
  en: {
603
736
  open: "Open Project Folder…",
604
737
  save: "Save to Project Folder",
@@ -645,12 +778,12 @@ var Q = {
645
778
  waiting: "外部の書き込みが終わるのを待っています。",
646
779
  full: "この変更は作品全体の再読み込みが必要です。"
647
780
  }
648
- }, $ = /* @__PURE__ */ new WeakMap();
649
- function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0 }) {
781
+ }, Q = /* @__PURE__ */ new WeakMap();
782
+ function ge({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0 }) {
650
783
  var a;
651
784
  let o = t.defaultView, s = o == null ? void 0 : o.showDirectoryPicker;
652
785
  if (!s || !((a = e.runtime) != null && a.storage)) return null;
653
- let c = ee(e, n), l = t.createElement("output");
786
+ let c = he(e, n), l = t.createElement("output");
654
787
  l.dataset.projectFolderStatus = "", l.setAttribute("role", "status"), l.hidden = !0, Object.assign(l.style, {
655
788
  position: "fixed",
656
789
  insetInlineEnd: "1rem",
@@ -667,7 +800,7 @@ function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
667
800
  l.isConnected && (l.hidden = !1, l.textContent = e, o.clearTimeout(u), u = o.setTimeout(() => {
668
801
  l.hidden = !0;
669
802
  }, 7500));
670
- }, f = (e) => e.startsWith("ja") ? Q.ja : Q.en, p = (e, t) => {
803
+ }, f = (e) => e.startsWith("ja") ? Z.ja : Z.en, p = (e, t) => {
671
804
  let n = f(e), r = t instanceof _ && t.message !== t.code ? ` (${t.message})` : "";
672
805
  d((t instanceof _ ? n[t.code] : n.failed) + r);
673
806
  }, m, h = () => {};
@@ -734,7 +867,7 @@ function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
734
867
  S(), o.clearInterval(C), o.clearTimeout(u), v == null || v.disconnect(), o.removeEventListener("focus", b), t.removeEventListener("visibilitychange", b), a.remove();
735
868
  };
736
869
  }
737
- return $.set(e, {
870
+ return Q.set(e, {
738
871
  session: c,
739
872
  open(e) {
740
873
  let t = f(e);
@@ -748,22 +881,22 @@ function te({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
748
881
  }), {
749
882
  openDirectory: (...e) => c.openDirectory(...e).finally(h),
750
883
  dispose() {
751
- $.delete(e), c.dispose(), m == null || m(), o.clearTimeout(u), l.remove();
884
+ Q.delete(e), c.dispose(), m == null || m(), o.clearTimeout(u), l.remove();
752
885
  }
753
886
  };
754
887
  }
755
- function ne(e, t = "en") {
756
- let n = $.get(e);
888
+ function $(e, t = "en") {
889
+ let n = Q.get(e);
757
890
  if (n) return {
758
891
  open: () => n.open(t),
759
892
  save: n.session.canSave ? () => n.save(t) : void 0,
760
893
  detach: () => n.session.detach()
761
894
  };
762
895
  }
763
- function re(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequestClose: a }) {
764
- let o = $.get(t);
896
+ function _e(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequestClose: a }) {
897
+ let o = Q.get(t);
765
898
  if (!o) return null;
766
- let s = n.startsWith("ja") ? Q.ja : Q.en, c = (t) => {
899
+ let s = n.startsWith("ja") ? Z.ja : Z.en, c = (t) => {
767
900
  let i = () => {
768
901
  a(), o[t](n);
769
902
  };
@@ -780,4 +913,4 @@ function re(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequest
780
913
  };
781
914
  return e(i, null, c("open"), o.session.canSave ? c("save") : null);
782
915
  }
783
- export { te as mountProjectFolder, ne as projectFolderActions, re as renderProjectFolderMenu };
916
+ export { ge as mountProjectFolder, $ as projectFolderActions, _e as renderProjectFolderMenu };
@@ -0,0 +1,50 @@
1
+ import type { JsonObject, Project } from './source.js';
2
+ import type { ReloadTarget } from './block-reload.js';
3
+ /** A block as the VM stores it after `deserializeBlocks`. */
4
+ export type VmBlock = {
5
+ id: string;
6
+ opcode: string;
7
+ topLevel: boolean;
8
+ parent?: string | null;
9
+ comment?: string;
10
+ fields: Record<string, {
11
+ name?: string;
12
+ value: unknown;
13
+ id?: string | null;
14
+ variableType?: string;
15
+ }>;
16
+ };
17
+ /** The VM's sb3 `deserializeBlocks`: turns serialized blocks into VM blocks, in place. Results are checked before use. */
18
+ export type DeserializeBlocks = (blocks: Record<string, unknown>) => Record<string, {
19
+ id: string;
20
+ }>;
21
+ type Container = ReloadTarget['blocks'] & {
22
+ _blocks: Record<string, VmBlock>;
23
+ _scripts: string[];
24
+ createBlock(block: VmBlock, deferProjectChanged?: boolean): void;
25
+ deleteBlock(id: string): void;
26
+ resetCache(): void;
27
+ };
28
+ export type ScriptReloadTarget = ReloadTarget & {
29
+ blocks: Container;
30
+ comments?: Record<string, unknown>;
31
+ lookupVariableById?(id: string): unknown;
32
+ };
33
+ /** Replace whole scripts of one target: delete the old top blocks, then create the new scripts' blocks. */
34
+ export type ScriptEdit = {
35
+ target: string;
36
+ stage: boolean;
37
+ remove: string[];
38
+ blocks: JsonObject;
39
+ };
40
+ /**
41
+ * Plans script replacements for changes that add, remove or reconnect blocks. Every other property of the
42
+ * project and its targets, including comments, must stay the same; otherwise the whole project is reloaded.
43
+ */
44
+ export declare function planScriptReload(before: Project, after: Project): ScriptEdit[];
45
+ /**
46
+ * Applies planned script replacements. Every edit is checked against the VM before any change. If a change
47
+ * fails part way, every target is restored to its previous blocks.
48
+ */
49
+ export declare function applyScriptReload(targets: readonly ScriptReloadTarget[], edits: ScriptEdit[], deserialize: DeserializeBlocks): ScriptReloadTarget[];
50
+ export {};
package/dist/session.d.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import type { Storage } from './source.js';
2
2
  import type { ReloadTarget } from './block-reload.js';
3
+ import type { DeserializeBlocks } from './script-reload.js';
3
4
  export interface FolderVM {
4
5
  runtime: {
5
6
  storage: Storage;
@@ -35,10 +36,15 @@ export interface FolderHost {
35
36
  isRunning(): boolean;
36
37
  subscribe(listener: () => void): () => void;
37
38
  onApplied(targets: readonly ReloadTarget[]): void;
39
+ /**
40
+ * The VM's sb3 `deserializeBlocks`. With it, changes that add, remove or reconnect blocks replace the
41
+ * changed scripts in place; without it they need the whole project reloaded.
42
+ */
43
+ deserializeBlocks?: DeserializeBlocks;
38
44
  };
39
45
  }
40
46
  /**
41
- * `ready`: values and positions can be applied in place. `full`: the change needs the whole project reloaded.
47
+ * `ready`: the change can be applied in place: values and positions, or with `deserializeBlocks`, whole scripts. `full`: the change needs the whole project reloaded.
42
48
  * `waiting`: an external write looks incomplete and is checked again. `dirty`, `running` and `busy` hold the change.
43
49
  */
44
50
  export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.2.0",
3
+ "version": "0.3.0",
4
4
  "description": "Read and save expanded Scratch project folders in TurboWarp Plus Editor",
5
5
  "type": "module",
6
6
  "license": "MPL-2.0",
@@ -21,8 +21,13 @@
21
21
  "src",
22
22
  "vite.config.ts",
23
23
  "tsconfig.json",
24
- "README.ja.md"
24
+ "README.ja.md",
25
+ "README.md",
26
+ "LICENSE"
25
27
  ],
28
+ "publishConfig": {
29
+ "access": "public"
30
+ },
26
31
  "scripts": {
27
32
  "build": "vite build && tsc -p tsconfig.json",
28
33
  "test": "npm run build && node --test",
package/src/index.ts CHANGED
@@ -4,6 +4,7 @@ import type {FolderHost, FolderVM, PickerWindow} from './session.js';
4
4
 
5
5
  export type {FolderHost, FolderVM, OpenResult} from './session.js';
6
6
  export type {ReloadTarget} from './block-reload.js';
7
+ export type {DeserializeBlocks} from './script-reload.js';
7
8
 
8
9
  const messages = {
9
10
  en: {
@@ -0,0 +1,171 @@
1
+ import {equal, isObject, unsupported} from './source.js';
2
+ import type {Json, JsonObject, Project} from './source.js';
3
+ import type {ReloadTarget} from './block-reload.js';
4
+
5
+ /** A block as the VM stores it after `deserializeBlocks`. */
6
+ export type VmBlock = {
7
+ id: string; opcode: string; topLevel: boolean; parent?: string | null; comment?: string;
8
+ fields: Record<string, {name?: string; value: unknown; id?: string | null; variableType?: string}>;
9
+ };
10
+ /** The VM's sb3 `deserializeBlocks`: turns serialized blocks into VM blocks, in place. Results are checked before use. */
11
+ export type DeserializeBlocks = (blocks: Record<string, unknown>) => Record<string, {id: string}>;
12
+
13
+ type Container = ReloadTarget['blocks'] & {
14
+ _blocks: Record<string, VmBlock>;
15
+ _scripts: string[];
16
+ createBlock(block: VmBlock, deferProjectChanged?: boolean): void;
17
+ deleteBlock(id: string): void;
18
+ resetCache(): void;
19
+ };
20
+ export type ScriptReloadTarget = ReloadTarget & {
21
+ blocks: Container;
22
+ comments?: Record<string, unknown>;
23
+ lookupVariableById?(id: string): unknown;
24
+ };
25
+
26
+ /** Replace whole scripts of one target: delete the old top blocks, then create the new scripts' blocks. */
27
+ export type ScriptEdit = {target: string; stage: boolean; remove: string[]; blocks: JsonObject};
28
+
29
+ const reject = (detail = 'Only changes to the scripts of existing targets can be reloaded in place'): never =>
30
+ unsupported(detail);
31
+ // Shadow and menu blocks use these prefixes too. Other prefixes must already appear in the project,
32
+ // so that a reload never needs an extension the VM has not loaded.
33
+ const corePrefixes = new Set(['motion', 'looks', 'sound', 'event', 'control', 'sensing', 'operator', 'data',
34
+ 'procedures', 'argument', 'math', 'text', 'colour']);
35
+ const prefix = (opcode: string) => opcode.split('_', 1)[0];
36
+ const variableFields = new Set(['VARIABLE', 'LIST', 'BROADCAST_OPTION']);
37
+
38
+ // A top-level primitive is stored as an array and is its own script.
39
+ const parentOf = (block: Json): string | null => isObject(block) && typeof block.parent === 'string' ? block.parent : null;
40
+
41
+ function rootsOf(blocks: JsonObject) {
42
+ const roots = new Map<string, string>();
43
+ for (const id of Object.keys(blocks)) {
44
+ let current = id;
45
+ const seen = new Set<string>();
46
+ for (;;) {
47
+ if (seen.has(current)) return reject('Blocks form a cycle');
48
+ seen.add(current);
49
+ const parent = parentOf(blocks[current]);
50
+ if (parent === null) break;
51
+ if (!Object.hasOwn(blocks, parent)) return reject('A block refers to a missing parent');
52
+ current = parent;
53
+ }
54
+ roots.set(id, current);
55
+ }
56
+ return roots;
57
+ }
58
+
59
+ function opcodesOf(blocks: JsonObject, into: Set<string>) {
60
+ for (const block of Object.values(blocks)) {
61
+ if (isObject(block) && typeof block.opcode === 'string') into.add(prefix(block.opcode));
62
+ }
63
+ }
64
+
65
+ /**
66
+ * Plans script replacements for changes that add, remove or reconnect blocks. Every other property of the
67
+ * project and its targets, including comments, must stay the same; otherwise the whole project is reloaded.
68
+ */
69
+ export function planScriptReload(before: Project, after: Project): ScriptEdit[] {
70
+ const {targets: oldTargets, ...oldProject} = before;
71
+ const {targets: newTargets, ...newProject} = after;
72
+ if (oldTargets.length !== newTargets.length || !equal(oldProject, newProject)) return reject();
73
+ const known = new Set(corePrefixes);
74
+ for (const target of oldTargets) if (isObject(target.blocks)) opcodesOf(target.blocks, known);
75
+ const edits: ScriptEdit[] = [];
76
+ for (const [index, oldTarget] of oldTargets.entries()) {
77
+ const {blocks: oldValue, ...oldRest} = oldTarget;
78
+ const {blocks: newValue, ...newRest} = newTargets[index];
79
+ if (!equal(oldRest, newRest)) return reject();
80
+ if (equal(oldValue, newValue)) continue;
81
+ const oldBlocks = isObject(oldValue) ? oldValue : {};
82
+ const newBlocks = isObject(newValue) ? newValue : {};
83
+ const oldRoots = rootsOf(oldBlocks);
84
+ const newRoots = rootsOf(newBlocks);
85
+ const removed = new Set<string>();
86
+ const added = new Set<string>();
87
+ const mark = (id: string) => {
88
+ const oldRoot = oldRoots.get(id);
89
+ const newRoot = newRoots.get(id);
90
+ let grew = false;
91
+ if (oldRoot !== undefined && !removed.has(oldRoot)) {removed.add(oldRoot); grew = true;}
92
+ if (newRoot !== undefined && !added.has(newRoot)) {added.add(newRoot); grew = true;}
93
+ return grew;
94
+ };
95
+ for (const id of new Set([...Object.keys(oldBlocks), ...Object.keys(newBlocks)])) {
96
+ if (!equal(oldBlocks[id], newBlocks[id])) mark(id);
97
+ }
98
+ // A block in a replaced script is replaced with it on both sides, so no script is left half-moved.
99
+ for (let grew = true; grew;) {
100
+ grew = false;
101
+ for (const [id, root] of oldRoots) if (removed.has(root) && mark(id)) grew = true;
102
+ for (const [id, root] of newRoots) if (added.has(root) && mark(id)) grew = true;
103
+ }
104
+ const blocks: JsonObject = {};
105
+ for (const [id, root] of newRoots) if (added.has(root)) blocks[id] = newBlocks[id];
106
+ for (const block of Object.values(blocks)) {
107
+ if (!isObject(block)) continue;
108
+ if (typeof block.opcode !== 'string') return reject('A block has no opcode');
109
+ if (!known.has(prefix(block.opcode))) return reject(`Blocks need an extension the project does not use: ${block.opcode}`);
110
+ }
111
+ edits.push({target: oldTarget.name, stage: oldTarget.isStage, remove: [...removed], blocks});
112
+ }
113
+ return edits;
114
+ }
115
+
116
+ const resolveTarget = (targets: readonly ScriptReloadTarget[], edit: ScriptEdit) => {
117
+ const matching = targets.filter(target => target.isStage === edit.stage &&
118
+ (edit.stage || target.isOriginal && target.getName() === edit.target));
119
+ return matching.length === 1 ? matching[0] : reject();
120
+ };
121
+
122
+ /**
123
+ * Applies planned script replacements. Every edit is checked against the VM before any change. If a change
124
+ * fails part way, every target is restored to its previous blocks.
125
+ */
126
+ export function applyScriptReload(targets: readonly ScriptReloadTarget[], edits: ScriptEdit[], deserialize: DeserializeBlocks) {
127
+ const prepared = edits.map(edit => {
128
+ const target = resolveTarget(targets, edit);
129
+ const container = target.blocks;
130
+ for (const id of edit.remove) {
131
+ const block = container.getBlock(id);
132
+ if (!block || !block.topLevel || !container._scripts.includes(id)) return reject('The editor and the folder differ');
133
+ }
134
+ const created = Object.values(deserialize(JSON.parse(JSON.stringify(edit.blocks)))) as VmBlock[];
135
+ for (const block of created) {
136
+ if (typeof block.id !== 'string' || typeof block.opcode !== 'string') return reject('A block could not be read');
137
+ if (block.comment && !(target.comments && Object.hasOwn(target.comments, block.comment))) {
138
+ return reject('A block refers to a missing comment');
139
+ }
140
+ for (const [name, field] of Object.entries(block.fields ?? {})) {
141
+ if (!variableFields.has(name) && !field.variableType) continue;
142
+ if (typeof field.id !== 'string' || !target.lookupVariableById?.(field.id)) {
143
+ return reject('A block refers to a variable, list or message the project does not have');
144
+ }
145
+ }
146
+ }
147
+ return {target, container, edit, created};
148
+ });
149
+ const saved = prepared.map(({container}) => ({container, blocks: {...container._blocks}, scripts: [...container._scripts],
150
+ tops: new Map(Object.entries(container._blocks).map(([id, block]) => [id, block.topLevel]))}));
151
+ try {
152
+ for (const {container, edit, created} of prepared) {
153
+ for (const id of edit.remove) container.deleteBlock(id);
154
+ for (const block of created) {
155
+ container.createBlock(block, true);
156
+ // createBlock ignores an id that is already present, which would leave the script incomplete.
157
+ if (container._blocks[block.id] !== block) reject('A block id is already in use');
158
+ }
159
+ container.resetCache();
160
+ }
161
+ } catch (error) {
162
+ for (const {container, blocks, scripts, tops} of saved) {
163
+ container._blocks = blocks;
164
+ container._scripts = scripts;
165
+ for (const [id, top] of tops) blocks[id].topLevel = top;
166
+ container.resetCache();
167
+ }
168
+ throw error;
169
+ }
170
+ return prepared.map(({target}) => target);
171
+ }
package/src/session.ts CHANGED
@@ -2,6 +2,8 @@ import {assetKey, assertFolderUnchanged, FolderError, parseProject, projectChang
2
2
  import type {Asset, FolderSource, FolderUpdate, Project, Storage} from './source.js';
3
3
  import {applyBlockReload, planBlockReload} from './block-reload.js';
4
4
  import type {ReloadTarget} from './block-reload.js';
5
+ import {applyScriptReload, planScriptReload} from './script-reload.js';
6
+ import type {DeserializeBlocks, ScriptReloadTarget} from './script-reload.js';
5
7
 
6
8
  export interface FolderVM {
7
9
  runtime: {
@@ -44,15 +46,22 @@ export interface FolderHost {
44
46
  isRunning(): boolean;
45
47
  subscribe(listener: () => void): () => void;
46
48
  onApplied(targets: readonly ReloadTarget[]): void;
49
+ /**
50
+ * The VM's sb3 `deserializeBlocks`. With it, changes that add, remove or reconnect blocks replace the
51
+ * changed scripts in place; without it they need the whole project reloaded.
52
+ */
53
+ deserializeBlocks?: DeserializeBlocks;
47
54
  };
48
55
  }
49
56
 
50
57
  // `stable` turns true once two scans see the same file version, so consecutive writes settle before auto-apply.
51
- type PendingUpdate = {update: FolderUpdate; edits: ReturnType<typeof planBlockReload> | null; stable: boolean};
58
+ type Edits = {kind: 'values'; changes: ReturnType<typeof planBlockReload>} |
59
+ {kind: 'scripts'; changes: ReturnType<typeof planScriptReload>};
60
+ type PendingUpdate = {update: FolderUpdate; edits: Edits | null; stable: boolean};
52
61
  type Pending = PendingUpdate | 'structure' | 'waiting';
53
62
  type Session = {source: FolderSource; baseline: Project; stage: object; pending: Pending | null};
54
63
  /**
55
- * `ready`: values and positions can be applied in place. `full`: the change needs the whole project reloaded.
64
+ * `ready`: the change can be applied in place: values and positions, or with `deserializeBlocks`, whole scripts. `full`: the change needs the whole project reloaded.
56
65
  * `waiting`: an external write looks incomplete and is checked again. `dirty`, `running` and `busy` hold the change.
57
66
  */
58
67
  export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
@@ -119,17 +128,27 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
119
128
  busy = false;
120
129
  }
121
130
  };
131
+ // Value and position edits keep every VM block. Other script changes replace only the changed scripts.
132
+ const planEdits = (before: Project, after: Project): Edits | null => {
133
+ try {
134
+ return {kind: 'values', changes: planBlockReload(before, after)};
135
+ } catch (error) {
136
+ if (!(error instanceof FolderError)) throw error;
137
+ }
138
+ if (!host.blockReload?.deserializeBlocks) return null;
139
+ try {
140
+ return {kind: 'scripts', changes: planScriptReload(before, after)};
141
+ } catch (error) {
142
+ if (!(error instanceof FolderError)) throw error;
143
+ return null;
144
+ }
145
+ };
122
146
  const readUpdate = async (session: Session): Promise<Session['pending']> => {
123
147
  const previous = typeof session.pending === 'object' ? session.pending : null;
124
148
  const update = await readFolderUpdate(session.source, previous?.update ?? null);
125
149
  if (!update || typeof update === 'string') return update;
126
150
  if (previous?.update === update) return {...previous, stable: true};
127
- try {
128
- return {update, edits: planBlockReload(session.source.project, update.project), stable: false};
129
- } catch (error) {
130
- if (!(error instanceof FolderError)) throw error;
131
- return {update, edits: null, stable: false};
132
- }
151
+ return {update, edits: planEdits(session.source.project, update.project), stable: false};
133
152
  };
134
153
  const reloadKind = (): ReloadKind => {
135
154
  const pending = current?.pending;
@@ -193,9 +212,13 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
193
212
  }
194
213
  let targets: readonly ReloadTarget[];
195
214
  try {
196
- targets = applyBlockReload(vm.runtime.targets ?? [], pending.edits);
215
+ const {edits} = pending;
216
+ targets = edits.kind === 'values' ? applyBlockReload(vm.runtime.targets ?? [], edits.changes) :
217
+ applyScriptReload((vm.runtime.targets ?? []) as readonly ScriptReloadTarget[], edits.changes,
218
+ host.blockReload.deserializeBlocks!);
197
219
  } catch (error) {
198
- if (error instanceof FolderError) session.pending = {...pending, edits: null};
220
+ // After a refused or failed in-place change, offer the whole reload instead of retrying it.
221
+ session.pending = {...pending, edits: null};
199
222
  throw error;
200
223
  }
201
224
  session.baseline = snapshot();
package/vite.config.ts CHANGED
@@ -4,6 +4,7 @@ export default defineConfig({
4
4
  build: {
5
5
  // The pinned Scratch GUI still parses the library with Webpack 4.
6
6
  target: 'es2017',
7
+ license: {fileName: 'THIRD_PARTY_NOTICES.md'},
7
8
  lib: {entry: 'src/index.ts', formats: ['es'], fileName: () => 'index.js'}
8
9
  }
9
10
  });