@kubohiroya/turbowarp-plus-editor-project-folder 0.7.0 → 0.9.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.
@@ -0,0 +1,50 @@
1
+ /** The project folder mounted for a VM, as a view of the folder follows it. */
2
+ export type ExplorerMutation = (guard: () => void) => Promise<void>;
3
+
4
+ export interface FollowedFolder {
5
+ readonly directory: FileSystemDirectoryHandle | null;
6
+ subscribe(listener: () => void): () => void;
7
+ subscribeEdits(listener: () => void): () => void;
8
+ unsavedPaths(): ReadonlySet<string> | null;
9
+ /** Asks for a folder and opens it, as the File menu's Open Project Folder… does. */
10
+ open(locale: string): void;
11
+ mutate(directory: FileSystemDirectoryHandle, operation: ExplorerMutation): Promise<void>;
12
+ }
13
+ const folders = new WeakMap<object, FollowedFolder>();
14
+ // Views rendered before the folder is mounted, or after it is disposed, wait for the VM's folder here.
15
+ const registrations = new Set<() => void>();
16
+ const announce = () => {for (const listener of [...registrations]) listener();};
17
+
18
+ export function registerFolder(vm: object, folder: FollowedFolder) {
19
+ folders.set(vm, folder);
20
+ announce();
21
+ return () => {
22
+ if (folders.get(vm) === folder) folders.delete(vm);
23
+ announce();
24
+ };
25
+ }
26
+
27
+ /**
28
+ * Calls `listener` with the project folder mounted for `vm` and the directory open in it, now and whenever a folder is
29
+ * mounted, opened, closed or saved. Returns the function that stops it.
30
+ */
31
+ export function followProjectFolder(vm: object,
32
+ listener: (folder: FollowedFolder | undefined, directory: FileSystemDirectoryHandle | null) => void) {
33
+ let unsubscribe = () => {};
34
+ let followed: FollowedFolder | undefined;
35
+ const update = () => {
36
+ const folder = folders.get(vm);
37
+ if (folder !== followed) {
38
+ unsubscribe();
39
+ followed = folder;
40
+ unsubscribe = folder ? folder.subscribe(() => listener(folder, folder.directory)) : () => {};
41
+ }
42
+ listener(folder, folder?.directory ?? null);
43
+ };
44
+ registrations.add(update);
45
+ update();
46
+ return () => {
47
+ registrations.delete(update);
48
+ unsubscribe();
49
+ };
50
+ }
package/src/index.ts CHANGED
@@ -1,10 +1,14 @@
1
1
  import {FolderError} from './source.js';
2
2
  import {createFolderSession} from './session.js';
3
+ import {registerFolder} from './folder-registry.js';
3
4
  import type {FolderHost, FolderVM, PickerWindow} from './session.js';
4
5
 
5
6
  export type {Comparison, ComparisonRequest, ComparisonSection, FolderHost, FolderVM, OpenResult} from './session.js';
6
7
  export type {ReloadTarget} from './block-reload.js';
8
+ export {followProjectFolder} from './folder-registry.js';
9
+ export type {FollowedFolder} from './folder-registry.js';
7
10
  export type {DeserializeBlocks} from './script-reload.js';
11
+ export {createProjectFolder} from './create-folder.js';
8
12
 
9
13
  const messages = {
10
14
  en: {
@@ -221,7 +225,7 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
221
225
  notice.remove();
222
226
  };
223
227
  }
224
- menus.set(vm, {
228
+ const menu: MenuEntry = {
225
229
  session,
226
230
  open(locale) {
227
231
  const message = messageFor(locale);
@@ -232,19 +236,55 @@ export function mountProjectFolder({vm, document, host, locale = 'en', autoReloa
232
236
  save(locale) {
233
237
  if (!session.busy) {
234
238
  const message = messageFor(locale);
235
- void session.save().then(({status, sourceRemoved}) => {
239
+ const directory = session.directory;
240
+ const save = () => {
241
+ if (session.directory !== directory) throw new FolderError('conflict');
242
+ return session.save();
243
+ };
244
+ void (host.saveWithLock?.(save) ?? save()).then(({status, sourceRemoved}) => {
236
245
  const detail = sourceRemoved.length ? ` ${message.sourceRemoved(sourceRemoved)}` : '';
237
246
  report(message[status] + detail);
238
247
  }, error => fail(locale, error)).finally(renderReload);
239
248
  renderReload();
240
249
  }
241
250
  }
251
+ };
252
+ menus.set(vm, menu);
253
+ const unregister = registerFolder(vm, {
254
+ get directory() {return session.directory;},
255
+ subscribe: listener => session.subscribe(listener),
256
+ subscribeEdits: listener => session.subscribeEdits(listener),
257
+ unsavedPaths: () => session.unsavedPaths(),
258
+ open: locale => menu.open(locale),
259
+ mutate: (directory, operation) => session.mutate(directory, operation).finally(renderReload)
242
260
  });
243
261
  return {
244
262
  openDirectory: (...args: Parameters<typeof session.openDirectory>) =>
245
263
  session.openDirectory(...args).finally(renderReload),
264
+ save: () => session.save().finally(renderReload),
265
+ createFromSnapshot({prepareFiles, directory, current = () => true}: {
266
+ prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>;
267
+ directory?: FileSystemDirectoryHandle;
268
+ current?: () => boolean;
269
+ }) {
270
+ return session.createFromSnapshot(async () => {
271
+ if (directory) return directory;
272
+ try {
273
+ return await pickDirectory.call(view, {id: 'turbowarp-plus-project-folder', mode: 'readwrite'});
274
+ } catch (error) {
275
+ if (error instanceof DOMException && error.name === 'AbortError') return null;
276
+ throw error;
277
+ }
278
+ }, prepareFiles, current).finally(renderReload);
279
+ },
280
+ /**
281
+ * The folder the loaded project came from, or `null` once another project loaded or the folder was
282
+ * detached. A host can tell projects apart by it, for example to keep the layout of each one.
283
+ */
284
+ get directory() {return session.directory;},
246
285
  dispose() {
247
286
  menus.delete(vm);
287
+ unregister();
248
288
  session.dispose();
249
289
  stopWatching?.();
250
290
  view.clearTimeout(timer);
package/src/session.ts CHANGED
@@ -1,10 +1,11 @@
1
1
  import {assetKey, assetTypeFor, assertFolderUnchanged, extensionsFile, fileVersion, FolderError, manifestFile, parseProject,
2
2
  planExtensionSave, projectAssets, projectChanges, projectFile, readFolder, readFolderUpdate, sameBytes, unsupported} from './source.js';
3
- import type {Asset, FolderSource, FolderUpdate, JsonObject, Project, Storage} from './source.js';
3
+ import type {Asset, AssetKind, FolderSource, FolderUpdate, JsonObject, Project, Storage} from './source.js';
4
4
  import {applyBlockReload, planBlockReload} from './block-reload.js';
5
5
  import type {ReloadTarget} from './block-reload.js';
6
6
  import {applyScriptReload, planScriptReload} from './script-reload.js';
7
7
  import type {DeserializeBlocks, ScriptReloadTarget} from './script-reload.js';
8
+ import {createProjectFolder} from './create-folder.js';
8
9
 
9
10
  export interface FolderVM {
10
11
  runtime: {
@@ -19,6 +20,7 @@ export interface FolderVM {
19
20
  quit(): void;
20
21
  loadProject(project: string, options?: {replaceLegacyExtensions: boolean}): Promise<unknown>;
21
22
  toJSON(target?: string, options?: {allowOptimization: boolean}): string;
23
+ assets?: readonly (Asset | null | undefined)[];
22
24
  renderer?: {draw(): void};
23
25
  }
24
26
 
@@ -43,6 +45,7 @@ export interface FolderHost {
43
45
  beforeLoad(): void;
44
46
  onOpened(title: string): void;
45
47
  onSaved(): void;
48
+ saveWithLock?<T>(save: () => Promise<T>): Promise<T>;
46
49
  blockReload?: {
47
50
  isRunning(): boolean;
48
51
  subscribe(listener: () => void): () => void;
@@ -90,6 +93,14 @@ type VMAsset = {assetId: string; dataFormat: string; data?: Uint8Array};
90
93
 
91
94
  export function createFolderSession(vm: FolderVM, host: FolderHost) {
92
95
  let current: Session | null = null;
96
+ // Told when a folder opens or closes, and after a save, so a view of the folder can read it again.
97
+ const listeners = new Set<() => void>();
98
+ const notify = () => {for (const listener of [...listeners]) listener();};
99
+ const setCurrent = (session: Session | null) => {
100
+ if (current === session) return;
101
+ current = session;
102
+ notify();
103
+ };
93
104
  let busy = false;
94
105
  let disposed = false;
95
106
  let revision = 0;
@@ -128,7 +139,10 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
128
139
  }
129
140
  };
130
141
  // The bytes of an asset the Editor holds, such as a costume added since the folder was opened.
131
- const assetData = (name: string) => {
142
+ const assetData = (name: string, kind: AssetKind) => {
143
+ if (kind === 'fonts') {
144
+ return vm.assets?.find(asset => asset && `${asset.assetId}.${asset.dataFormat}` === name)?.data;
145
+ }
132
146
  for (const target of runtimeTargets()) {
133
147
  for (const entry of [...target.sprite?.costumes ?? [], ...target.sprite?.sounds ?? []]) {
134
148
  const asset = entry.asset;
@@ -137,8 +151,19 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
137
151
  }
138
152
  return null;
139
153
  };
140
- const changed = () => {revision++;};
141
- const loaded = () => {current = null;};
154
+ const editListeners = new Set<() => void>();
155
+ const notifyEdits = () => {for (const listener of [...editListeners]) listener();};
156
+ const changed = () => {revision++; notifyEdits();};
157
+ const planSave = (session: Session, edited: Project) => {
158
+ const {source} = session;
159
+ const result = projectChanges(source.project, session.baseline, edited, identity(session, edited));
160
+ const extensionSave = planExtensionSave(source, result ?? source.project);
161
+ const needed = projectAssets(extensionSave.project);
162
+ const added = [...needed].filter(([name]) => !source.bytes.has(name));
163
+ const removed = [...source.bytes.keys()].filter(name => !needed.has(name));
164
+ return {result, extensionSave, added, removed};
165
+ };
166
+ const loaded = () => setCurrent(null);
142
167
  vm.runtime.on('PROJECT_LOADED', loaded);
143
168
  vm.on('PROJECT_CHANGED', changed);
144
169
  const active = (session: Session) => {
@@ -148,13 +173,18 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
148
173
  };
149
174
  const dispose = () => {
150
175
  disposed = true;
151
- current = null;
176
+ setCurrent(null);
177
+ listeners.clear();
178
+ editListeners.clear();
152
179
  vm.runtime.off('PROJECT_LOADED', loaded);
153
180
  vm.off('PROJECT_CHANGED', changed);
154
181
  };
155
182
  const openFrom = async (
156
183
  getDirectory: () => Promise<FileSystemDirectoryHandle | null>,
157
- confirmReplace: () => boolean
184
+ confirmReplace: () => boolean,
185
+ prepare: (directory: FileSystemDirectoryHandle) => Promise<FolderSource | null> =
186
+ directory => readFolder(directory, vm.runtime.storage),
187
+ stillCurrent = () => true
158
188
  ): Promise<OpenResult> => {
159
189
  if (disposed || busy) return 'cancelled';
160
190
  busy = true;
@@ -163,11 +193,11 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
163
193
  const directory = await getDirectory();
164
194
  if (!directory || disposed) return 'cancelled';
165
195
  const storage = vm.runtime.storage;
166
- const source = await readFolder(directory, storage);
167
- if (disposed || vm.runtime.getTargetForStage() !== priorStage) return 'cancelled';
196
+ const source = await prepare(directory);
197
+ if (!source || disposed || !stillCurrent() || vm.runtime.getTargetForStage() !== priorStage) return 'cancelled';
168
198
  if (host.isProjectDirty() && !confirmReplace()) return 'cancelled';
169
199
  host.beforeLoad();
170
- current = null;
200
+ setCurrent(null);
171
201
  const reader = readerFor(storage);
172
202
  const assets = source.storageAssets;
173
203
  reader.assets = assets;
@@ -182,7 +212,7 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
182
212
  if (disposed || !stage || vm.runtime.getTargetForStage() !== stage) return 'cancelled';
183
213
  host.onOpened(directory.name);
184
214
  const baseline = snapshot();
185
- current = {source, stage, baseline, ids: identify(baseline), pending: null};
215
+ setCurrent({source, stage, baseline, ids: identify(baseline), pending: null});
186
216
  vm.renderer?.draw();
187
217
  return 'opened';
188
218
  } finally {
@@ -227,7 +257,34 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
227
257
  };
228
258
  const canApply = () => !host.isProjectDirty() && !host.blockReload?.isRunning();
229
259
  return {
230
- detach() {current = null;},
260
+ detach() {setCurrent(null);},
261
+ /** Calls `listener` when a folder opens or closes, and after a save. Returns the function that stops it. */
262
+ subscribe(listener: () => void) {
263
+ listeners.add(listener);
264
+ return () => {listeners.delete(listener);};
265
+ },
266
+ subscribeEdits(listener: () => void) {
267
+ editListeners.add(listener);
268
+ return () => {editListeners.delete(listener);};
269
+ },
270
+ /** Files affected by the pending save. A save in progress still owns its baseline. */
271
+ unsavedPaths(): ReadonlySet<string> | null {
272
+ if (busy) return null;
273
+ const paths = new Set<string>();
274
+ if (!current) return paths;
275
+ try {
276
+ const {result, extensionSave, added, removed} = planSave(current, snapshot());
277
+ if (result) paths.add(projectFile);
278
+ if (extensionSave.manifestChanged) paths.add(extensionsFile);
279
+ if (added.length || removed.length) paths.add(manifestFile);
280
+ for (const name of [...added.map(([name]) => name), ...removed]) paths.add(`assets/${name}`);
281
+ for (const name of [...extensionSave.writes.keys(), ...extensionSave.removed]) paths.add(`extensions/${name}`);
282
+ } catch (error) {
283
+ if (!(error instanceof FolderError)) throw error;
284
+ if (host.isProjectDirty()) paths.add(projectFile);
285
+ }
286
+ return paths;
287
+ },
231
288
  get canSave() {return current !== null;},
232
289
  get busy() {return busy;},
233
290
  get reloadState() {return reloadState();},
@@ -248,6 +305,19 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
248
305
  return typeof pending === 'object' && pending !== null ? pending.update.version : null;
249
306
  },
250
307
  get directory() {return current?.source.directory ?? null;},
308
+ async mutate(directory: FileSystemDirectoryHandle, operation: (guard: () => void) => Promise<void>) {
309
+ const session = current;
310
+ if (!session || busy || session.source.directory !== directory) throw new FolderError('conflict');
311
+ const guard = () => active(session);
312
+ guard();
313
+ busy = true;
314
+ try {
315
+ await operation(guard);
316
+ } finally {
317
+ busy = false;
318
+ if (current === session) notify();
319
+ }
320
+ },
251
321
  /**
252
322
  * Reads what to compare before unsaved edits are replaced. `editor` is `null` when the edits cannot be
253
323
  * written to the folder, and `disk` when the folder's project file cannot be read.
@@ -316,9 +386,11 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
316
386
  session.source.versions.set(projectFile, pending.update.version);
317
387
  session.pending = null;
318
388
  host.blockReload.onApplied(targets);
389
+ notify();
319
390
  return true;
320
391
  } finally {
321
392
  busy = false;
393
+ notifyEdits();
322
394
  }
323
395
  },
324
396
  /**
@@ -345,6 +417,20 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
345
417
  openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean): Promise<OpenResult> {
346
418
  return openFrom(() => Promise.resolve(directory), confirmReplace);
347
419
  },
420
+ createFromSnapshot(getDirectory: () => Promise<FileSystemDirectoryHandle | null>,
421
+ prepareFiles: () => Promise<ReadonlyMap<string, Uint8Array>>, isCurrent: () => boolean): Promise<OpenResult> {
422
+ const stage = vm.runtime.getTargetForStage();
423
+ let savedRevision: number | undefined;
424
+ const currentProject = () => !disposed && vm.runtime.getTargetForStage() === stage &&
425
+ (savedRevision === undefined || revision === savedRevision) && isCurrent();
426
+ return openFrom(getDirectory, currentProject, async directory => {
427
+ if (!currentProject()) return null;
428
+ savedRevision = revision;
429
+ const files = await prepareFiles();
430
+ if (!currentProject()) return null;
431
+ return createProjectFolder({directory, files, storage: vm.runtime.storage, current: currentProject});
432
+ }, currentProject);
433
+ },
348
434
  async save(): Promise<SaveResult> {
349
435
  if (!current || busy) throw new FolderError('conflict');
350
436
  const session = current;
@@ -354,25 +440,22 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
354
440
  const saveRevision = revision;
355
441
  const edited = snapshot();
356
442
  const ids = identify(edited);
357
- const result = projectChanges(session.source.project, session.baseline, edited, identity(session, edited));
443
+ const {result, extensionSave, added: newAssets, removed} = planSave(session, edited);
358
444
  await assertFolderUnchanged(session.source);
359
445
  active(session);
360
446
  const {source} = session;
361
- const extensionSave = planExtensionSave(source, result ?? source.project);
362
- const needed = projectAssets(extensionSave.project);
363
447
  const added = new Map<string, Uint8Array>();
364
- for (const [name, kind] of needed) {
365
- if (source.bytes.has(name)) continue;
366
- const data = assetData(name);
448
+ for (const [name, kind] of newAssets) {
449
+ const data = assetData(name, kind);
367
450
  if (!data) return unsupported(`The data of ${name} is not in the Editor`);
368
451
  const [id, format] = name.split('.');
369
452
  const asset = vm.runtime.storage.createAsset(assetTypeFor(vm.runtime.storage, kind, format), format, data.slice(), null, true);
370
453
  if (asset.assetId !== id) return unsupported(`Asset hash mismatch: ${name}`);
371
454
  added.set(name, data);
372
455
  }
373
- const removed = [...source.bytes.keys()].filter(name => !needed.has(name));
374
456
  if (!result && !removed.length && !extensionSave.removed.length) {
375
457
  if (revision === saveRevision) host.onSaved();
458
+ notify();
376
459
  return {status: 'unchanged', sourceRemoved: []};
377
460
  }
378
461
  const encoder = new TextEncoder();
@@ -384,8 +467,8 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
384
467
  manifest = encoder.encode(`${JSON.stringify(value, null, 2)}\n`);
385
468
  }
386
469
  const root = {directory: source.directory, files: source.files, prefix: ''};
387
- const assets = {directory: await source.directory.getDirectoryHandle('assets'), files: source.bytes, prefix: 'assets/'};
388
- const extensions = {directory: await source.directory.getDirectoryHandle('extensions'),
470
+ const assets = {directory: await source.directory.getDirectoryHandle('assets', {create: true}), files: source.bytes, prefix: 'assets/'};
471
+ const extensions = {directory: await source.directory.getDirectoryHandle('extensions', {create: true}),
389
472
  files: source.extensionBytes, prefix: 'extensions/'};
390
473
  const undo: (() => Promise<void>)[] = [];
391
474
  const write = async ({directory, files, prefix}: SaveDirectory, name: string, data: Uint8Array) => {
@@ -466,9 +549,11 @@ export function createFolderSession(vm: FolderVM, host: FolderHost) {
466
549
  session.ids = ids;
467
550
  session.pending = null;
468
551
  if (current === session && revision === saveRevision) host.onSaved();
552
+ notify();
469
553
  return {status: 'saved', sourceRemoved: extensionSave.sourceRemoved};
470
554
  } finally {
471
555
  busy = false;
556
+ notifyEdits();
472
557
  }
473
558
  },
474
559
  dispose
package/src/source.ts CHANGED
@@ -48,7 +48,7 @@ export function parseProject(text: string): Project {
48
48
  export interface AssetType {name: string}
49
49
  export interface Asset {assetId: string; dataFormat: string; data: Uint8Array}
50
50
  export interface Storage {
51
- AssetType: {Sound: AssetType; ImageVector: AssetType; ImageBitmap: AssetType};
51
+ AssetType: {Sound: AssetType; ImageVector: AssetType; ImageBitmap: AssetType; Font?: AssetType};
52
52
  createAsset(type: AssetType, format: string, data: Uint8Array, id: null, generateId: true): Asset;
53
53
  addHelper(helper: {load(type: AssetType, id: string, format: string): Promise<Asset> | null}, priority: number): void;
54
54
  }
@@ -67,12 +67,14 @@ export type FolderSource = FolderFiles & {
67
67
  embedded: ExtensionManifest;
68
68
  };
69
69
 
70
- const getFile = async (dir: FileSystemDirectoryHandle, name: string) => (await dir.getFileHandle(name)).getFile();
70
+ const getFile = async (dir: FileSystemDirectoryHandle | null, name: string) =>
71
+ dir ? (await dir.getFileHandle(name)).getFile() : unsupported(`Missing folder for ${name}`);
71
72
  export const fileVersion = (file: File) => `${file.size}:${file.lastModified}`;
72
73
  const fileBytes = async (file: File) => new Uint8Array(await file.arrayBuffer());
73
- const readBytes = async (dir: FileSystemDirectoryHandle, name: string) => fileBytes(await getFile(dir, name));
74
- const readNames = async (dir: FileSystemDirectoryHandle) => {
74
+ const readBytes = async (dir: FileSystemDirectoryHandle | null, name: string) => fileBytes(await getFile(dir, name));
75
+ const readNames = async (dir: FileSystemDirectoryHandle | null) => {
75
76
  const names = new Set<string>();
77
+ if (!dir) return names;
76
78
  // Directory iteration is available alongside the picker, but absent from older DOM typings.
77
79
  for await (const entry of (dir as FileSystemDirectoryHandle & {values(): AsyncIterable<FileSystemHandle>}).values()) {
78
80
  if (entry.kind !== 'file') return unsupported('Nested entries are outside the supported source format');
@@ -80,13 +82,23 @@ const readNames = async (dir: FileSystemDirectoryHandle) => {
80
82
  }
81
83
  return names;
82
84
  };
85
+ // Git does not retain empty asset or extension directories.
86
+ const readDirectory = (dir: FileSystemDirectoryHandle, name: string) => dir.getDirectoryHandle(name).catch(error => {
87
+ if (error instanceof DOMException && error.name === 'NotFoundError') return null;
88
+ throw error;
89
+ });
83
90
  const sameNames = (actual: Set<string>, expected: Iterable<string>) => {
84
91
  const expectedNames = new Set(expected);
85
92
  return actual.size === expectedNames.size && [...actual].every(name => expectedNames.has(name));
86
93
  };
87
94
 
88
- export const assetTypeFor = (storage: Storage, kind: 'costumes' | 'sounds', format: string) => kind === 'sounds' ?
89
- storage.AssetType.Sound : format === 'svg' ? storage.AssetType.ImageVector : storage.AssetType.ImageBitmap;
95
+ export type AssetKind = 'costumes' | 'sounds' | 'fonts';
96
+
97
+ export const assetTypeFor = (storage: Storage, kind: AssetKind, format: string): AssetType => {
98
+ if (kind === 'fonts') return storage.AssetType.Font ?? unsupported('The editor does not support font assets');
99
+ if (kind === 'sounds') return storage.AssetType.Sound;
100
+ return format === 'svg' ? storage.AssetType.ImageVector : storage.AssetType.ImageBitmap;
101
+ };
90
102
  export const assetKey = (type: AssetType, id: string, format: string) => `${type.name}/${id}.${format}`;
91
103
 
92
104
  type DataUrlMetadata = {mediaType: string; parameters: string[]; encoding: 'base64' | 'percent'};
@@ -262,7 +274,7 @@ export function planExtensionSave(source: FolderSource, project: Project) {
262
274
 
263
275
  export async function readFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource> {
264
276
  const versions = new Map<string, string>();
265
- const readEntry = async (dir: FileSystemDirectoryHandle, name: string, prefix = '') => {
277
+ const readEntry = async (dir: FileSystemDirectoryHandle | null, name: string, prefix = '') => {
266
278
  const file = await getFile(dir, name);
267
279
  versions.set(prefix + name, fileVersion(file));
268
280
  return [name, await fileBytes(file)] as const;
@@ -278,34 +290,15 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
278
290
  manifest.assetsDirectory !== 'assets' || !Array.isArray(manifest.archiveEntries)) {
279
291
  return unsupported('Expected an sb3-toolchain v1 folder');
280
292
  }
281
- if (customContent(project)) return unsupported('Plus extension manifests and custom fonts are not supported in project folders');
293
+ if (project.turboWarpPlus !== undefined) return unsupported('Plus extension manifests are not supported in project folders');
282
294
  const extensionManifest = validateExtensions(project, embedded);
283
- const expected = new Set(['project.json']);
284
- const references = new Map<string, {id: string; format: string; type: AssetType; name: string}>();
285
- for (const target of project.targets) {
286
- for (const kind of ['costumes', 'sounds'] as const) {
287
- const entries = target[kind] ?? [];
288
- if (!Array.isArray(entries)) return unsupported('Invalid asset list');
289
- for (const entry of entries) {
290
- if (!isObject(entry) || typeof entry.assetId !== 'string' || !/^[a-f0-9]{32}$/u.test(entry.assetId) ||
291
- typeof entry.dataFormat !== 'string') return unsupported('Invalid asset reference');
292
- const {assetId: id, dataFormat: format} = entry;
293
- const name = `${id}.${format}`;
294
- const type = kind === 'sounds' ?
295
- (/^(wav|mp3)$/u.test(format) ? storage.AssetType.Sound : null) :
296
- (format === 'svg' ? storage.AssetType.ImageVector :
297
- (/^(png|bmp|jpg|jpeg|gif)$/u.test(format) ? storage.AssetType.ImageBitmap : null));
298
- if (!type || entry.md5ext !== name) return unsupported(`Unsupported asset reference: ${name}`);
299
- expected.add(name);
300
- references.set(assetKey(type, id, format), {id, format, type, name});
301
- }
302
- }
303
- }
295
+ const references = projectAssets(project);
296
+ const expected = new Set(['project.json', ...references.keys()]);
304
297
  if (manifest.archiveEntries.length !== expected.size || !sameNames(new Set(manifest.archiveEntries as string[]), expected)) {
305
298
  return unsupported('Asset references and archiveEntries do not match');
306
299
  }
307
300
  expected.delete('project.json');
308
- const [assets, extensions] = await Promise.all([directory.getDirectoryHandle('assets'), directory.getDirectoryHandle('extensions')]);
301
+ const [assets, extensions] = await Promise.all([readDirectory(directory, 'assets'), readDirectory(directory, 'extensions')]);
309
302
  const scripts = extensionNames(extensionManifest.extensions);
310
303
  if (!sameNames(await readNames(assets), expected) || !sameNames(await readNames(extensions), scripts)) {
311
304
  return unsupported('Unexpected or missing source files');
@@ -318,10 +311,12 @@ export async function readFolder(directory: FileSystemDirectoryHandle, storage:
318
311
  [entry.id, encodeDataUrl(entry, extensionBytes.get(`${entry.id}.js`)!)]))
319
312
  }}) : projectText;
320
313
  const storageAssets = new Map<string, Asset>();
321
- for (const [key, {id, format, type, name}] of references) {
314
+ for (const [name, kind] of references) {
315
+ const [id, format] = name.split('.');
316
+ const type = assetTypeFor(storage, kind, format);
322
317
  const asset = storage.createAsset(type, format, bytes.get(name)!.slice(), null, true);
323
318
  if (asset.assetId !== id) return unsupported(`Asset hash mismatch: ${name}`);
324
- storageAssets.set(key, asset);
319
+ storageAssets.set(assetKey(type, id, format), asset);
325
320
  }
326
321
  return {versions, files, directory, bytes, extensionBytes, project, loadText, storageAssets, embedded: extensionManifest};
327
322
  }
@@ -337,7 +332,7 @@ export async function readFolderUpdate(source: FolderSource, previous: FolderUpd
337
332
  const {directory, versions} = source;
338
333
  try {
339
334
  const [assets, extensions, project] = await Promise.all([
340
- directory.getDirectoryHandle('assets'), directory.getDirectoryHandle('extensions'), getFile(directory, projectFile)
335
+ readDirectory(directory, 'assets'), readDirectory(directory, 'extensions'), getFile(directory, projectFile)
341
336
  ]);
342
337
  const [assetNames, extensionNames] = await Promise.all([readNames(assets), readNames(extensions)]);
343
338
  if (!sameNames(assetNames, source.bytes.keys()) || !sameNames(extensionNames, source.extensionBytes.keys())) return 'structure';
@@ -368,8 +363,9 @@ export async function readFolderUpdate(source: FolderSource, previous: FolderUpd
368
363
 
369
364
  export async function assertFolderUnchanged(source: FolderSource) {
370
365
  try {
371
- const assets = await source.directory.getDirectoryHandle('assets');
372
- const extensions = await source.directory.getDirectoryHandle('extensions');
366
+ const [assets, extensions] = await Promise.all([
367
+ readDirectory(source.directory, 'assets'), readDirectory(source.directory, 'extensions')
368
+ ]);
373
369
  if (!sameNames(await readNames(assets), source.bytes.keys()) ||
374
370
  !sameNames(await readNames(extensions), source.extensionBytes.keys())) throw new FolderError('conflict');
375
371
  for (const [directory, files] of [[source.directory, source.files], [assets, source.bytes], [extensions, source.extensionBytes]] as const) {
@@ -423,7 +419,7 @@ const applyChanges = (source: Json | undefined, before: Json, after: Json): Json
423
419
 
424
420
  /** The asset files a project refers to, by file name, with the kind of list that refers to each. */
425
421
  export const projectAssets = (project: Project) => {
426
- const names = new Map<string, 'costumes' | 'sounds'>();
422
+ const names = new Map<string, AssetKind>();
427
423
  for (const target of project.targets) {
428
424
  for (const kind of ['costumes', 'sounds'] as const) {
429
425
  const entries = target[kind] ?? [];
@@ -440,9 +436,17 @@ export const projectAssets = (project: Project) => {
440
436
  }
441
437
  }
442
438
  }
439
+ const fonts = project.customFonts ?? [];
440
+ if (!Array.isArray(fonts)) return unsupported('Invalid customFonts list');
441
+ for (const font of fonts) {
442
+ if (!isObject(font) || font.system !== false || font.md5ext === undefined) continue;
443
+ if (typeof font.md5ext !== 'string' || !/^[a-f0-9]{32}\.(ttf|otf|woff2?)$/u.test(font.md5ext)) {
444
+ return unsupported('Invalid font asset reference');
445
+ }
446
+ names.set(font.md5ext, 'fonts');
447
+ }
443
448
  return names;
444
449
  };
445
- const customContent = (project: Project) => project.turboWarpPlus !== undefined || project.customFonts !== undefined;
446
450
 
447
451
  /** Runtime ids of the targets, in the order of the project's `targets`, so a renamed sprite stays the same sprite. */
448
452
  export type TargetIdentity = {before: readonly string[]; after: readonly string[]};
@@ -460,7 +464,7 @@ export function projectChanges(source: Project, before: Project, after: Project,
460
464
  return unsupported('The targets could not be identified');
461
465
  }
462
466
  projectAssets(after);
463
- if (customContent(after)) return unsupported('Plus extension manifests and custom fonts are not saved to a project folder');
467
+ if (after.turboWarpPlus !== undefined) return unsupported('Plus extension manifests are not saved to a project folder');
464
468
  if (equal(before, after) && equal([...beforeIds], [...afterIds])) return null;
465
469
  const {targets: sourceTargets, ...sourceOther} = source;
466
470
  const {targets: beforeTargets, ...beforeOther} = before;