@kubohiroya/turbowarp-plus-editor-project-folder 0.10.0 → 0.12.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.
@@ -1,44 +1,6 @@
1
- // \0@oxc-project+runtime@0.156.0/helpers/esm/asyncIterator.js
2
- function _asyncIterator(r) {
3
- var n, t, o, e = 2;
4
- for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
5
- if (t && null != (n = r[t])) return n.call(r);
6
- if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
7
- t = "@@asyncIterator", o = "@@iterator";
8
- }
9
- throw new TypeError("Object is not async iterable");
10
- }
11
- function AsyncFromSyncIterator(r) {
12
- function AsyncFromSyncIteratorContinuation(r) {
13
- if (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + " is not an object."));
14
- var n = r.done;
15
- return Promise.resolve(r.value).then(function(r) {
16
- return {
17
- value: r,
18
- done: n
19
- };
20
- });
21
- }
22
- return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {
23
- this.s = r, this.n = r.next;
24
- }, AsyncFromSyncIterator.prototype = {
25
- s: null,
26
- n: null,
27
- next: function next() {
28
- return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
29
- },
30
- "return": function _return(r) {
31
- var n = this.s["return"];
32
- return void 0 === n ? Promise.resolve({
33
- value: r,
34
- done: !0
35
- }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
36
- },
37
- "throw": function _throw(r) {
38
- var n = this.s["throw"];
39
- return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
40
- }
41
- }, new AsyncFromSyncIterator(r);
1
+ // node_modules/@kubohiroya/sb3-toolchain/dist/assert.js
2
+ function assert(condition, message) {
3
+ if (!condition) throw new Error(message);
42
4
  }
43
5
  // \0@oxc-project+runtime@0.156.0/helpers/esm/typeof.js
44
6
  function _typeof(o) {
@@ -96,6 +58,283 @@ function _objectSpread2(e) {
96
58
  }
97
59
  return e;
98
60
  }
61
+ // node_modules/@kubohiroya/sb3-toolchain/dist/block-palette.js
62
+ var blockPaletteFile = "block-palette.json";
63
+ var blockPaletteCommentMarker = " // _twplus_palette_";
64
+ var blockPaletteCommentReference = `block-palette:${blockPaletteFile}`;
65
+ var blockPaletteCommentMaxLength = 8e3;
66
+ var blockPaletteSpriteCommentHeader = "TurboWarp Plus Editor block palette for this sprite. You can delete this comment to reset the palette.";
67
+ var blockPaletteStageCommentHeader = "TurboWarp Plus Editor block palette for the stage. You can delete this comment to reset the palette.";
68
+ var markerToken = "// _twplus_palette_";
69
+ var groupIdPattern = /^[A-Za-z0-9._-]+(?:\/[A-Za-z0-9_-]+)?$/u;
70
+ var setIdPattern = /^[A-Za-z_][A-Za-z0-9_-]*$/u;
71
+ function isRecord(value) {
72
+ return typeof value === "object" && value !== null && !Array.isArray(value);
73
+ }
74
+ function assertOnlyKeys(value, allowed, description) {
75
+ for (const key of Object.keys(value)) assert(allowed.includes(key), `${description} has an unknown key: ${key}`);
76
+ }
77
+ function validateGroupList(value, description) {
78
+ assert(Array.isArray(value), `${description} must be an array of block group IDs.`);
79
+ const seen = /* @__PURE__ */ new Set();
80
+ for (const group of value) {
81
+ assert(typeof group === "string" && groupIdPattern.test(group), `${description} contains an invalid block group ID: ${JSON.stringify(group)}`);
82
+ assert(!seen.has(group), `${description} contains a duplicate block group ID: ${group}`);
83
+ seen.add(group);
84
+ }
85
+ return [...seen];
86
+ }
87
+ function validateTargetSetting(value, description) {
88
+ assert(isRecord(value), `${description} must be an object.`);
89
+ assertOnlyKeys(value, ["groups"], description);
90
+ return { groups: validateGroupList(value.groups, `${description} groups`) };
91
+ }
92
+ function validateSets(value, description) {
93
+ assert(isRecord(value), `${description} must be an object.`);
94
+ return Object.fromEntries(Object.entries(value).map(([setId, set]) => {
95
+ assert(setIdPattern.test(setId), `${description} has an invalid set ID: ${setId}`);
96
+ const setDescription = `${description}.${setId}`;
97
+ assert(isRecord(set), `${setDescription} must be an object.`);
98
+ assertOnlyKeys(set, ["name", "groups"], setDescription);
99
+ assert(typeof set.name === "string" && set.name.length > 0, `${setDescription} name must be a non-empty string.`);
100
+ return [setId, {
101
+ name: set.name,
102
+ groups: validateGroupList(set.groups, `${setDescription} groups`)
103
+ }];
104
+ }));
105
+ }
106
+ function canonicalDocument(parts) {
107
+ const document = { formatVersion: 1 };
108
+ if (parts.order !== void 0) document.order = parts.order;
109
+ if (parts.sets !== void 0) document.sets = parts.sets;
110
+ if (parts.stage !== void 0) document.stage = parts.stage;
111
+ if (parts.sprites !== void 0 && Object.keys(parts.sprites).length > 0) document.sprites = parts.sprites;
112
+ return document;
113
+ }
114
+ function hasBlockPaletteSettings(document) {
115
+ return document.order !== void 0 || document.sets !== void 0 || document.stage !== void 0 || document.sprites !== void 0 && Object.keys(document.sprites).length > 0;
116
+ }
117
+ function stageHasSettings(document) {
118
+ return document.order !== void 0 || document.sets !== void 0 || document.stage !== void 0;
119
+ }
120
+ /** Validate the shape of `block-palette.json` without looking at the project. */
121
+ function validateBlockPaletteDocument(value) {
122
+ const description = blockPaletteFile;
123
+ assert(isRecord(value), `${description} must contain an object.`);
124
+ assertOnlyKeys(value, [
125
+ "formatVersion",
126
+ "order",
127
+ "sets",
128
+ "stage",
129
+ "sprites"
130
+ ], description);
131
+ assert(value.formatVersion === 1, `Unsupported ${description} formatVersion: ${String(value.formatVersion)}`);
132
+ let sprites;
133
+ if (value.sprites !== void 0) {
134
+ assert(isRecord(value.sprites), `${description} sprites must be an object.`);
135
+ assert(Object.keys(value.sprites).length > 0, `${description} sprites must be omitted when it has no sprites.`);
136
+ sprites = Object.fromEntries(Object.entries(value.sprites).map(([name, setting]) => [name, validateTargetSetting(setting, `${description} sprites.${name}`)]));
137
+ }
138
+ const document = canonicalDocument({
139
+ order: value.order === void 0 ? void 0 : validateGroupList(value.order, "order"),
140
+ sets: value.sets === void 0 ? void 0 : validateSets(value.sets, `${description} sets`),
141
+ stage: value.stage === void 0 ? void 0 : validateTargetSetting(value.stage, `${description} stage`),
142
+ sprites
143
+ });
144
+ assert(hasBlockPaletteSettings(document), `${description} has no settings; remove it and use SB3 source format 1.`);
145
+ return document;
146
+ }
147
+ function serializeBlockPaletteDocument(document) {
148
+ return `${JSON.stringify(canonicalDocument(document), null, 2)}\n`;
149
+ }
150
+ /**
151
+ * List each target's comments. In strict mode, a malformed target or comment is an error;
152
+ * otherwise it is skipped so unpacking stays as permissive as it was in source format 1.
153
+ */
154
+ function targetComments(project, strict = true) {
155
+ if (!strict && !Array.isArray(project.targets)) return [];
156
+ assert(Array.isArray(project.targets), "Project targets must be an array.");
157
+ const targets = [];
158
+ for (const [index, target] of project.targets.entries()) {
159
+ var _target$comments;
160
+ if (!strict && !isRecord(target)) continue;
161
+ assert(isRecord(target), `Project target ${index} must be an object.`);
162
+ const comments = (_target$comments = target.comments) !== null && _target$comments !== void 0 ? _target$comments : {};
163
+ if (!strict && !isRecord(comments)) continue;
164
+ assert(isRecord(comments), `Project target ${index} comments must be an object.`);
165
+ const records = Object.fromEntries(Object.entries(comments).filter(([id, comment]) => {
166
+ assert(!strict || isRecord(comment), `Project target ${index} comment ${id} must be an object.`);
167
+ return isRecord(comment);
168
+ }));
169
+ targets.push({
170
+ comments: records,
171
+ isStage: target.isStage === true,
172
+ name: typeof target.name === "string" ? target.name : String(index)
173
+ });
174
+ }
175
+ return targets;
176
+ }
177
+ function isMarkedComment(comment) {
178
+ return typeof comment.text === "string" && comment.text.includes(markerToken);
179
+ }
180
+ function isReferenceComment(comment) {
181
+ return comment.text === blockPaletteCommentReference;
182
+ }
183
+ function canonicalCommentText(document, target) {
184
+ let payload;
185
+ if (target.isStage) {
186
+ payload = { formatVersion: 1 };
187
+ if (document.stage) payload.groups = document.stage.groups;
188
+ if (document.order) payload.order = document.order;
189
+ if (document.sets) payload.sets = document.sets;
190
+ } else {
191
+ var _document$sprites;
192
+ const setting = (_document$sprites = document.sprites) === null || _document$sprites === void 0 ? void 0 : _document$sprites[target.name];
193
+ assert(setting, `${blockPaletteFile} has no setting for sprite ${target.name}.`);
194
+ payload = {
195
+ formatVersion: 1,
196
+ groups: setting.groups
197
+ };
198
+ }
199
+ return `${target.isStage ? blockPaletteStageCommentHeader : blockPaletteSpriteCommentHeader}\n${JSON.stringify(payload)}${blockPaletteCommentMarker}`;
200
+ }
201
+ /**
202
+ * The canonical comment text for one sprite or the stage. Fails when the text is longer than
203
+ * 8000 characters, which Scratch 3 refuses to load.
204
+ */
205
+ function formatBlockPaletteComment(document, target) {
206
+ const text = canonicalCommentText(document, target);
207
+ const length = Array.from(text).length;
208
+ assert(length <= blockPaletteCommentMaxLength, `Block palette comment for ${target.isStage ? "the stage" : `sprite ${target.name}`} has ${length} characters; the limit is ${blockPaletteCommentMaxLength}.`);
209
+ return text;
210
+ }
211
+ function parseMarkedComment(comment, isStage) {
212
+ if (comment.extraText !== void 0) return {
213
+ ok: false,
214
+ reason: "the comment has extraText"
215
+ };
216
+ const markedLines = comment.text.split("\n").filter((line) => line.includes(markerToken));
217
+ if (markedLines.length !== 1) return {
218
+ ok: false,
219
+ reason: "the marker must appear on exactly one line"
220
+ };
221
+ const [line] = markedLines;
222
+ const json = line.slice(0, line.indexOf(markerToken)).trim();
223
+ let value;
224
+ try {
225
+ value = JSON.parse(json);
226
+ } catch (_unused) {
227
+ return {
228
+ ok: false,
229
+ reason: "the marked line is not valid JSON"
230
+ };
231
+ }
232
+ try {
233
+ assert(isRecord(value), "the JSON must be an object");
234
+ assertOnlyKeys(value, isStage ? [
235
+ "formatVersion",
236
+ "groups",
237
+ "order",
238
+ "sets"
239
+ ] : ["formatVersion", "groups"], "the JSON");
240
+ assert(value.formatVersion === 1, `unsupported formatVersion ${String(value.formatVersion)}`);
241
+ assert(isStage || value.groups !== void 0, "the JSON has no groups");
242
+ const parsed = {
243
+ order: value.order === void 0 ? void 0 : validateGroupList(value.order, "order"),
244
+ sets: value.sets === void 0 ? void 0 : validateSets(value.sets, "sets"),
245
+ stage: value.groups === void 0 ? void 0 : { groups: validateGroupList(value.groups, "groups") }
246
+ };
247
+ assert(parsed.order !== void 0 || parsed.sets !== void 0 || parsed.stage !== void 0, "the JSON has no settings");
248
+ return {
249
+ ok: true,
250
+ value: parsed
251
+ };
252
+ } catch (error) {
253
+ return {
254
+ ok: false,
255
+ reason: error instanceof Error ? error.message : String(error)
256
+ };
257
+ }
258
+ }
259
+ /**
260
+ * Move palette comments from an SB3 project into a `block-palette.json` document.
261
+ * The project is changed in place: each recognized comment keeps its ID, position, size,
262
+ * state and order, and its text becomes {@link blockPaletteCommentReference}.
263
+ */
264
+ function extractBlockPalette(project) {
265
+ const warnings = [];
266
+ const parts = {};
267
+ const sprites = [];
268
+ for (const target of targetComments(project, false)) {
269
+ const marked = Object.entries(target.comments).filter(([, comment]) => isMarkedComment(comment));
270
+ assert(Object.values(target.comments).filter(isReferenceComment).length === 0, `${target.isStage ? "The stage" : `Sprite ${target.name}`} has a comment whose text is reserved for block palette references: ${blockPaletteCommentReference}`);
271
+ assert(marked.length <= 1, `${target.isStage ? "The stage" : `Sprite ${target.name}`} has ${marked.length} block palette comments; only one is allowed.`);
272
+ if (marked.length === 0) continue;
273
+ const [[commentId, comment]] = marked;
274
+ const parsed = parseMarkedComment(comment, target.isStage);
275
+ if (!parsed.ok) {
276
+ warnings.push({
277
+ code: "block-palette-invalid",
278
+ commentId,
279
+ message: `Block palette comment ${commentId} on ${target.name} was kept as a plain comment and ignored: ${parsed.reason}.`,
280
+ target: target.name
281
+ });
282
+ continue;
283
+ }
284
+ if (target.isStage) Object.assign(parts, parsed.value);
285
+ else {
286
+ assert(!sprites.some(([name]) => name === target.name), `Duplicate sprite name with block palette settings: ${target.name}`);
287
+ sprites.push([target.name, parsed.value.stage]);
288
+ }
289
+ const canonicalText = canonicalCommentText(canonicalDocument(_objectSpread2(_objectSpread2({}, parts), {}, { sprites: Object.fromEntries(sprites) })), target);
290
+ if (comment.text !== canonicalText) warnings.push({
291
+ code: "block-palette-normalized",
292
+ commentId,
293
+ message: `Block palette comment ${commentId} on ${target.name} is not in the canonical form; it will be rewritten on build.`,
294
+ target: target.name
295
+ });
296
+ comment.text = blockPaletteCommentReference;
297
+ }
298
+ const document = canonicalDocument(_objectSpread2(_objectSpread2({}, parts), {}, { sprites: Object.fromEntries(sprites) }));
299
+ return {
300
+ document: hasBlockPaletteSettings(document) ? document : null,
301
+ warnings
302
+ };
303
+ }
304
+ /**
305
+ * Check that `project.source.json` and `block-palette.json` agree, and return the canonical
306
+ * comment text for each reference. `document` is null for source format 1.
307
+ */
308
+ function resolveBlockPaletteReferences(project, document) {
309
+ var _document$sprites2;
310
+ const resolved = [];
311
+ const targets = targetComments(project, document !== null);
312
+ if (document === null) {
313
+ for (const target of targets) assert(!Object.values(target.comments).some(isReferenceComment), `project.source.json refers to ${blockPaletteFile}, which requires SB3 source format 2.`);
314
+ return resolved;
315
+ }
316
+ const spriteNames = new Set(targets.filter(({ isStage }) => !isStage).map(({ name }) => name));
317
+ for (const name of Object.keys((_document$sprites2 = document.sprites) !== null && _document$sprites2 !== void 0 ? _document$sprites2 : {})) assert(spriteNames.has(name), `${blockPaletteFile} refers to an unknown sprite: ${name}`);
318
+ for (const target of targets) {
319
+ var _document$sprites3;
320
+ const label = target.isStage ? "The stage" : `Sprite ${target.name}`;
321
+ const references = Object.values(target.comments).filter(isReferenceComment);
322
+ const marked = Object.values(target.comments).filter(isMarkedComment);
323
+ const expected = target.isStage ? stageHasSettings(document) : ((_document$sprites3 = document.sprites) === null || _document$sprites3 === void 0 ? void 0 : _document$sprites3[target.name]) !== void 0;
324
+ assert(references.length <= 1, `${label} has ${references.length} block palette references; only one is allowed.`);
325
+ assert(references.length === 0 || marked.length === 0, `${label} has both a block palette reference and a block palette comment.`);
326
+ assert(references.length === (expected ? 1 : 0), expected ? `${label} has block palette settings in ${blockPaletteFile} but no comment that refers to it (${blockPaletteCommentReference}).` : `${label} has a block palette reference but no settings in ${blockPaletteFile}.`);
327
+ if (references.length === 1) resolved.push({
328
+ comment: references[0],
329
+ text: formatBlockPaletteComment(document, target)
330
+ });
331
+ }
332
+ return resolved;
333
+ }
334
+ /** Replace each reference comment in a cloned project with its canonical SB3 text. */
335
+ function applyBlockPaletteComments(project, document) {
336
+ for (const { comment, text } of resolveBlockPaletteReferences(project, document)) comment.text = text;
337
+ }
99
338
  // \0@oxc-project+runtime@0.156.0/helpers/esm/objectWithoutPropertiesLoose.js
100
339
  function _objectWithoutPropertiesLoose(r, e) {
101
340
  if (null == r) return {};
@@ -116,6 +355,48 @@ function _objectWithoutProperties(e, t) {
116
355
  }
117
356
  return i;
118
357
  }
358
+ // \0@oxc-project+runtime@0.156.0/helpers/esm/asyncIterator.js
359
+ function _asyncIterator(r) {
360
+ var n, t, o, e = 2;
361
+ for ("undefined" != typeof Symbol && (t = Symbol.asyncIterator, o = Symbol.iterator); e--;) {
362
+ if (t && null != (n = r[t])) return n.call(r);
363
+ if (o && null != (n = r[o])) return new AsyncFromSyncIterator(n.call(r));
364
+ t = "@@asyncIterator", o = "@@iterator";
365
+ }
366
+ throw new TypeError("Object is not async iterable");
367
+ }
368
+ function AsyncFromSyncIterator(r) {
369
+ function AsyncFromSyncIteratorContinuation(r) {
370
+ if (Object(r) !== r) return Promise.reject(/* @__PURE__ */ new TypeError(r + " is not an object."));
371
+ var n = r.done;
372
+ return Promise.resolve(r.value).then(function(r) {
373
+ return {
374
+ value: r,
375
+ done: n
376
+ };
377
+ });
378
+ }
379
+ return AsyncFromSyncIterator = function AsyncFromSyncIterator(r) {
380
+ this.s = r, this.n = r.next;
381
+ }, AsyncFromSyncIterator.prototype = {
382
+ s: null,
383
+ n: null,
384
+ next: function next() {
385
+ return AsyncFromSyncIteratorContinuation(this.n.apply(this.s, arguments));
386
+ },
387
+ "return": function _return(r) {
388
+ var n = this.s["return"];
389
+ return void 0 === n ? Promise.resolve({
390
+ value: r,
391
+ done: !0
392
+ }) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
393
+ },
394
+ "throw": function _throw(r) {
395
+ var n = this.s["throw"];
396
+ return void 0 === n ? Promise.reject(r) : AsyncFromSyncIteratorContinuation(n.apply(this.s, arguments));
397
+ }
398
+ }, new AsyncFromSyncIterator(r);
399
+ }
119
400
  // src/source.ts
120
401
  var _excluded = ["targets"];
121
402
  var _excluded2 = ["targets"];
@@ -123,6 +404,10 @@ var _excluded3 = ["targets"];
123
404
  var projectFile = "project.source.json";
124
405
  var manifestFile = "sb3-source.json";
125
406
  var extensionsFile = "embedded-extensions.json";
407
+ /** The ZIP entry of the Editor's screen state, which sb3-toolchain lists in `archiveEntries`. */
408
+ var screenStateEntry = "tw-plus/workspace.json";
409
+ /** Block palette settings of source format 2. Format 1 folders have no such file. */
410
+ var paletteFile = blockPaletteFile;
126
411
  var embeddedReference = "embedded-extension:";
127
412
  var FolderError = class extends Error {
128
413
  constructor(code, detail) {
@@ -157,6 +442,34 @@ function parseProject(text) {
157
442
  if (stages !== 1) return unsupported("Expected one stage");
158
443
  return project;
159
444
  }
445
+ var palette = (action) => {
446
+ try {
447
+ return action();
448
+ } catch (error) {
449
+ if (error instanceof FolderError) throw error;
450
+ return unsupported(`Invalid block palette settings: ${error instanceof Error ? error.message : String(error)}`);
451
+ }
452
+ };
453
+ /** A copy of a folder project with each palette reference turned back into its comment text, as the VM loads it. */
454
+ var expandPalette = (project, document) => {
455
+ if (!document) return project;
456
+ const copy = structuredClone(project);
457
+ palette(() => applyBlockPaletteComments(copy, document));
458
+ return copy;
459
+ };
460
+ /**
461
+ * Moves palette comments from a project in the Editor's form into `block-palette.json` and returns the folder form
462
+ * of the project with the document, or a null document when no sprite or the stage has palette settings.
463
+ */
464
+ var collapsePalette = (project) => {
465
+ const copy = structuredClone(project);
466
+ const { document } = palette(() => extractBlockPalette(copy));
467
+ return {
468
+ project: copy,
469
+ document
470
+ };
471
+ };
472
+ var encodePalette = (document) => new TextEncoder().encode(serializeBlockPaletteDocument(document));
160
473
  var getFile = async (dir, name) => dir ? (await dir.getFileHandle(name)).getFile() : unsupported(`Missing folder for ${name}`);
161
474
  var fileVersion = (file) => `${file.size}:${file.lastModified}`;
162
475
  var fileBytes = async (file) => new Uint8Array(await file.arrayBuffer());
@@ -369,19 +682,29 @@ async function readFolder(directory, storage) {
369
682
  const project = parseProject(projectText);
370
683
  const manifest = readObject(decoder.decode(files.get(manifestFile)));
371
684
  const embedded = readObject(decoder.decode(files.get(extensionsFile)));
372
- if (manifest.formatVersion !== 1 || manifest.project !== "project.source.json" || manifest.embeddedExtensions !== "embedded-extensions.json" || manifest.assetsDirectory !== "assets" || !Array.isArray(manifest.archiveEntries)) return unsupported("Expected an sb3-toolchain v1 folder");
685
+ const formatVersion = manifest.formatVersion;
686
+ if (formatVersion !== 1 && formatVersion !== 2 || manifest.project !== "project.source.json" || manifest.embeddedExtensions !== "embedded-extensions.json" || manifest.assetsDirectory !== "assets" || !Array.isArray(manifest.archiveEntries) || (formatVersion === 1 ? manifest.blockPalette !== void 0 : manifest.blockPalette !== paletteFile)) return unsupported("Expected an sb3-toolchain v1 or v2 folder");
687
+ let paletteDocument = null;
688
+ if (formatVersion === 2) {
689
+ const [, paletteBytes] = await readEntry(directory, paletteFile);
690
+ files.set(paletteFile, paletteBytes);
691
+ paletteDocument = palette(() => validateBlockPaletteDocument(readObject(decoder.decode(paletteBytes))));
692
+ }
693
+ palette(() => resolveBlockPaletteReferences(project, paletteDocument));
373
694
  if (project.turboWarpPlus !== void 0) return unsupported("Plus extension manifests are not supported in project folders");
374
695
  const extensionManifest = validateExtensions(project, embedded);
375
696
  const references = projectAssets(project);
376
697
  const expected = /* @__PURE__ */ new Set(["project.json", ...references.keys()]);
377
- if (manifest.archiveEntries.length !== expected.size || !sameNames(new Set(manifest.archiveEntries), expected)) return unsupported("Asset references and archiveEntries do not match");
698
+ const listed = manifest.archiveEntries.filter((name) => name !== screenStateEntry);
699
+ if (listed.length !== expected.size || !sameNames(new Set(listed), expected)) return unsupported("Asset references and archiveEntries do not match");
378
700
  expected.delete("project.json");
379
701
  const [assets, extensions] = await Promise.all([readDirectory(directory, "assets"), readDirectory(directory, "extensions")]);
380
702
  const scripts = extensionNames(extensionManifest.extensions);
381
703
  if (!sameNames(await readNames(assets), expected) || !sameNames(await readNames(extensions), scripts)) return unsupported("Unexpected or missing source files");
382
704
  const bytes = new Map(await Promise.all([...expected].map((name) => readEntry(assets, name, "assets/"))));
383
705
  const extensionBytes = new Map(await Promise.all(scripts.map((name) => readEntry(extensions, name, "extensions/"))));
384
- const loadText = extensionManifest.extensions.length ? JSON.stringify(_objectSpread2(_objectSpread2({}, project), {}, { extensionURLs: _objectSpread2(_objectSpread2({}, extensionURLs(project)), Object.fromEntries(extensionManifest.extensions.map((entry) => [entry.id, encodeDataUrl(entry, extensionBytes.get(`${entry.id}.js`))]))) })) : projectText;
706
+ const loaded = expandPalette(project, paletteDocument);
707
+ const loadText = extensionManifest.extensions.length ? JSON.stringify(_objectSpread2(_objectSpread2({}, loaded), {}, { extensionURLs: _objectSpread2(_objectSpread2({}, extensionURLs(project)), Object.fromEntries(extensionManifest.extensions.map((entry) => [entry.id, encodeDataUrl(entry, extensionBytes.get(`${entry.id}.js`))]))) })) : paletteDocument ? JSON.stringify(loaded) : projectText;
385
708
  const storageAssets = /* @__PURE__ */ new Map();
386
709
  for (const [name, kind] of references) {
387
710
  const [id, format] = name.split(".");
@@ -399,7 +722,8 @@ async function readFolder(directory, storage) {
399
722
  project,
400
723
  loadText,
401
724
  storageAssets,
402
- embedded: extensionManifest
725
+ embedded: extensionManifest,
726
+ palette: paletteDocument
403
727
  };
404
728
  }
405
729
  var sameBytes = (a, b) => a.length === b.length && a.every((value, index) => value === b[index]);
@@ -414,7 +738,11 @@ async function readFolderUpdate(source, previous) {
414
738
  const [assetNames, extensionNames] = await Promise.all([readNames(assets), readNames(extensions)]);
415
739
  if (!sameNames(assetNames, source.bytes.keys()) || !sameNames(extensionNames, source.extensionBytes.keys())) return "structure";
416
740
  if ((await Promise.all([
417
- ...["sb3-source.json", "embedded-extensions.json"].map(async (name) => fileVersion(await getFile(directory, name)) === versions.get(name)),
741
+ ...[
742
+ "sb3-source.json",
743
+ "embedded-extensions.json",
744
+ ...source.files.has(paletteFile) ? [paletteFile] : []
745
+ ].map(async (name) => fileVersion(await getFile(directory, name)) === versions.get(name)),
418
746
  ...[...assetNames].map(async (name) => fileVersion(await getFile(assets, name)) === versions.get(`assets/${name}`)),
419
747
  ...[...extensionNames].map(async (name) => fileVersion(await getFile(extensions, name)) === versions.get(`extensions/${name}`))
420
748
  ])).includes(false)) return "structure";
@@ -547,12 +875,46 @@ function projectChanges(source, before, after, identity) {
547
875
  for (const key of Object.keys(other)) if (!Object.hasOwn(result, key)) result[key] = other[key];
548
876
  return result;
549
877
  }
878
+ // src/explorer-state.ts
879
+ /** The folder the Editor keeps its own files in. The explorer and its search leave it out, like `.git`. */
880
+ var editorDirectory = ".tw-plus";
881
+ /** The screen state of the Editor, inside `editorDirectory`. */
882
+ var screenStateFile = "workspace.json";
883
+ var hiddenEntry = (name) => [".git", editorDirectory].includes(name.toLowerCase());
884
+ var limit = 1e3;
885
+ var states = /* @__PURE__ */ new WeakMap();
886
+ var listeners = /* @__PURE__ */ new WeakMap();
887
+ var validPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 1024 && value.split("/").every((part) => part && part !== "." && part !== ".." && !hiddenEntry(part) && !/[\\\u0000]/u.test(part));
888
+ /** Read a tree state saved in a file, keeping only well-formed paths. */
889
+ function parseExplorerState(value) {
890
+ if (value === null || typeof value !== "object" || Array.isArray(value)) return;
891
+ const { expanded, selected } = value;
892
+ if (!Array.isArray(expanded)) return;
893
+ return _objectSpread2({ expanded: [...new Set(expanded.filter(validPath))].slice(0, limit) }, validPath(selected) && { selected });
894
+ }
895
+ var readExplorerState = (directory) => states.get(directory);
896
+ /** Remember the tree of `directory`. With `notify`, a mounted explorer of that folder shows it too. */
897
+ function writeExplorerState(directory, state, notify = false) {
898
+ var _listeners$get;
899
+ states.set(directory, state);
900
+ if (notify) for (const listener of [...(_listeners$get = listeners.get(directory)) !== null && _listeners$get !== void 0 ? _listeners$get : []]) listener(state);
901
+ }
902
+ function subscribeExplorerState(directory, listener) {
903
+ let set = listeners.get(directory);
904
+ if (!set) listeners.set(directory, set = /* @__PURE__ */ new Set());
905
+ set.add(listener);
906
+ return () => {
907
+ set.delete(listener);
908
+ };
909
+ }
550
910
  // src/create-folder.ts
551
911
  var manifests = /* @__PURE__ */ new Set([
552
912
  projectFile,
553
913
  manifestFile,
554
914
  extensionsFile
555
915
  ]);
916
+ var optionalManifests = /* @__PURE__ */ new Set([paletteFile]);
917
+ var screenStatePath = `${editorDirectory}/${screenStateFile}`;
556
918
  var sourceDirectories = ["assets", "extensions"];
557
919
  var sourcePath = /^(?:assets\/[a-f0-9]{32}\.[A-Za-z0-9]+|extensions\/[A-Za-z0-9._-]+\.(?:js|manifest\.json))$/u;
558
920
  function missing(error) {
@@ -607,7 +969,7 @@ async function directoryEntries(directory) {
607
969
  /** Create and validate a project-folder snapshot in a directory chosen by the user. */
608
970
  async function createProjectFolder({ directory, files, storage, overwrite = false, current = () => true }) {
609
971
  for (const filename of manifests) if (!files.has(filename)) return unsupported(`Missing ${filename}`);
610
- for (const [filename, bytes] of files) if (!manifests.has(filename) && !sourcePath.test(filename) || !(bytes instanceof Uint8Array)) return unsupported(`Invalid project folder entry: ${filename}`);
972
+ for (const [filename, bytes] of files) if (!manifests.has(filename) && !optionalManifests.has(filename) && filename !== screenStatePath && !sourcePath.test(filename) || !(bytes instanceof Uint8Array)) return unsupported(`Invalid project folder entry: ${filename}`);
611
973
  const assertCurrent = () => {
612
974
  if (!current()) throw new FolderError("conflict", "The project changed before the folder was saved");
613
975
  };
@@ -690,6 +1052,33 @@ async function createProjectFolder({ directory, files, storage, overwrite = fals
690
1052
  entries: children
691
1053
  });
692
1054
  }
1055
+ const editorEntry = existing.get(editorDirectory);
1056
+ if (files.has(screenStatePath)) {
1057
+ if ((editorEntry === null || editorEntry === void 0 ? void 0 : editorEntry.kind) === "file") await remove(directory, editorEntry);
1058
+ const previous = await getDirectory(directory, editorDirectory);
1059
+ if (previous && (editorEntry === null || editorEntry === void 0 ? void 0 : editorEntry.kind) === "directory" && !await previous.isSameEntry(editorEntry)) throw new FolderError("conflict");
1060
+ assertCurrent();
1061
+ const handle = previous !== null && previous !== void 0 ? previous : await directory.getDirectoryHandle(editorDirectory, { create: true });
1062
+ if (!previous) undo.push(async () => {
1063
+ const found = await getDirectory(directory, editorDirectory);
1064
+ if (found && await found.isSameEntry(handle)) await directory.removeEntry(editorDirectory);
1065
+ });
1066
+ directories.set(editorDirectory, {
1067
+ handle,
1068
+ entries: await directoryEntries(handle)
1069
+ });
1070
+ } else if ((editorEntry === null || editorEntry === void 0 ? void 0 : editorEntry.kind) === "directory") {
1071
+ const handle = await getDirectory(directory, editorDirectory);
1072
+ const stale = handle && (await directoryEntries(handle)).get("workspace.json");
1073
+ if (stale) await remove(handle, stale);
1074
+ }
1075
+ for (const name of optionalManifests) {
1076
+ const entry = existing.get(name);
1077
+ if (entry && !files.has(name)) {
1078
+ await remove(directory, entry);
1079
+ existing.delete(name);
1080
+ }
1081
+ }
693
1082
  const entries = [...files].sort(([a], [b]) => Number(manifests.has(a)) - Number(manifests.has(b)) || Number(a === "project.source.json") - Number(b === "project.source.json"));
694
1083
  for (const [filename, bytes] of entries) {
695
1084
  var _subdirectory$handle, _subdirectory$entries;
@@ -732,38 +1121,6 @@ async function createProjectFolder({ directory, files, storage, overwrite = fals
732
1121
  throw error;
733
1122
  }
734
1123
  }
735
- // src/explorer-state.ts
736
- /** The folder the Editor keeps its own files in. The explorer and its search leave it out, like `.git`. */
737
- var editorDirectory = ".tw-plus";
738
- /** The screen state of the Editor, inside `editorDirectory`. */
739
- var screenStateFile = "workspace.json";
740
- var hiddenEntry = (name) => [".git", editorDirectory].includes(name.toLowerCase());
741
- var limit = 1e3;
742
- var states = /* @__PURE__ */ new WeakMap();
743
- var listeners = /* @__PURE__ */ new WeakMap();
744
- var validPath = (value) => typeof value === "string" && value.length > 0 && value.length <= 1024 && value.split("/").every((part) => part && part !== "." && part !== ".." && !hiddenEntry(part) && !/[\\\u0000]/u.test(part));
745
- /** Read a tree state saved in a file, keeping only well-formed paths. */
746
- function parseExplorerState(value) {
747
- if (value === null || typeof value !== "object" || Array.isArray(value)) return;
748
- const { expanded, selected } = value;
749
- if (!Array.isArray(expanded)) return;
750
- return _objectSpread2({ expanded: [...new Set(expanded.filter(validPath))].slice(0, limit) }, validPath(selected) && { selected });
751
- }
752
- var readExplorerState = (directory) => states.get(directory);
753
- /** Remember the tree of `directory`. With `notify`, a mounted explorer of that folder shows it too. */
754
- function writeExplorerState(directory, state, notify = false) {
755
- var _listeners$get;
756
- states.set(directory, state);
757
- if (notify) for (const listener of [...(_listeners$get = listeners.get(directory)) !== null && _listeners$get !== void 0 ? _listeners$get : []]) listener(state);
758
- }
759
- function subscribeExplorerState(directory, listener) {
760
- let set = listeners.get(directory);
761
- if (!set) listeners.set(directory, set = /* @__PURE__ */ new Set());
762
- set.add(listener);
763
- return () => {
764
- set.delete(listener);
765
- };
766
- }
767
1124
  // src/folder-registry.ts
768
1125
  var folders = /* @__PURE__ */ new WeakMap();
769
1126
  var registrations = /* @__PURE__ */ new Set();
@@ -802,4 +1159,4 @@ function followProjectFolder(vm, listener) {
802
1159
  unsubscribe();
803
1160
  };
804
1161
  }
805
- export { unsupported as A, planExtensionSave as C, readFolder as D, projectFile as E, _objectSpread2 as M, _asyncIterator as N, readFolderUpdate as O, parseProject as S, projectChanges as T, equal as _, parseExplorerState as a, isObject as b, subscribeExplorerState as c, isProjectFolderEmpty as d, projectFolderOverwriteWarning as f, assetTypeFor as g, assetKey as h, hiddenEntry as i, _objectWithoutProperties as j, sameBytes as k, writeExplorerState as l, assertFolderUnchanged as m, registerFolder as n, readExplorerState as o, FolderError as p, editorDirectory as r, screenStateFile as s, followProjectFolder as t, createProjectFolder as u, extensionsFile as v, projectAssets as w, manifestFile as x, fileVersion as y };
1162
+ export { projectFile as A, isObject as C, planExtensionSave as D, parseProject as E, _asyncIterator as F, _objectWithoutProperties as I, _objectSpread2 as L, readFolderUpdate as M, sameBytes as N, projectAssets as O, unsupported as P, fileVersion as S, paletteFile as T, collapsePalette as _, projectFolderOverwriteWarning as a, expandPalette as b, parseExplorerState as c, subscribeExplorerState as d, writeExplorerState as f, assetTypeFor as g, assetKey as h, isProjectFolderEmpty as i, readFolder as j, projectChanges as k, readExplorerState as l, assertFolderUnchanged as m, registerFolder as n, editorDirectory as o, FolderError as p, createProjectFolder as r, hiddenEntry as s, followProjectFolder as t, screenStateFile as u, encodePalette as v, manifestFile as w, extensionsFile as x, equal as y };
package/dist/source.d.ts CHANGED
@@ -1,3 +1,4 @@
1
+ import type { BlockPaletteDocument } from '@kubohiroya/sb3-toolchain/browser';
1
2
  export type Json = null | boolean | number | string | Json[] | {
2
3
  [key: string]: Json;
3
4
  };
@@ -14,6 +15,8 @@ type Target = JsonObject & {
14
15
  export declare const projectFile = "project.source.json";
15
16
  export declare const manifestFile = "sb3-source.json";
16
17
  export declare const extensionsFile = "embedded-extensions.json";
18
+ /** Block palette settings of source format 2. Format 1 folders have no such file. */
19
+ export declare const paletteFile = "block-palette.json";
17
20
  export declare class FolderError extends Error {
18
21
  code: 'conflict' | 'unsupported';
19
22
  constructor(code: FolderError['code'], detail?: string);
@@ -53,7 +56,20 @@ export type FolderSource = FolderFiles & {
53
56
  loadText: string;
54
57
  storageAssets: Map<string, Asset>;
55
58
  embedded: ExtensionManifest;
59
+ /** The folder's `block-palette.json`, or null for a format 1 folder. */
60
+ palette: BlockPaletteDocument | null;
56
61
  };
62
+ /** A copy of a folder project with each palette reference turned back into its comment text, as the VM loads it. */
63
+ export declare const expandPalette: (project: Project, document: BlockPaletteDocument | null) => Project;
64
+ /**
65
+ * Moves palette comments from a project in the Editor's form into `block-palette.json` and returns the folder form
66
+ * of the project with the document, or a null document when no sprite or the stage has palette settings.
67
+ */
68
+ export declare const collapsePalette: (project: Project) => {
69
+ project: Project;
70
+ document: BlockPaletteDocument | null;
71
+ };
72
+ export declare const encodePalette: (document: BlockPaletteDocument) => Uint8Array<ArrayBuffer>;
57
73
  export declare const fileVersion: (file: File) => string;
58
74
  export type AssetKind = 'costumes' | 'sounds' | 'fonts';
59
75
  export declare const assetTypeFor: (storage: Storage, kind: AssetKind, format: string) => AssetType;
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@kubohiroya/turbowarp-plus-editor-project-folder",
3
- "version": "0.10.0",
3
+ "version": "0.12.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",
@@ -55,7 +55,7 @@
55
55
  "@codemirror/view": "6.43.15",
56
56
  "@headless-tree/core": "1.8.0",
57
57
  "@headless-tree/react": "1.8.0",
58
- "@kubohiroya/sb3-toolchain": "0.22.0",
58
+ "@kubohiroya/sb3-toolchain": "0.26.0",
59
59
  "@kubohiroya/turbowarp-plus-editor-test-runtime": "0.1.0",
60
60
  "@lezer/highlight": "1.2.5",
61
61
  "@playwright/test": "1.64.1",