@kubohiroya/turbowarp-plus-editor-project-folder 0.4.0 → 0.5.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
@@ -10,7 +10,7 @@ TurboWarp Plus Editor で既存の sb3-toolchain v1 の作品フォルダを開
10
10
  - `renderProjectFolderMenu(createElement, props)` は既存の開く・保存コマンドをホストのファイルメニューに渡します。
11
11
  - 接続後の `openDirectory(handle, confirmReplace)` には、ホストが選択済みのディレクトリハンドルを渡せます。ファイルメニューと同じ作品検証・未保存編集の確認を経て開き、保存先にはその作品フォルダを使います。
12
12
 
13
- ホストは VM、メニューコンポーネント、作品状態を扱うコールバックを渡します。メニューからフォルダを開くには、ブラウザーが File System Access のフォルダ選択に対応している必要があります。試作段階では既存作品の標準ブロック編集を扱います。 [Editor #305](https://github.com/kubohiroya/turbowarp-plus-editor/issues/305) · [Editor #308](https://github.com/kubohiroya/turbowarp-plus-editor/issues/308)
13
+ ホストは VM、メニューコンポーネント、作品状態を扱うコールバックを渡します。メニューからフォルダを開くには、ブラウザーが File System Access のフォルダ選択に対応している必要があります。保存で書き換えるのは作品データ(`project.source.json`)だけです。ブロック、変数・リスト、スプライトの位置や大きさなどの項目、モニター、組み込みの拡張機能の編集を保存し、作品の実行で変わった状態も含みます。スプライトの追加・削除・名前の変更と、コスチューム・音の追加・削除は、まだ保存しません。カスタム拡張機能・埋め込み拡張・フォントを含む作品は開けません。 [Editor #305](https://github.com/kubohiroya/turbowarp-plus-editor/issues/305) · [Editor #308](https://github.com/kubohiroya/turbowarp-plus-editor/issues/308)
14
14
 
15
15
  ## 外部変更
16
16
 
package/README.md CHANGED
@@ -10,7 +10,7 @@ This package opens and saves existing sb3-toolchain v1 project folders in TurboW
10
10
  - `renderProjectFolderMenu(createElement, props)` supplies the existing open and save commands to the host's file menu.
11
11
  - The mounted session's `openDirectory(handle, confirmReplace)` accepts a directory handle already selected by the host. It uses the same project validation and unsaved-edit confirmation as the file menu. Save still targets the opened folder.
12
12
 
13
- The host supplies the VM, menu components, and project state callbacks. The browser must support the File System Access picker for the built-in open command. This prototype supports standard block edits in existing projects. See [Editor issue #305](https://github.com/kubohiroya/turbowarp-plus-editor/issues/305) and [issue #308](https://github.com/kubohiroya/turbowarp-plus-editor/issues/308).
13
+ The host supplies the VM, menu components, and project state callbacks. The browser must support the File System Access picker for the built-in open command. Save writes the project file only: block, variable, list, sprite property, monitor and built-in extension edits are saved, including state that changes while the project runs. Adding, removing or renaming sprites, and adding or removing costumes and sounds, are not saved yet. Projects with custom extensions, embedded extensions or fonts cannot be opened. See [Editor issue #305](https://github.com/kubohiroya/turbowarp-plus-editor/issues/305) and [issue #308](https://github.com/kubohiroya/turbowarp-plus-editor/issues/308).
14
14
 
15
15
  ## External changes
16
16
 
package/dist/index.js CHANGED
@@ -60,93 +60,37 @@ function r(e, t) {
60
60
  }
61
61
  return a;
62
62
  }
63
- // \0@oxc-project+runtime@0.156.0/helpers/esm/typeof.js
64
- function i(e) {
65
- "@babel/helpers - typeof";
66
- return i = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) {
67
- return typeof e;
68
- } : function(e) {
69
- return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
70
- }, i(e);
71
- }
72
- // \0@oxc-project+runtime@0.156.0/helpers/esm/toPrimitive.js
73
- function a(e, t) {
74
- if (i(e) != "object" || !e) return e;
75
- var n = e[Symbol.toPrimitive];
76
- if (n !== void 0) {
77
- var r = n.call(e, t || "default");
78
- if (i(r) != "object") return r;
79
- throw TypeError("@@toPrimitive must return a primitive value.");
80
- }
81
- return (t === "string" ? String : Number)(e);
82
- }
83
- // \0@oxc-project+runtime@0.156.0/helpers/esm/toPropertyKey.js
84
- function o(e) {
85
- var t = a(e, "string");
86
- return i(t) == "symbol" ? t : t + "";
87
- }
88
- // \0@oxc-project+runtime@0.156.0/helpers/esm/defineProperty.js
89
- function s(e, t, n) {
90
- return (t = o(t)) in e ? Object.defineProperty(e, t, {
91
- value: n,
92
- enumerable: !0,
93
- configurable: !0,
94
- writable: !0
95
- }) : e[t] = n, e;
96
- }
97
- // \0@oxc-project+runtime@0.156.0/helpers/esm/objectSpread2.js
98
- function c(e, t) {
99
- var n = Object.keys(e);
100
- if (Object.getOwnPropertySymbols) {
101
- var r = Object.getOwnPropertySymbols(e);
102
- t && (r = r.filter(function(t) {
103
- return Object.getOwnPropertyDescriptor(e, t).enumerable;
104
- })), n.push.apply(n, r);
105
- }
106
- return n;
107
- }
108
- function l(e) {
109
- for (var t = 1; t < arguments.length; t++) {
110
- var n = arguments[t] == null ? {} : arguments[t];
111
- t % 2 ? c(Object(n), !0).forEach(function(t) {
112
- s(e, t, n[t]);
113
- }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : c(Object(n)).forEach(function(t) {
114
- Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
115
- });
116
- }
117
- return e;
118
- }
119
63
  // src/source.ts
120
- var u = ["targets"], d = ["targets"], f = ["blocks", "comments"], p = ["blocks", "comments"], m = "project.source.json", h = "sb3-source.json", g = "embedded-extensions.json", _ = class extends Error {
64
+ var i = ["targets"], a = ["targets"], o = ["targets"], s = "project.source.json", c = "sb3-source.json", l = "embedded-extensions.json", u = class extends Error {
121
65
  constructor(e, t) {
122
66
  super(t == null ? e : t), this.code = e;
123
67
  }
124
- }, v = (e) => {
125
- throw new _("unsupported", e);
126
- }, y = (e) => typeof e == "object" && !!e && !Array.isArray(e), b = (e) => {
68
+ }, d = (e) => {
69
+ throw new u("unsupported", e);
70
+ }, f = (e) => typeof e == "object" && !!e && !Array.isArray(e), p = (e) => {
127
71
  let t = JSON.parse(e);
128
- return y(t) ? t : v("Expected a JSON object");
129
- }, x = (e) => e.isStage ? "stage" : `sprite:${e.name}`;
130
- function S(e) {
131
- let t = b(e);
132
- if (!Array.isArray(t.targets)) return v("Missing targets");
72
+ return f(t) ? t : d("Expected a JSON object");
73
+ }, m = (e) => e.isStage ? "stage" : `sprite:${e.name}`;
74
+ function h(e) {
75
+ let t = p(e);
76
+ if (!Array.isArray(t.targets)) return d("Missing targets");
133
77
  let n = /* @__PURE__ */ new Set(), r = 0;
134
78
  for (let e of t.targets) {
135
- if (!y(e) || typeof e.isStage != "boolean" || typeof e.name != "string") return v("Invalid target");
136
- let t = x(e);
137
- if (n.has(t)) return v("Ambiguous target names");
138
- if (n.add(t), e.isStage && r++, e.blocks !== void 0 && !y(e.blocks)) return v("Invalid blocks");
139
- if (e.comments !== void 0 && !y(e.comments)) return v("Invalid comments");
79
+ if (!f(e) || typeof e.isStage != "boolean" || typeof e.name != "string") return d("Invalid target");
80
+ let t = m(e);
81
+ if (n.has(t)) return d("Ambiguous target names");
82
+ if (n.add(t), e.isStage && r++, e.blocks !== void 0 && !f(e.blocks)) return d("Invalid blocks");
83
+ if (e.comments !== void 0 && !f(e.comments)) return d("Invalid comments");
140
84
  }
141
- return r === 1 ? t : v("Expected one stage");
85
+ return r === 1 ? t : d("Expected one stage");
142
86
  }
143
- var C = async (e, t) => (await e.getFileHandle(t)).getFile(), w = (e) => `${e.size}:${e.lastModified}`, T = async (e) => new Uint8Array(await e.arrayBuffer()), E = async (e, t) => T(await C(e, t)), D = async (t) => {
87
+ var g = async (e, t) => (await e.getFileHandle(t)).getFile(), _ = (e) => `${e.size}:${e.lastModified}`, v = async (e) => new Uint8Array(await e.arrayBuffer()), y = async (e, t) => v(await g(e, t)), b = async (t) => {
144
88
  let n = /* @__PURE__ */ new Set();
145
89
  var r = !1, i = !1, a;
146
90
  try {
147
91
  for (var o = e(t.values()), s; r = !(s = await o.next()).done; r = !1) {
148
92
  let e = s.value;
149
- if (e.kind !== "file") return v("Nested entries are outside the supported source format");
93
+ if (e.kind !== "file") return d("Nested entries are outside the supported source format");
150
94
  n.add(e.name);
151
95
  }
152
96
  } catch (e) {
@@ -159,31 +103,31 @@ var C = async (e, t) => (await e.getFileHandle(t)).getFile(), w = (e) => `${e.si
159
103
  }
160
104
  }
161
105
  return n;
162
- }, O = (e, t) => {
106
+ }, x = (e, t) => {
163
107
  let n = new Set(t);
164
108
  return e.size === n.size && [...e].every((e) => n.has(e));
165
- }, k = (e, t, n) => `${e.name}/${t}.${n}`;
166
- async function A(e, t) {
109
+ }, S = (e, t, n) => `${e.name}/${t}.${n}`;
110
+ async function C(e, t) {
167
111
  let n = /* @__PURE__ */ new Map(), r = async (e, t, r = "") => {
168
- let i = await C(e, t);
169
- return n.set(r + t, w(i)), [t, await T(i)];
112
+ let i = await g(e, t);
113
+ return n.set(r + t, _(i)), [t, await v(i)];
170
114
  }, i = [
171
- m,
172
- h,
173
- g
174
- ], a = new Map(await Promise.all(i.map((t) => r(e, t)))), o = new TextDecoder("utf-8", { fatal: !0 }), s = o.decode(a.get(m)), c = S(s), l = b(o.decode(a.get(h))), u = b(o.decode(a.get(g)));
175
- if (l.formatVersion !== 1 || l.project !== "project.source.json" || l.embeddedExtensions !== g || l.assetsDirectory !== "assets" || !Array.isArray(l.archiveEntries)) return v("Expected an sb3-toolchain v1 folder");
176
- if (u.formatVersion !== 1 || !Array.isArray(u.extensions) || u.extensions.length || u.extensionBundles !== void 0 && (!Array.isArray(u.extensionBundles) || u.extensionBundles.length) || c.turboWarpPlus !== void 0 || c.customFonts !== void 0 || c.extensionURLs !== void 0 && (!y(c.extensionURLs) || Object.keys(c.extensionURLs).length)) return v("Custom extensions and fonts are outside the prototype scope");
177
- let d = /* @__PURE__ */ new Set(["project.json"]), f = /* @__PURE__ */ new Map();
178
- for (let e of c.targets) for (let n of ["costumes", "sounds"]) {
179
- var p;
180
- let r = (p = e[n]) == null ? [] : p;
181
- if (!Array.isArray(r)) return v("Invalid asset list");
115
+ s,
116
+ c,
117
+ l
118
+ ], a = new Map(await Promise.all(i.map((t) => r(e, t)))), o = new TextDecoder("utf-8", { fatal: !0 }), u = o.decode(a.get(s)), m = h(u), y = p(o.decode(a.get(c))), C = p(o.decode(a.get(l)));
119
+ if (y.formatVersion !== 1 || y.project !== "project.source.json" || y.embeddedExtensions !== l || y.assetsDirectory !== "assets" || !Array.isArray(y.archiveEntries)) return d("Expected an sb3-toolchain v1 folder");
120
+ if (C.formatVersion !== 1 || !Array.isArray(C.extensions) || C.extensions.length || C.extensionBundles !== void 0 && (!Array.isArray(C.extensionBundles) || C.extensionBundles.length) || m.turboWarpPlus !== void 0 || m.customFonts !== void 0 || m.extensionURLs !== void 0 && (!f(m.extensionURLs) || Object.keys(m.extensionURLs).length)) return d("Custom extensions and fonts are not supported in project folders");
121
+ let w = /* @__PURE__ */ new Set(["project.json"]), T = /* @__PURE__ */ new Map();
122
+ for (let e of m.targets) for (let n of ["costumes", "sounds"]) {
123
+ var E;
124
+ let r = (E = e[n]) == null ? [] : E;
125
+ if (!Array.isArray(r)) return d("Invalid asset list");
182
126
  for (let e of r) {
183
- if (!y(e) || typeof e.assetId != "string" || !/^[a-f0-9]{32}$/u.test(e.assetId) || typeof e.dataFormat != "string") return v("Invalid asset reference");
127
+ if (!f(e) || typeof e.assetId != "string" || !/^[a-f0-9]{32}$/u.test(e.assetId) || typeof e.dataFormat != "string") return d("Invalid asset reference");
184
128
  let { assetId: r, dataFormat: i } = e, a = `${r}.${i}`, o = n === "sounds" ? /^(wav|mp3)$/u.test(i) ? t.AssetType.Sound : null : i === "svg" ? t.AssetType.ImageVector : /^(png|bmp|jpg|jpeg|gif)$/u.test(i) ? t.AssetType.ImageBitmap : null;
185
- if (!o || e.md5ext !== a) return v(`Unsupported asset reference: ${a}`);
186
- d.add(a), f.set(k(o, r, i), {
129
+ if (!o || e.md5ext !== a) return d(`Unsupported asset reference: ${a}`);
130
+ w.add(a), T.set(S(o, r, i), {
187
131
  id: r,
188
132
  format: i,
189
133
  type: o,
@@ -191,104 +135,169 @@ async function A(e, t) {
191
135
  });
192
136
  }
193
137
  }
194
- if (l.archiveEntries.length !== d.size || !O(new Set(l.archiveEntries), d)) return v("Asset references and archiveEntries do not match");
195
- d.delete("project.json");
196
- let [_, x] = await Promise.all([e.getDirectoryHandle("assets"), e.getDirectoryHandle("extensions")]);
197
- if (!O(await D(_), d) || (await D(x)).size) return v("Unexpected or missing source files");
198
- let E = new Map(await Promise.all([...d].map((e) => r(_, e, "assets/")))), A = /* @__PURE__ */ new Map();
199
- for (let [e, { id: n, format: r, type: i, name: a }] of f) {
200
- let o = t.createAsset(i, r, E.get(a).slice(), null, !0);
201
- if (o.assetId !== n) return v(`Asset hash mismatch: ${a}`);
138
+ if (y.archiveEntries.length !== w.size || !x(new Set(y.archiveEntries), w)) return d("Asset references and archiveEntries do not match");
139
+ w.delete("project.json");
140
+ let [D, O] = await Promise.all([e.getDirectoryHandle("assets"), e.getDirectoryHandle("extensions")]);
141
+ if (!x(await b(D), w) || (await b(O)).size) return d("Unexpected or missing source files");
142
+ let k = new Map(await Promise.all([...w].map((e) => r(D, e, "assets/")))), A = /* @__PURE__ */ new Map();
143
+ for (let [e, { id: n, format: r, type: i, name: a }] of T) {
144
+ let o = t.createAsset(i, r, k.get(a).slice(), null, !0);
145
+ if (o.assetId !== n) return d(`Asset hash mismatch: ${a}`);
202
146
  A.set(e, o);
203
147
  }
204
148
  return {
205
149
  versions: n,
206
150
  files: a,
207
151
  directory: e,
208
- bytes: E,
209
- project: c,
210
- projectText: s,
152
+ bytes: k,
153
+ project: m,
154
+ projectText: u,
211
155
  storageAssets: A
212
156
  };
213
157
  }
214
- var j = (e, t) => e.length === t.length && e.every((e, n) => e === t[n]);
215
- async function M(e, t) {
158
+ var w = (e, t) => e.length === t.length && e.every((e, n) => e === t[n]);
159
+ async function T(e, t) {
216
160
  let { directory: n, versions: r } = e;
217
161
  try {
218
162
  let [i, a, o] = await Promise.all([
219
163
  n.getDirectoryHandle("assets"),
220
164
  n.getDirectoryHandle("extensions"),
221
- C(n, m)
222
- ]), [s, c] = await Promise.all([D(i), D(a)]);
223
- if (!O(s, e.bytes.keys()) || c.size || (await Promise.all([...[h, g].map(async (e) => w(await C(n, e)) === r.get(e)), ...[...s].map(async (e) => w(await C(i, e)) === r.get(`assets/${e}`))])).includes(!1)) return "structure";
224
- let l = w(o);
225
- if (l === r.get("project.source.json")) return null;
226
- if ((t == null ? void 0 : t.version) === l) return t;
227
- let u = await T(o);
228
- return j(u, e.files.get("project.source.json")) ? (r.set(m, l), null) : {
229
- version: l,
230
- bytes: u,
231
- project: S(new TextDecoder("utf-8", { fatal: !0 }).decode(u))
165
+ g(n, s)
166
+ ]), [u, d] = await Promise.all([b(i), b(a)]);
167
+ if (!x(u, e.bytes.keys()) || d.size || (await Promise.all([...[c, l].map(async (e) => _(await g(n, e)) === r.get(e)), ...[...u].map(async (e) => _(await g(i, e)) === r.get(`assets/${e}`))])).includes(!1)) return "structure";
168
+ let f = _(o);
169
+ if (f === r.get("project.source.json")) return null;
170
+ if ((t == null ? void 0 : t.version) === f) return t;
171
+ let p = await v(o);
172
+ return w(p, e.files.get("project.source.json")) ? (r.set(s, f), null) : {
173
+ version: f,
174
+ bytes: p,
175
+ project: h(new TextDecoder("utf-8", { fatal: !0 }).decode(p))
232
176
  };
233
177
  } catch (e) {
234
- return e instanceof _ ? "structure" : "waiting";
178
+ return e instanceof u ? "structure" : "waiting";
235
179
  }
236
180
  }
237
- async function N(e) {
181
+ async function E(e) {
238
182
  try {
239
183
  let t = await e.directory.getDirectoryHandle("assets"), n = await e.directory.getDirectoryHandle("extensions");
240
- if (!O(await D(t), e.bytes.keys()) || (await D(n)).size) throw new _("conflict");
241
- for (let [t, n] of e.files) if (!j(await E(e.directory, t), n)) throw new _("conflict");
242
- for (let [n, r] of e.bytes) if (!j(await E(t, n), r)) throw new _("conflict");
184
+ if (!x(await b(t), e.bytes.keys()) || (await b(n)).size) throw new u("conflict");
185
+ for (let [t, n] of e.files) if (!w(await y(e.directory, t), n)) throw new u("conflict");
186
+ for (let [n, r] of e.bytes) if (!w(await y(t, n), r)) throw new u("conflict");
243
187
  } catch (e) {
244
- throw e instanceof _ || e instanceof DOMException && ["NotFoundError", "TypeMismatchError"].includes(e.name) ? new _("conflict") : e;
188
+ throw e instanceof u || e instanceof DOMException && ["NotFoundError", "TypeMismatchError"].includes(e.name) ? new u("conflict") : e;
245
189
  }
246
190
  }
247
- var P = (e, t) => {
191
+ var D = (e, t) => {
248
192
  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]));
250
- if (!y(e) || !y(t)) return !1;
193
+ if (Array.isArray(e) && Array.isArray(t)) return e.length === t.length && e.every((e, n) => D(e, t[n]));
194
+ if (!f(e) || !f(t)) return !1;
251
195
  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;
255
- if (!y(t) || !y(n)) return n;
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];
196
+ return n.length === Object.keys(t).length && n.every((n) => Object.hasOwn(t, n) && D(e[n], t[n]));
197
+ }, O = (e, t) => !f(e) || !f(t) || [
198
+ "id",
199
+ "assetId",
200
+ "name",
201
+ "opcode"
202
+ ].every((n) => !Object.hasOwn(e, n) || !Object.hasOwn(t, n) || D(e[n], t[n])), k = (e, t, n) => {
203
+ if (D(t, n)) return e === void 0 ? n : e;
204
+ if (Array.isArray(t) && Array.isArray(n) && Array.isArray(e) && t.length === n.length && e.length === n.length && e.every((e, n) => O(e, t[n]))) return n.map((n, r) => k(e[r], t[r], n));
205
+ if (!f(t) || !f(n)) return n;
206
+ let r = Object.assign(Object.create(null), f(e) ? e : {});
207
+ for (let e of Object.keys(t)) Object.hasOwn(n, e) ? D(t[e], n[e]) || (r[e] = k(Object.hasOwn(r, e) ? r[e] : void 0, t[e], n[e])) : delete r[e];
258
208
  for (let e of Object.keys(n)) Object.hasOwn(t, e) || (r[e] = n[e]);
259
209
  return r;
260
- };
261
- function I(e, t, n) {
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");
264
- let s = /* @__PURE__ */ new Map(), c = new Map(e.targets.map((e) => [x(e), e]));
265
- for (let [e, t] of o.entries()) {
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");
268
- let m = x(t), h = c.get(m);
269
- if (!h) return v("The original target could not be identified");
270
- if (!P(u, n) || !P(d, a)) {
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);
273
- }
210
+ }, A = (e) => {
211
+ let t = /* @__PURE__ */ new Set();
212
+ for (let n of e.targets) for (let e of ["costumes", "sounds"]) {
213
+ let r = n[e];
214
+ if (Array.isArray(r)) for (let e of r) f(e) && typeof e.md5ext == "string" && t.add(e.md5ext);
274
215
  }
275
- return s.size ? l(l({}, e), {}, { targets: e.targets.map((e) => {
276
- let t = s.get(x(e));
277
- return t ? l(l({}, e), t) : e;
278
- }) }) : null;
216
+ return t;
217
+ }, j = (e) => e.turboWarpPlus !== void 0 || e.customFonts !== void 0 || e.extensionURLs !== void 0 && (!f(e.extensionURLs) || Object.keys(e.extensionURLs).length > 0);
218
+ function M(e, t, n) {
219
+ let s = (e) => e.targets.map(m), c = s(t), l = s(n);
220
+ if (c.length !== l.length || !l.every((e) => c.includes(e))) return d("Adding, removing or renaming sprites is not saved to a project folder yet");
221
+ let u = A(n), f = A(t);
222
+ if (u.size !== f.size || [...u].some((e) => !f.has(e))) return d("Adding or removing costumes and sounds is not saved to a project folder yet");
223
+ if (j(n)) return d("Custom extensions and fonts are not saved to a project folder");
224
+ if (D(t, n)) return null;
225
+ let { targets: p } = e, h = r(e, i), { targets: g } = t, _ = r(t, a), { targets: v } = n, y = r(n, o), b = new Map(p.map((e) => [m(e), e])), x = new Map(g.map((e) => [m(e), e])), S = v.map((e) => {
226
+ let t = m(e), n = b.get(t);
227
+ return n ? k(n, x.get(t), e) : d("The original target could not be identified");
228
+ }), C = D(c, l) ? p.map(m) : l, w = new Map(S.map((e) => [m(e), e])), T = k(h, _, y), E = {};
229
+ for (let t of Object.keys(e)) t === "targets" ? E.targets = C.map((e) => w.get(e)) : Object.hasOwn(T, t) && (E[t] = T[t]);
230
+ for (let e of Object.keys(T)) Object.hasOwn(E, e) || (E[e] = T[e]);
231
+ return E;
232
+ }
233
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/typeof.js
234
+ function N(e) {
235
+ "@babel/helpers - typeof";
236
+ return N = typeof Symbol == "function" && typeof Symbol.iterator == "symbol" ? function(e) {
237
+ return typeof e;
238
+ } : function(e) {
239
+ return e && typeof Symbol == "function" && e.constructor === Symbol && e !== Symbol.prototype ? "symbol" : typeof e;
240
+ }, N(e);
241
+ }
242
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/toPrimitive.js
243
+ function P(e, t) {
244
+ if (N(e) != "object" || !e) return e;
245
+ var n = e[Symbol.toPrimitive];
246
+ if (n !== void 0) {
247
+ var r = n.call(e, t || "default");
248
+ if (N(r) != "object") return r;
249
+ throw TypeError("@@toPrimitive must return a primitive value.");
250
+ }
251
+ return (t === "string" ? String : Number)(e);
252
+ }
253
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/toPropertyKey.js
254
+ function ee(e) {
255
+ var t = P(e, "string");
256
+ return N(t) == "symbol" ? t : t + "";
257
+ }
258
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/defineProperty.js
259
+ function te(e, t, n) {
260
+ return (t = ee(t)) in e ? Object.defineProperty(e, t, {
261
+ value: n,
262
+ enumerable: !0,
263
+ configurable: !0,
264
+ writable: !0
265
+ }) : e[t] = n, e;
266
+ }
267
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/objectSpread2.js
268
+ function F(e, t) {
269
+ var n = Object.keys(e);
270
+ if (Object.getOwnPropertySymbols) {
271
+ var r = Object.getOwnPropertySymbols(e);
272
+ t && (r = r.filter(function(t) {
273
+ return Object.getOwnPropertyDescriptor(e, t).enumerable;
274
+ })), n.push.apply(n, r);
275
+ }
276
+ return n;
277
+ }
278
+ function I(e) {
279
+ for (var t = 1; t < arguments.length; t++) {
280
+ var n = arguments[t] == null ? {} : arguments[t];
281
+ t % 2 ? F(Object(n), !0).forEach(function(t) {
282
+ te(e, t, n[t]);
283
+ }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(n)) : F(Object(n)).forEach(function(t) {
284
+ Object.defineProperty(e, t, Object.getOwnPropertyDescriptor(n, t));
285
+ });
286
+ }
287
+ return e;
279
288
  }
280
289
  // src/block-reload.ts
281
- var ee = ["targets"], te = ["targets"], ne = ["blocks"], L = ["blocks"], R = [
290
+ var L = ["targets"], ne = ["targets"], re = ["blocks"], ie = ["blocks"], ae = [
282
291
  "inputs",
283
292
  "fields",
284
293
  "x",
285
294
  "y"
286
- ], z = [
295
+ ], oe = [
287
296
  "inputs",
288
297
  "fields",
289
298
  "x",
290
299
  "y"
291
- ], B = (e) => typeof e == "string" || typeof e == "boolean" || typeof e == "number" && Number.isFinite(e), V = {
300
+ ], R = (e) => typeof e == "string" || typeof e == "boolean" || typeof e == "number" && Number.isFinite(e), z = {
292
301
  4: ["math_number", "NUM"],
293
302
  5: ["math_positive_number", "NUM"],
294
303
  6: ["math_whole_number", "NUM"],
@@ -296,53 +305,53 @@ var ee = ["targets"], te = ["targets"], ne = ["blocks"], L = ["blocks"], R = [
296
305
  8: ["math_angle", "NUM"],
297
306
  9: ["colour_picker", "COLOUR"],
298
307
  10: ["text", "TEXT"]
299
- }, H = () => v("Only values and coordinates of existing blocks can be reloaded"), U = (e, t) => P(Object.keys(e), Object.keys(t)), W = (e, t) => typeof e != "number" || typeof t != "number" || !Number.isSafeInteger(e) || !Number.isSafeInteger(t) ? H() : {
308
+ }, B = () => d("Only values and coordinates of existing blocks can be reloaded"), V = (e, t) => D(Object.keys(e), Object.keys(t)), H = (e, t) => typeof e != "number" || typeof t != "number" || !Number.isSafeInteger(e) || !Number.isSafeInteger(t) ? B() : {
300
309
  x: e,
301
310
  y: t
302
311
  };
303
- function G(e, t) {
304
- let { targets: n } = e, i = r(e, ee), { targets: a } = t, o = r(t, te);
305
- if (n.length !== a.length || !P(i, o)) return H();
312
+ function U(e, t) {
313
+ let { targets: n } = e, i = r(e, L), { targets: a } = t, o = r(t, ne);
314
+ if (n.length !== a.length || !D(i, o)) return B();
306
315
  let s = [];
307
316
  for (let [e, t] of n.entries()) {
308
- let { blocks: n } = t, i = r(t, ne), o = a[e], { blocks: c } = o;
309
- if (!P(i, r(o, L))) return H();
310
- if (!y(n) || !y(c)) {
311
- if (P(n, c)) continue;
312
- return H();
317
+ let { blocks: n } = t, i = r(t, re), o = a[e], { blocks: c } = o;
318
+ if (!D(i, r(o, ie))) return B();
319
+ if (!f(n) || !f(c)) {
320
+ if (D(n, c)) continue;
321
+ return B();
313
322
  }
314
- if (!U(n, c)) return H();
323
+ if (!V(n, c)) return B();
315
324
  for (let [e, i] of Object.entries(n)) {
316
325
  let n = c[e];
317
- if (P(i, n)) continue;
318
- if (!y(i) || !y(n)) return H();
319
- let { inputs: a, fields: o, x: u, y: d } = i, f = r(i, R), { inputs: p, fields: m, x: h, y: g } = n;
320
- if (!P(f, r(n, z)) || typeof f.opcode != "string") return H();
326
+ if (D(i, n)) continue;
327
+ if (!f(i) || !f(n)) return B();
328
+ let { inputs: a, fields: o, x: l, y: u } = i, d = r(i, ae), { inputs: p, fields: m, x: h, y: g } = n;
329
+ if (!D(d, r(n, oe)) || typeof d.opcode != "string") return B();
321
330
  let _ = {
322
331
  id: e,
323
332
  target: t.name,
324
333
  stage: t.isStage,
325
- opcode: f.opcode
334
+ opcode: d.opcode
326
335
  };
327
- if (u !== h || d !== g) {
328
- if (f.topLevel !== !0) return H();
329
- s.push(l(l({}, _), {}, {
336
+ if (l !== h || u !== g) {
337
+ if (d.topLevel !== !0) return B();
338
+ s.push(I(I({}, _), {}, {
330
339
  kind: "position",
331
- before: W(u, d),
332
- after: W(h, g)
340
+ before: H(l, u),
341
+ after: H(h, g)
333
342
  }));
334
343
  }
335
- if (!P(o, m)) {
336
- if (!y(o) || !y(m) || !U(o, m)) return H();
344
+ if (!D(o, m)) {
345
+ if (!f(o) || !f(m) || !V(o, m)) return B();
337
346
  for (let [e, t] of Object.entries(o)) {
338
347
  let n = m[e];
339
- if (!P(t, n)) {
348
+ if (!D(t, n)) {
340
349
  if ([
341
350
  "VARIABLE",
342
351
  "LIST",
343
352
  "BROADCAST_OPTION"
344
- ].includes(e) || f.opcode === "sensing_of_object_menu" || !Array.isArray(t) || !Array.isArray(n) || t.length !== 1 || n.length !== 1 || !B(t[0]) || !B(n[0])) return H();
345
- s.push(l(l({}, _), {}, {
353
+ ].includes(e) || d.opcode === "sensing_of_object_menu" || !Array.isArray(t) || !Array.isArray(n) || t.length !== 1 || n.length !== 1 || !R(t[0]) || !R(n[0])) return B();
354
+ s.push(I(I({}, _), {}, {
346
355
  kind: "field",
347
356
  name: e,
348
357
  before: t[0],
@@ -351,18 +360,18 @@ function G(e, t) {
351
360
  }
352
361
  }
353
362
  }
354
- if (!P(a, p)) {
355
- if (!y(a) || !y(p) || !U(a, p)) return H();
363
+ if (!D(a, p)) {
364
+ if (!f(a) || !f(p) || !V(a, p)) return B();
356
365
  for (let [e, t] of Object.entries(a)) {
357
366
  let n = p[e];
358
- if (P(t, n)) continue;
359
- if (!Array.isArray(t) || !Array.isArray(n) || t[0] !== n[0]) return H();
367
+ if (D(t, n)) continue;
368
+ if (!Array.isArray(t) || !Array.isArray(n) || t[0] !== n[0]) return B();
360
369
  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 H();
370
+ if (r === null || t.length !== r + 1 || n.length !== r + 1) return B();
362
371
  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(V, i[0]) || i[0] !== a[0] || !B(i[1]) || !B(a[1])) return H();
372
+ if (!Array.isArray(i) || !Array.isArray(a) || i.length !== 2 || a.length !== 2 || typeof i[0] != "number" || !Object.hasOwn(z, i[0]) || i[0] !== a[0] || !R(i[1]) || !R(a[1])) return B();
364
373
  let o = r === 2 ? t[1] : null;
365
- s.push(l(l({}, _), {}, {
374
+ s.push(I(I({}, _), {}, {
366
375
  kind: "input",
367
376
  name: e,
368
377
  connected: o,
@@ -376,15 +385,15 @@ function G(e, t) {
376
385
  }
377
386
  return s;
378
387
  }
379
- function K(e, t) {
388
+ function W(e, t) {
380
389
  let n = /* @__PURE__ */ new Set(), r = t.map((t) => {
381
390
  let r = e.filter((e) => e.isStage === t.stage && (t.stage || e.isOriginal && e.getName() === t.target));
382
- if (r.length !== 1) return H();
391
+ if (r.length !== 1) return B();
383
392
  let i = r[0], a = i.blocks, o = a.getBlock(t.id);
384
- if (!o || o.opcode !== t.opcode) return H();
393
+ if (!o || o.opcode !== t.opcode) return B();
385
394
  if (n.add(i), t.kind === "position") {
386
395
  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 ? H() : (e) => a.moveBlock({
396
+ 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 ? B() : (e) => a.moveBlock({
388
397
  id: t.id,
389
398
  newCoordinate: t[e]
390
399
  });
@@ -393,13 +402,13 @@ function K(e, t) {
393
402
  if (t.kind === "input") {
394
403
  var d;
395
404
  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 H();
397
- let r = a.getBlock(n), [i, s] = V[t.tag];
398
- if (!(r != null && r.shadow) || r.parent !== o.id || r.opcode !== i) return H();
405
+ if (!n || e.block !== ((d = t.connected) == null ? n : d)) return B();
406
+ let r = a.getBlock(n), [i, s] = z[t.tag];
407
+ if (!(r != null && r.shadow) || r.parent !== o.id || r.opcode !== i) return B();
399
408
  l = r, u = s;
400
409
  }
401
410
  let f = l.fields[u];
402
- return !f || f.id != null || f.value !== t.before || l.isMonitored || o.isMonitored ? H() : (e) => a.changeBlock({
411
+ return !f || f.id != null || f.value !== t.before || l.isMonitored || o.isMonitored ? B() : (e) => a.changeBlock({
403
412
  id: l.id,
404
413
  element: "field",
405
414
  name: u,
@@ -415,7 +424,7 @@ function K(e, t) {
415
424
  return [...n];
416
425
  }
417
426
  // src/script-reload.ts
418
- var q = ["targets"], re = ["targets"], ie = ["blocks"], ae = ["blocks"], J = (e = "Only changes to the scripts of existing targets can be reloaded in place") => v(e), oe = /* @__PURE__ */ new Set([
427
+ var G = ["targets"], K = ["targets"], se = ["blocks"], ce = ["blocks"], q = (e = "Only changes to the scripts of existing targets can be reloaded in place") => d(e), le = /* @__PURE__ */ new Set([
419
428
  "motion",
420
429
  "looks",
421
430
  "sound",
@@ -429,84 +438,84 @@ var q = ["targets"], re = ["targets"], ie = ["blocks"], ae = ["blocks"], J = (e
429
438
  "math",
430
439
  "text",
431
440
  "colour"
432
- ]), Y = (e) => e.split("_", 1)[0], se = /* @__PURE__ */ new Set([
441
+ ]), J = (e) => e.split("_", 1)[0], ue = /* @__PURE__ */ new Set([
433
442
  "VARIABLE",
434
443
  "LIST",
435
444
  "BROADCAST_OPTION"
436
- ]), ce = (e) => y(e) && typeof e.parent == "string" ? e.parent : null;
437
- function X(e) {
445
+ ]), de = (e) => f(e) && typeof e.parent == "string" ? e.parent : null;
446
+ function Y(e) {
438
447
  let t = /* @__PURE__ */ new Map();
439
448
  for (let n of Object.keys(e)) {
440
449
  let r = n, i = /* @__PURE__ */ new Set();
441
450
  for (;;) {
442
- if (i.has(r)) return J("Blocks form a cycle");
451
+ if (i.has(r)) return q("Blocks form a cycle");
443
452
  i.add(r);
444
- let t = ce(e[r]);
453
+ let t = de(e[r]);
445
454
  if (t === null) break;
446
- if (!Object.hasOwn(e, t)) return J("A block refers to a missing parent");
455
+ if (!Object.hasOwn(e, t)) return q("A block refers to a missing parent");
447
456
  r = t;
448
457
  }
449
458
  t.set(n, r);
450
459
  }
451
460
  return t;
452
461
  }
453
- function le(e, t) {
454
- for (let n of Object.values(e)) y(n) && typeof n.opcode == "string" && t.add(Y(n.opcode));
462
+ function fe(e, t) {
463
+ for (let n of Object.values(e)) f(n) && typeof n.opcode == "string" && t.add(J(n.opcode));
455
464
  }
456
- function ue(e, t) {
457
- let { targets: n } = e, i = r(e, q), { targets: a } = t, o = r(t, re);
458
- if (n.length !== a.length || !P(i, o)) return J();
459
- let s = new Set(oe);
460
- for (let e of n) y(e.blocks) && le(e.blocks, s);
465
+ function pe(e, t) {
466
+ let { targets: n } = e, i = r(e, G), { targets: a } = t, o = r(t, K);
467
+ if (n.length !== a.length || !D(i, o)) return q();
468
+ let s = new Set(le);
469
+ for (let e of n) f(e.blocks) && fe(e.blocks, s);
461
470
  let c = [];
462
471
  for (let [e, t] of n.entries()) {
463
- let { blocks: n } = t, i = r(t, ie), o = a[e], { blocks: l } = o;
464
- if (!P(i, r(o, ae))) return J();
465
- if (P(n, l)) continue;
466
- let u = y(n) ? n : {}, d = y(l) ? l : {}, f = X(u), p = X(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;
472
+ let { blocks: n } = t, i = r(t, se), o = a[e], { blocks: l } = o;
473
+ if (!D(i, r(o, ce))) return q();
474
+ if (D(n, l)) continue;
475
+ let u = f(n) ? n : {}, d = f(l) ? l : {}, p = Y(u), m = Y(d), h = /* @__PURE__ */ new Set(), g = /* @__PURE__ */ new Set(), _ = (e) => {
476
+ let t = p.get(e), n = m.get(e), r = !1;
477
+ return t !== void 0 && !h.has(t) && (h.add(t), r = !0), n !== void 0 && !g.has(n) && (g.add(n), r = !0), r;
469
478
  };
470
- for (let e of /* @__PURE__ */ new Set([...Object.keys(u), ...Object.keys(d)])) P(u[e], d[e]) || g(e);
479
+ for (let e of /* @__PURE__ */ new Set([...Object.keys(u), ...Object.keys(d)])) D(u[e], d[e]) || _(e);
471
480
  for (let e = !0; e;) {
472
481
  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);
482
+ for (let [t, n] of p) h.has(n) && _(t) && (e = !0);
483
+ for (let [t, n] of m) g.has(n) && _(t) && (e = !0);
475
484
  }
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 J("A block has no opcode");
480
- if (!s.has(Y(e.opcode))) return J(`Blocks need an extension the project does not use: ${e.opcode}`);
485
+ let v = {};
486
+ for (let [e, t] of m) g.has(t) && (v[e] = d[e]);
487
+ for (let e of Object.values(v)) if (f(e)) {
488
+ if (typeof e.opcode != "string") return q("A block has no opcode");
489
+ if (!s.has(J(e.opcode))) return q(`Blocks need an extension the project does not use: ${e.opcode}`);
481
490
  }
482
491
  c.push({
483
492
  target: t.name,
484
493
  stage: t.isStage,
485
- remove: [...m],
486
- blocks: _
494
+ remove: [...h],
495
+ blocks: v
487
496
  });
488
497
  }
489
498
  return c;
490
499
  }
491
- var de = (e, t) => {
500
+ var me = (e, t) => {
492
501
  let n = e.filter((e) => e.isStage === t.stage && (t.stage || e.isOriginal && e.getName() === t.target));
493
- return n.length === 1 ? n[0] : J();
502
+ return n.length === 1 ? n[0] : q();
494
503
  };
495
- function fe(e, t, n) {
504
+ function he(e, t, n) {
496
505
  let r = t.map((t) => {
497
- let r = de(e, t), i = r.blocks;
506
+ let r = me(e, t), i = r.blocks;
498
507
  for (let e of t.remove) {
499
508
  let t = i.getBlock(e);
500
- if (!t || !t.topLevel || !i._scripts.includes(e)) return J("The editor and the folder differ");
509
+ if (!t || !t.topLevel || !i._scripts.includes(e)) return q("The editor and the folder differ");
501
510
  }
502
511
  let a = Object.values(n(JSON.parse(JSON.stringify(t.blocks))));
503
512
  for (let e of a) {
504
513
  var o;
505
- if (typeof e.id != "string" || typeof e.opcode != "string") return J("A block could not be read");
506
- if (e.comment && !(r.comments && Object.hasOwn(r.comments, e.comment))) return J("A block refers to a missing comment");
514
+ if (typeof e.id != "string" || typeof e.opcode != "string") return q("A block could not be read");
515
+ if (e.comment && !(r.comments && Object.hasOwn(r.comments, e.comment))) return q("A block refers to a missing comment");
507
516
  for (let [t, n] of Object.entries((o = e.fields) == null ? {} : o)) {
508
517
  var s;
509
- if ((se.has(t) || n.variableType) && (typeof n.id != "string" || !((s = r.lookupVariableById) != null && s.call(r, n.id)))) return J("A block refers to a variable, list or message the project does not have");
518
+ if ((ue.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
519
  }
511
520
  }
512
521
  return {
@@ -517,14 +526,14 @@ function fe(e, t, n) {
517
526
  };
518
527
  }), i = r.map(({ container: e }) => ({
519
528
  container: e,
520
- blocks: l({}, e._blocks),
529
+ blocks: I({}, e._blocks),
521
530
  scripts: [...e._scripts],
522
531
  tops: new Map(Object.entries(e._blocks).map(([e, t]) => [e, t.topLevel]))
523
532
  }));
524
533
  try {
525
534
  for (let { container: e, edit: t, created: n } of r) {
526
535
  for (let n of t.remove) e.deleteBlock(n);
527
- for (let t of n) e.createBlock(t, !0), e._blocks[t.id] !== t && J("A block id is already in use");
536
+ for (let t of n) e.createBlock(t, !0), e._blocks[t.id] !== t && q("A block id is already in use");
528
537
  e.resetCache();
529
538
  }
530
539
  } catch (e) {
@@ -538,39 +547,39 @@ function fe(e, t, n) {
538
547
  return r.map(({ target: e }) => e);
539
548
  }
540
549
  // src/session.ts
541
- var Z = /* @__PURE__ */ new WeakMap(), pe = (e) => {
542
- let t = Z.get(e);
550
+ var X = /* @__PURE__ */ new WeakMap(), Z = (e) => {
551
+ let t = X.get(e);
543
552
  if (t) return t;
544
553
  let n = { assets: null };
545
554
  return e.addHelper({ load(e, t, r) {
546
555
  var i;
547
- let a = (i = n.assets) == null ? void 0 : i.get(k(e, t, r));
556
+ let a = (i = n.assets) == null ? void 0 : i.get(S(e, t, r));
548
557
  return a ? Promise.resolve(a) : null;
549
- } }, 101), Z.set(e, n), n;
558
+ } }, 101), X.set(e, n), n;
550
559
  };
551
- function me(e, t) {
552
- let n = null, r = !1, i = !1, a = 0, o = null, s = () => S(e.toJSON(void 0, { allowOptimization: !1 })), c = () => {
560
+ function ge(e, t) {
561
+ let n = null, r = !1, i = !1, a = 0, o = null, c = () => h(e.toJSON(void 0, { allowOptimization: !1 })), l = () => {
553
562
  a++;
554
- }, u = () => {
563
+ }, d = () => {
555
564
  n = null;
556
565
  };
557
- e.runtime.on("PROJECT_LOADED", u), e.on("PROJECT_CHANGED", c);
558
- let d = (t) => {
559
- if (i || n !== t || e.runtime.getTargetForStage() !== t.stage) throw new _("conflict");
560
- }, f = () => {
561
- i = !0, n = null, e.runtime.off("PROJECT_LOADED", u), e.off("PROJECT_CHANGED", c);
562
- }, p = async (a, o) => {
566
+ e.runtime.on("PROJECT_LOADED", d), e.on("PROJECT_CHANGED", l);
567
+ let f = (t) => {
568
+ if (i || n !== t || e.runtime.getTargetForStage() !== t.stage) throw new u("conflict");
569
+ }, p = () => {
570
+ i = !0, n = null, e.runtime.off("PROJECT_LOADED", d), e.off("PROJECT_CHANGED", l);
571
+ }, m = async (a, o) => {
563
572
  if (i || r) return "cancelled";
564
573
  r = !0;
565
- let c = e.runtime.getTargetForStage();
574
+ let s = e.runtime.getTargetForStage();
566
575
  try {
567
576
  var l;
568
577
  let r = await a();
569
578
  if (!r || i) return "cancelled";
570
- let u = e.runtime.storage, d = await A(r, u);
571
- if (i || e.runtime.getTargetForStage() !== c || t.isProjectDirty() && !o()) return "cancelled";
579
+ let u = e.runtime.storage, d = await C(r, u);
580
+ if (i || e.runtime.getTargetForStage() !== s || t.isProjectDirty() && !o()) return "cancelled";
572
581
  t.beforeLoad(), n = null;
573
- let f = pe(u), p = d.storageAssets;
582
+ let f = Z(u), p = d.storageAssets;
574
583
  f.assets = p;
575
584
  let m;
576
585
  try {
@@ -581,38 +590,38 @@ function me(e, t) {
581
590
  return i || !m || e.runtime.getTargetForStage() !== m ? "cancelled" : (t.onOpened(r.name), n = {
582
591
  source: d,
583
592
  stage: m,
584
- baseline: s(),
593
+ baseline: c(),
585
594
  pending: null
586
595
  }, (l = e.renderer) == null || l.draw(), "opened");
587
596
  } finally {
588
597
  r = !1;
589
598
  }
590
- }, h = (e, n) => {
599
+ }, g = (e, n) => {
591
600
  var r;
592
601
  try {
593
602
  return {
594
603
  kind: "values",
595
- changes: G(e, n)
604
+ changes: U(e, n)
596
605
  };
597
606
  } catch (e) {
598
- if (!(e instanceof _)) throw e;
607
+ if (!(e instanceof u)) throw e;
599
608
  }
600
609
  if (!((r = t.blockReload) != null && r.deserializeBlocks)) return null;
601
610
  try {
602
611
  return {
603
612
  kind: "scripts",
604
- changes: ue(e, n)
613
+ changes: pe(e, n)
605
614
  };
606
615
  } catch (e) {
607
- if (!(e instanceof _)) throw e;
616
+ if (!(e instanceof u)) throw e;
608
617
  return null;
609
618
  }
610
- }, g = async (e) => {
619
+ }, _ = async (e) => {
611
620
  var t;
612
- let n = typeof e.pending == "object" ? e.pending : null, r = await M(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 }) : {
621
+ let n = typeof e.pending == "object" ? e.pending : null, r = await T(e.source, (t = n == null ? void 0 : n.update) == null ? null : t);
622
+ return !r || typeof r == "string" ? r : (n == null ? void 0 : n.update) === r ? I(I({}, n), {}, { stable: !0 }) : {
614
623
  update: r,
615
- edits: h(e.source.project, r.project),
624
+ edits: g(e.source.project, r.project),
616
625
  stable: !1
617
626
  };
618
627
  }, v = () => {
@@ -661,17 +670,17 @@ function me(e, t) {
661
670
  async comparison() {
662
671
  let e = n;
663
672
  if (!e) return null;
664
- let t = new TextDecoder(), r = t.decode(e.source.files.get(m)), i;
673
+ let t = new TextDecoder(), r = t.decode(e.source.files.get(s)), i;
665
674
  try {
666
- let t = I(e.source.project, e.baseline, s());
675
+ let t = M(e.source.project, e.baseline, c());
667
676
  i = t ? `${JSON.stringify(t, null, 2)}\n` : r;
668
677
  } catch (e) {
669
- if (!(e instanceof _)) throw e;
678
+ if (!(e instanceof u)) throw e;
670
679
  i = null;
671
680
  }
672
681
  let a;
673
682
  try {
674
- let n = await (await e.source.directory.getFileHandle(m)).getFile();
683
+ let n = await (await e.source.directory.getFileHandle(s)).getFile();
675
684
  a = t.decode(new Uint8Array(await n.arrayBuffer()));
676
685
  } catch (e) {
677
686
  a = null;
@@ -686,7 +695,7 @@ function me(e, t) {
686
695
  if (i || r || !n || !t.blockReload) return Promise.resolve();
687
696
  if (o) return o;
688
697
  let e = n, a = e.baseline;
689
- return o = g(e).then((t) => {
698
+ return o = _(e).then((t) => {
690
699
  n === e && e.baseline === a && !r && (e.pending = t);
691
700
  }).finally(() => {
692
701
  o = null;
@@ -695,19 +704,19 @@ function me(e, t) {
695
704
  async reload() {
696
705
  if (!n || y() !== "ready" || !t.blockReload) return !1;
697
706
  let o = n;
698
- d(o), r = !0;
707
+ f(o), r = !0;
699
708
  try {
700
- let r = a, d = await g(o);
709
+ let r = a, d = await _(o);
701
710
  if (n !== o || i || e.runtime.getTargetForStage() !== o.stage || (o.pending = d, !d || typeof d == "string" || d.edits === null || r !== a || !b())) return !1;
702
711
  let f;
703
712
  try {
704
- var c, u;
713
+ var l, u;
705
714
  let { edits: n } = d;
706
- f = n.kind === "values" ? K((c = e.runtime.targets) == null ? [] : c, n.changes) : fe((u = e.runtime.targets) == null ? [] : u, n.changes, t.blockReload.deserializeBlocks);
715
+ f = n.kind === "values" ? W((l = e.runtime.targets) == null ? [] : l, n.changes) : he((u = e.runtime.targets) == null ? [] : u, n.changes, t.blockReload.deserializeBlocks);
707
716
  } catch (e) {
708
- throw o.pending = l(l({}, d), {}, { edits: null }), e;
717
+ throw o.pending = I(I({}, d), {}, { edits: null }), e;
709
718
  }
710
- 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;
719
+ return o.baseline = c(), o.source.project = d.update.project, o.source.files.set(s, d.update.bytes), o.source.versions.set(s, d.update.version), o.pending = null, t.blockReload.onApplied(f), !0;
711
720
  } finally {
712
721
  r = !1;
713
722
  }
@@ -715,10 +724,10 @@ function me(e, t) {
715
724
  reloadAll(e) {
716
725
  var r;
717
726
  let i = n;
718
- return !i || !i.pending || i.pending === "waiting" || (r = t.blockReload) != null && r.isRunning() ? Promise.resolve("cancelled") : p(() => Promise.resolve(n === i ? i.source.directory : null), e);
727
+ return !i || !i.pending || i.pending === "waiting" || (r = t.blockReload) != null && r.isRunning() ? Promise.resolve("cancelled") : m(() => Promise.resolve(n === i ? i.source.directory : null), e);
719
728
  },
720
729
  open(e, t) {
721
- return p(async () => {
730
+ return m(async () => {
722
731
  try {
723
732
  return await e({
724
733
  id: "turbowarp-plus-project-folder",
@@ -731,27 +740,27 @@ function me(e, t) {
731
740
  }, t);
732
741
  },
733
742
  openDirectory(e, t) {
734
- return p(() => Promise.resolve(e), t);
743
+ return m(() => Promise.resolve(e), t);
735
744
  },
736
745
  async save() {
737
- if (!n || r) throw new _("conflict");
746
+ if (!n || r) throw new u("conflict");
738
747
  let e = n;
739
- d(e), r = !0;
748
+ f(e), r = !0;
740
749
  try {
741
- let r = a, i = s(), o = I(e.source.project, e.baseline, i);
742
- if (await N(e.source), d(e), !o) return a === r && t.onSaved(), "unchanged";
743
- let c = `${JSON.stringify(o, null, 2)}\n`, l = await (await e.source.directory.getFileHandle(m)).createWritable({ mode: "exclusive" });
750
+ let r = a, i = c(), o = M(e.source.project, e.baseline, i);
751
+ if (await E(e.source), f(e), !o) return a === r && t.onSaved(), "unchanged";
752
+ let l = `${JSON.stringify(o, null, 2)}\n`, u = await (await e.source.directory.getFileHandle(s)).createWritable({ mode: "exclusive" });
744
753
  try {
745
- await l.write(c), await N(e.source), d(e), await l.close();
754
+ await u.write(l), await E(e.source), f(e), await u.close();
746
755
  } catch (e) {
747
- throw await l.abort().catch(() => {}), e;
756
+ throw await u.abort().catch(() => {}), e;
748
757
  }
749
- return e.source.project = o, e.source.files.set(m, new TextEncoder().encode(c)), e.source.versions.delete(m), e.baseline = i, e.pending = null, n === e && a === r && t.onSaved(), "saved";
758
+ return e.source.project = o, e.source.files.set(s, new TextEncoder().encode(l)), e.source.versions.delete(s), e.baseline = i, e.pending = null, n === e && a === r && t.onSaved(), "saved";
750
759
  } finally {
751
760
  r = !1;
752
761
  }
753
762
  },
754
- dispose: f
763
+ dispose: p
755
764
  };
756
765
  }
757
766
  // src/index.ts
@@ -764,7 +773,7 @@ var Q = {
764
773
  saved: "Project folder saved.",
765
774
  unchanged: "No changes to save.",
766
775
  conflict: "The project folder changed outside the editor or is no longer open. Your edits are still in the editor.",
767
- unsupported: "This project or edit is outside the folder prototype scope.",
776
+ unsupported: "This project or edit cannot be saved to a project folder yet.",
768
777
  failed: "Could not access the project folder.",
769
778
  external: "External changes detected.",
770
779
  reload: "Reload from Disk",
@@ -796,7 +805,7 @@ var Q = {
796
805
  saved: "プロジェクトフォルダに保存しました。",
797
806
  unchanged: "保存する変更はありません。",
798
807
  conflict: "外部でフォルダが変更されたか、作品が切り替わりました。編集中の変更はエディターに残っています。",
799
- unsupported: "この作品または編集はフォルダ編集の試作対象外です。",
808
+ unsupported: "この作品または編集は、まだプロジェクトフォルダに保存できません。",
800
809
  failed: "プロジェクトフォルダにアクセスできませんでした。",
801
810
  external: "外部変更あり",
802
811
  reload: "ディスクから再読み込み",
@@ -821,11 +830,11 @@ var Q = {
821
830
  full: "この変更は作品全体の再読み込みが必要です。"
822
831
  }
823
832
  }, $ = /* @__PURE__ */ new WeakMap();
824
- function he({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0 }) {
833
+ function _e({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0 }) {
825
834
  var a;
826
835
  let o = t.defaultView, s = o == null ? void 0 : o.showDirectoryPicker;
827
836
  if (!s || !((a = e.runtime) != null && a.storage)) return null;
828
- let c = me(e, n), l = t.createElement("output");
837
+ let c = ge(e, n), l = t.createElement("output");
829
838
  l.dataset.projectFolderStatus = "", l.setAttribute("role", "status"), l.hidden = !0, Object.assign(l.style, {
830
839
  position: "fixed",
831
840
  insetInlineEnd: "1rem",
@@ -838,17 +847,17 @@ function he({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
838
847
  border: "1px solid currentColor",
839
848
  borderRadius: "0.4rem"
840
849
  }), t.body.append(l);
841
- let u, d = (e) => {
842
- l.isConnected && (l.hidden = !1, l.textContent = e, o.clearTimeout(u), u = o.setTimeout(() => {
850
+ let d, f = (e) => {
851
+ l.isConnected && (l.hidden = !1, l.textContent = e, o.clearTimeout(d), d = o.setTimeout(() => {
843
852
  l.hidden = !0;
844
853
  }, 7500));
845
- }, f = (e) => e.startsWith("ja") ? Q.ja : Q.en, p = (e, t) => {
846
- let n = f(e), r = t instanceof _ && t.message !== t.code ? ` (${t.message})` : "";
847
- d((t instanceof _ ? n[t.code] : n.failed) + r);
848
- }, m, h = () => {};
854
+ }, p = (e) => e.startsWith("ja") ? Q.ja : Q.en, m = (e, t) => {
855
+ let n = p(e), r = t instanceof u && t.message !== t.code ? ` (${t.message})` : "";
856
+ f((t instanceof u ? n[t.code] : n.failed) + r);
857
+ }, h, g = () => {};
849
858
  if (n.blockReload) {
850
- var g;
851
- let e = f(r), a = t.createElement("aside");
859
+ var _;
860
+ let e = p(r), a = t.createElement("aside");
852
861
  a.dataset.projectFolderExternal = "", a.hidden = !0, Object.assign(a.style, {
853
862
  position: "fixed",
854
863
  insetInlineEnd: "1rem",
@@ -865,9 +874,9 @@ function he({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
865
874
  s.setAttribute("role", "status");
866
875
  let l = t.createElement("button");
867
876
  l.type = "button", l.textContent = e.reload, a.append(s, l), t.body.append(a);
868
- let u = (g = n.blockReload.compareChanges) == null ? void 0 : g.bind(n.blockReload), _ = !1, v = async (t) => {
869
- if (!_) {
870
- _ = !0;
877
+ let u = (_ = n.blockReload.compareChanges) == null ? void 0 : _.bind(n.blockReload), d = !1, v = async (t) => {
878
+ if (!d) {
879
+ d = !0;
871
880
  try {
872
881
  let n = await c.comparison();
873
882
  if (!n) return;
@@ -895,18 +904,18 @@ function he({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
895
904
  closeLabel: e.close
896
905
  }) === "discard" && c.reloadState === "dirty" && C(() => c.reloadAll(() => !0));
897
906
  } catch (e) {
898
- p(r, e);
907
+ m(r, e);
899
908
  } finally {
900
- _ = !1, h();
909
+ d = !1, g();
901
910
  }
902
911
  }
903
912
  }, y, b = null, x = null, S = null, C = (t) => {
904
913
  let n = t();
905
- h(), n.then((t) => {
906
- (t === !0 || t === "opened") && d(e.reloaded);
907
- }, (e) => p(r, e)).finally(h);
914
+ g(), n.then((t) => {
915
+ (t === !0 || t === "opened") && f(e.reloaded);
916
+ }, (e) => m(r, e)).finally(g);
908
917
  };
909
- h = () => {
918
+ g = () => {
910
919
  let t = c.reloadState, n = c.reloadKind;
911
920
  if (i && c.canAutoReload && c.pendingVersion !== b) {
912
921
  b = c.pendingVersion, C(() => c.reload());
@@ -926,8 +935,8 @@ function he({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
926
935
  };
927
936
  let w = () => {
928
937
  t.visibilityState === "visible" && c.refresh().then(() => {
929
- h(), c.settling && T(500);
930
- }, (e) => p(r, e));
938
+ g(), c.settling && T(500);
939
+ }, (e) => m(r, e));
931
940
  }, T = (e) => {
932
941
  o.clearTimeout(y), y = o.setTimeout(w, e);
933
942
  };
@@ -940,30 +949,30 @@ function he({ vm: e, document: t, host: n, locale: r = "en", autoReload: i = !0
940
949
  let t = c.reloadState;
941
950
  t === "ready" ? C(() => c.reload()) : t === "full" ? C(() => c.reloadAll(() => !0)) : t === "dirty" && u ? v(u) : t === "dirty" && C(() => c.reloadAll(() => o.confirm(e.discardConfirm)));
942
951
  });
943
- let E = n.blockReload.subscribe(h), D = o.setInterval(w, 2e3);
944
- o.addEventListener("focus", w), t.addEventListener("visibilitychange", w), m = () => {
952
+ let E = n.blockReload.subscribe(g), D = o.setInterval(w, 2e3);
953
+ o.addEventListener("focus", w), t.addEventListener("visibilitychange", w), h = () => {
945
954
  E(), o.clearInterval(D), o.clearTimeout(y), S == null || S.disconnect(), o.removeEventListener("focus", w), t.removeEventListener("visibilitychange", w), a.remove();
946
955
  };
947
956
  }
948
957
  return $.set(e, {
949
958
  session: c,
950
959
  open(e) {
951
- let t = f(e);
960
+ let t = p(e);
952
961
  c.open((e) => s.call(o, e), () => o.confirm(t.replace)).then((e) => {
953
- e === "opened" && d(t.opened);
954
- }, (t) => p(e, t)).finally(h), h();
962
+ e === "opened" && f(t.opened);
963
+ }, (t) => m(e, t)).finally(g), g();
955
964
  },
956
965
  save(e) {
957
- c.busy || (c.save().then((t) => d(f(e)[t]), (t) => p(e, t)).finally(h), h());
966
+ c.busy || (c.save().then((t) => f(p(e)[t]), (t) => m(e, t)).finally(g), g());
958
967
  }
959
968
  }), {
960
- openDirectory: (...e) => c.openDirectory(...e).finally(h),
969
+ openDirectory: (...e) => c.openDirectory(...e).finally(g),
961
970
  dispose() {
962
- $.delete(e), c.dispose(), m == null || m(), o.clearTimeout(u), l.remove();
971
+ $.delete(e), c.dispose(), h == null || h(), o.clearTimeout(d), l.remove();
963
972
  }
964
973
  };
965
974
  }
966
- function ge(e, t = "en") {
975
+ function ve(e, t = "en") {
967
976
  let n = $.get(e);
968
977
  if (n) return {
969
978
  open: () => n.open(t),
@@ -971,7 +980,7 @@ function ge(e, t = "en") {
971
980
  detach: () => n.session.detach()
972
981
  };
973
982
  }
974
- function _e(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequestClose: a }) {
983
+ function ye(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequestClose: a }) {
975
984
  let o = $.get(t);
976
985
  if (!o) return null;
977
986
  let s = n.startsWith("ja") ? Q.ja : Q.en, c = (t) => {
@@ -991,4 +1000,4 @@ function _e(e, { vm: t, locale: n = "en", MenuItem: r, MenuSection: i, onRequest
991
1000
  };
992
1001
  return e(i, null, c("open"), o.session.canSave ? c("save") : null);
993
1002
  }
994
- export { he as mountProjectFolder, ge as projectFolderActions, _e as renderProjectFolderMenu };
1003
+ export { _e as mountProjectFolder, ve as projectFolderActions, ye as renderProjectFolderMenu };
package/dist/source.d.ts CHANGED
@@ -60,5 +60,10 @@ export type DiskChange = FolderUpdate | 'structure' | 'waiting' | null;
60
60
  export declare function readFolderUpdate(source: FolderSource, previous: FolderUpdate | null): Promise<DiskChange>;
61
61
  export declare function assertFolderUnchanged(source: FolderSource): Promise<void>;
62
62
  export declare const equal: (left: Json | undefined, right: Json | undefined) => boolean;
63
+ /**
64
+ * Applies the edits between `before` and `after` (both from the VM) to the project read from the folder, keeping the
65
+ * fields and order the VM does not know. Saves change only the project file: the stage and sprites keep their names,
66
+ * and the costumes and sounds keep using the asset files already in the folder. Returns `null` without edits.
67
+ */
63
68
  export declare function projectChanges(source: Project, before: Project, after: Project): Project | null;
64
69
  export {};
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.4.0",
3
+ "version": "0.5.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",
package/src/index.ts CHANGED
@@ -12,7 +12,7 @@ const messages = {
12
12
  replace: 'Replace the open project and discard its unsaved changes?',
13
13
  opened: 'Project folder opened.', saved: 'Project folder saved.', unchanged: 'No changes to save.',
14
14
  conflict: 'The project folder changed outside the editor or is no longer open. Your edits are still in the editor.',
15
- unsupported: 'This project or edit is outside the folder prototype scope.',
15
+ unsupported: 'This project or edit cannot be saved to a project folder yet.',
16
16
  failed: 'Could not access the project folder.',
17
17
  external: 'External changes detected.', reload: 'Reload from Disk', reloaded: 'Changes loaded from disk.',
18
18
  reloadAll: 'Reload Whole Project', discard: 'Discard Edits and Reload…',
@@ -32,7 +32,7 @@ const messages = {
32
32
  replace: '未保存の変更を破棄して、別の作品を開きますか?',
33
33
  opened: 'プロジェクトフォルダを開きました。', saved: 'プロジェクトフォルダに保存しました。', unchanged: '保存する変更はありません。',
34
34
  conflict: '外部でフォルダが変更されたか、作品が切り替わりました。編集中の変更はエディターに残っています。',
35
- unsupported: 'この作品または編集はフォルダ編集の試作対象外です。',
35
+ unsupported: 'この作品または編集は、まだプロジェクトフォルダに保存できません。',
36
36
  failed: 'プロジェクトフォルダにアクセスできませんでした。',
37
37
  external: '外部変更あり', reload: 'ディスクから再読み込み', reloaded: 'ディスクの変更を読み込みました。',
38
38
  reloadAll: '作品全体を再読み込み', discard: '編集を破棄して再読み込み…',
package/src/source.ts CHANGED
@@ -102,7 +102,7 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
102
102
  (embedded.extensionBundles !== undefined && (!Array.isArray(embedded.extensionBundles) || embedded.extensionBundles.length)) ||
103
103
  project.turboWarpPlus !== undefined || project.customFonts !== undefined ||
104
104
  (project.extensionURLs !== undefined && (!isObject(project.extensionURLs) || Object.keys(project.extensionURLs).length))) {
105
- return unsupported('Custom extensions and fonts are outside the prototype scope');
105
+ return unsupported('Custom extensions and fonts are not supported in project folders');
106
106
  }
107
107
  const expected = new Set(['project.json']);
108
108
  const references = new Map<string, {id: string; format: string; type: AssetType; name: string}>();
@@ -210,8 +210,17 @@ export const equal = (left: Json | undefined, right: Json | undefined): boolean
210
210
  keys.every(key => Object.hasOwn(right, key) && equal(left[key], right[key]));
211
211
  };
212
212
 
213
+ // Items that name themselves (monitors, costumes) must be the same item in the folder and in the Editor.
214
+ const sameIdentity = (left: Json, right: Json) => !isObject(left) || !isObject(right) ||
215
+ ['id', 'assetId', 'name', 'opcode'].every(key => !Object.hasOwn(left, key) || !Object.hasOwn(right, key) || equal(left[key], right[key]));
213
216
  const applyChanges = (source: Json | undefined, before: Json, after: Json): Json => {
214
217
  if (equal(before, after)) return source === undefined ? after : source;
218
+ // Lists of the same length, such as costumes or a block input, change item by item to keep unknown fields.
219
+ if (Array.isArray(before) && Array.isArray(after) && Array.isArray(source) &&
220
+ before.length === after.length && source.length === after.length &&
221
+ source.every((item, index) => sameIdentity(item, before[index]))) {
222
+ return after.map((item, index) => applyChanges(source[index], before[index], item));
223
+ }
215
224
  if (!isObject(before) || !isObject(after)) return after;
216
225
  const result: JsonObject = Object.assign(Object.create(null), isObject(source) ? source : {});
217
226
  for (const key of Object.keys(before)) {
@@ -226,31 +235,58 @@ const applyChanges = (source: Json | undefined, before: Json, after: Json): Json
226
235
  return result;
227
236
  };
228
237
 
238
+ const assetNames = (project: Project) => {
239
+ const names = new Set<string>();
240
+ for (const target of project.targets) {
241
+ for (const kind of ['costumes', 'sounds'] as const) {
242
+ const entries = target[kind];
243
+ if (!Array.isArray(entries)) continue;
244
+ for (const entry of entries) if (isObject(entry) && typeof entry.md5ext === 'string') names.add(entry.md5ext);
245
+ }
246
+ }
247
+ return names;
248
+ };
249
+ const customContent = (project: Project) => project.turboWarpPlus !== undefined || project.customFonts !== undefined ||
250
+ (project.extensionURLs !== undefined && (!isObject(project.extensionURLs) || Object.keys(project.extensionURLs).length > 0));
251
+
252
+ /**
253
+ * Applies the edits between `before` and `after` (both from the VM) to the project read from the folder, keeping the
254
+ * fields and order the VM does not know. Saves change only the project file: the stage and sprites keep their names,
255
+ * and the costumes and sounds keep using the asset files already in the folder. Returns `null` without edits.
256
+ */
229
257
  export function projectChanges(source: Project, before: Project, after: Project): Project | null {
258
+ const keys = (project: Project) => project.targets.map(targetKey);
259
+ const beforeKeys = keys(before), afterKeys = keys(after);
260
+ if (beforeKeys.length !== afterKeys.length || !afterKeys.every(key => beforeKeys.includes(key))) {
261
+ return unsupported('Adding, removing or renaming sprites is not saved to a project folder yet');
262
+ }
263
+ const used = assetNames(after), known = assetNames(before);
264
+ if (used.size !== known.size || [...used].some(name => !known.has(name))) {
265
+ return unsupported('Adding or removing costumes and sounds is not saved to a project folder yet');
266
+ }
267
+ if (customContent(after)) return unsupported('Custom extensions and fonts are not saved to a project folder');
268
+ if (equal(before, after)) return null;
269
+ const {targets: sourceTargets, ...sourceOther} = source;
230
270
  const {targets: beforeTargets, ...beforeOther} = before;
231
271
  const {targets: afterTargets, ...afterOther} = after;
232
- if (!equal(beforeOther, afterOther) || !equal(beforeTargets.map(targetKey), afterTargets.map(targetKey))) {
233
- return unsupported('This prototype saves block edits on existing targets only');
234
- }
235
- const edits = new Map<string, Partial<Pick<Target, 'blocks' | 'comments'>>>();
236
- const originalTargets = new Map(source.targets.map(target => [targetKey(target), target]));
237
- for (const [index, target] of afterTargets.entries()) {
238
- const {blocks, comments, ...rest} = target;
239
- const {blocks: priorBlocks, comments: priorComments, ...priorRest} = beforeTargets[index];
240
- if (!equal(rest, priorRest)) return unsupported('This prototype saves block edits on existing targets only');
272
+ const originals = new Map(sourceTargets.map(target => [targetKey(target), target]));
273
+ const previous = new Map(beforeTargets.map(target => [targetKey(target), target]));
274
+ const targets = afterTargets.map(target => {
241
275
  const key = targetKey(target);
242
- const original = originalTargets.get(key);
276
+ const original = originals.get(key);
243
277
  if (!original) return unsupported('The original target could not be identified');
244
- if (!equal(priorBlocks, blocks) || !equal(priorComments, comments)) {
245
- const changes: Partial<Pick<Target, 'blocks' | 'comments'>> = {};
246
- if (!equal(priorBlocks, blocks)) changes.blocks = applyChanges(original.blocks, priorBlocks, blocks);
247
- if (!equal(priorComments, comments)) changes.comments = applyChanges(original.comments, priorComments, comments);
248
- edits.set(key, changes);
249
- }
278
+ return applyChanges(original, previous.get(key)!, target) as Target;
279
+ });
280
+ // The folder keeps its own target order unless the Editor reordered the sprites.
281
+ const order = equal(beforeKeys, afterKeys) ? sourceTargets.map(targetKey) : afterKeys;
282
+ const byKey = new Map(targets.map(target => [targetKey(target), target]));
283
+ const other = applyChanges(sourceOther, beforeOther, afterOther) as JsonObject;
284
+ // Keep the folder's key order, with the targets where they were.
285
+ const result: JsonObject = {};
286
+ for (const key of Object.keys(source)) {
287
+ if (key === 'targets') result.targets = order.map(key => byKey.get(key)!);
288
+ else if (Object.hasOwn(other, key)) result[key] = other[key];
250
289
  }
251
- if (!edits.size) return null;
252
- return {...source, targets: source.targets.map(target => {
253
- const edit = edits.get(targetKey(target));
254
- return edit ? {...target, ...edit} : target;
255
- })};
290
+ for (const key of Object.keys(other)) if (!Object.hasOwn(result, key)) result[key] = other[key];
291
+ return result as Project;
256
292
  }