@kubohiroya/turbowarp-plus-editor-project-folder 0.0.0-stage → 0.2.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/src/session.ts ADDED
@@ -0,0 +1,277 @@
1
+ import {assetKey, assertFolderUnchanged, FolderError, parseProject, projectChanges, projectFile, readFolder, readFolderUpdate} from './source.js';
2
+ import type {Asset, FolderSource, FolderUpdate, Project, Storage} from './source.js';
3
+ import {applyBlockReload, planBlockReload} from './block-reload.js';
4
+ import type {ReloadTarget} from './block-reload.js';
5
+
6
+ export interface FolderVM {
7
+ runtime: {
8
+ storage: Storage;
9
+ targets?: readonly ReloadTarget[];
10
+ getTargetForStage(): object | null;
11
+ on(event: 'PROJECT_LOADED', listener: () => void): void;
12
+ off(event: 'PROJECT_LOADED', listener: () => void): void;
13
+ };
14
+ on(event: 'PROJECT_CHANGED', listener: () => void): void;
15
+ off(event: 'PROJECT_CHANGED', listener: () => void): void;
16
+ quit(): void;
17
+ loadProject(project: string): Promise<unknown>;
18
+ toJSON(target?: string, options?: {allowOptimization: boolean}): string;
19
+ renderer?: {draw(): void};
20
+ }
21
+
22
+ type FileSystemPicker = (options: {id: string; mode: 'readwrite'}) => Promise<FileSystemDirectoryHandle>;
23
+ export type PickerWindow = Window & {showDirectoryPicker?: FileSystemPicker};
24
+
25
+ const storageReaders = new WeakMap<Storage, {assets: Map<string, Asset> | null}>();
26
+ const readerFor = (storage: Storage) => {
27
+ const existing = storageReaders.get(storage);
28
+ if (existing) return existing;
29
+ const reader: {assets: Map<string, Asset> | null} = {assets: null};
30
+ storage.addHelper({load(type, id, format) {
31
+ const asset = reader.assets?.get(assetKey(type, id, format));
32
+ return asset ? Promise.resolve(asset) : null;
33
+ }}, 101);
34
+ storageReaders.set(storage, reader);
35
+ return reader;
36
+ };
37
+
38
+ export interface FolderHost {
39
+ isProjectDirty(): boolean;
40
+ beforeLoad(): void;
41
+ onOpened(title: string): void;
42
+ onSaved(): void;
43
+ blockReload?: {
44
+ isRunning(): boolean;
45
+ subscribe(listener: () => void): () => void;
46
+ onApplied(targets: readonly ReloadTarget[]): void;
47
+ };
48
+ }
49
+
50
+ // `stable` turns true once two scans see the same file version, so consecutive writes settle before auto-apply.
51
+ type PendingUpdate = {update: FolderUpdate; edits: ReturnType<typeof planBlockReload> | null; stable: boolean};
52
+ type Pending = PendingUpdate | 'structure' | 'waiting';
53
+ type Session = {source: FolderSource; baseline: Project; stage: object; pending: Pending | null};
54
+ /**
55
+ * `ready`: values and positions can be applied in place. `full`: the change needs the whole project reloaded.
56
+ * `waiting`: an external write looks incomplete and is checked again. `dirty`, `running` and `busy` hold the change.
57
+ */
58
+ export type ReloadState = 'ready' | 'full' | 'waiting' | 'dirty' | 'running' | 'busy' | null;
59
+ /** What the reload command does for the pending change, regardless of whether it may run now. */
60
+ export type ReloadKind = 'partial' | 'full' | null;
61
+ export type OpenResult = 'opened' | 'cancelled';
62
+ export type SaveResult = 'saved' | 'unchanged';
63
+
64
+ export function createFolderSession(vm: FolderVM, host: FolderHost) {
65
+ let current: Session | null = null;
66
+ let busy = false;
67
+ let disposed = false;
68
+ let revision = 0;
69
+ let scanning: Promise<void> | null = null;
70
+ const snapshot = () => parseProject(vm.toJSON(undefined, {allowOptimization: false}));
71
+ const changed = () => {revision++;};
72
+ const loaded = () => {current = null;};
73
+ vm.runtime.on('PROJECT_LOADED', loaded);
74
+ vm.on('PROJECT_CHANGED', changed);
75
+ const active = (session: Session) => {
76
+ if (disposed || current !== session || vm.runtime.getTargetForStage() !== session.stage) {
77
+ throw new FolderError('conflict');
78
+ }
79
+ };
80
+ const dispose = () => {
81
+ disposed = true;
82
+ current = null;
83
+ vm.runtime.off('PROJECT_LOADED', loaded);
84
+ vm.off('PROJECT_CHANGED', changed);
85
+ };
86
+ const openFrom = async (
87
+ getDirectory: () => Promise<FileSystemDirectoryHandle | null>,
88
+ confirmReplace: () => boolean
89
+ ): Promise<OpenResult> => {
90
+ if (disposed || busy) return 'cancelled';
91
+ busy = true;
92
+ const priorStage = vm.runtime.getTargetForStage();
93
+ try {
94
+ const directory = await getDirectory();
95
+ if (!directory || disposed) return 'cancelled';
96
+ const storage = vm.runtime.storage;
97
+ const source = await readFolder(directory, storage);
98
+ if (disposed || vm.runtime.getTargetForStage() !== priorStage) return 'cancelled';
99
+ if (host.isProjectDirty() && !confirmReplace()) return 'cancelled';
100
+ host.beforeLoad();
101
+ current = null;
102
+ const reader = readerFor(storage);
103
+ const assets = source.storageAssets;
104
+ reader.assets = assets;
105
+ let stage: object | null;
106
+ try {
107
+ vm.quit();
108
+ await vm.loadProject(source.projectText);
109
+ stage = vm.runtime.getTargetForStage();
110
+ } finally {
111
+ if (reader.assets === assets) reader.assets = null;
112
+ }
113
+ if (disposed || !stage || vm.runtime.getTargetForStage() !== stage) return 'cancelled';
114
+ host.onOpened(directory.name);
115
+ current = {source, stage, baseline: snapshot(), pending: null};
116
+ vm.renderer?.draw();
117
+ return 'opened';
118
+ } finally {
119
+ busy = false;
120
+ }
121
+ };
122
+ const readUpdate = async (session: Session): Promise<Session['pending']> => {
123
+ const previous = typeof session.pending === 'object' ? session.pending : null;
124
+ const update = await readFolderUpdate(session.source, previous?.update ?? null);
125
+ if (!update || typeof update === 'string') return update;
126
+ if (previous?.update === update) return {...previous, stable: true};
127
+ try {
128
+ return {update, edits: planBlockReload(session.source.project, update.project), stable: false};
129
+ } catch (error) {
130
+ if (!(error instanceof FolderError)) throw error;
131
+ return {update, edits: null, stable: false};
132
+ }
133
+ };
134
+ const reloadKind = (): ReloadKind => {
135
+ const pending = current?.pending;
136
+ if (!pending || pending === 'waiting') return null;
137
+ return pending === 'structure' || pending.edits === null ? 'full' : 'partial';
138
+ };
139
+ const reloadState = (): ReloadState => {
140
+ const pending = current?.pending;
141
+ if (!pending) return null;
142
+ if (busy) return 'busy';
143
+ if (pending === 'waiting') return 'waiting';
144
+ if (host.isProjectDirty()) return 'dirty';
145
+ if (host.blockReload?.isRunning()) return 'running';
146
+ return reloadKind() === 'full' ? 'full' : 'ready';
147
+ };
148
+ const canApply = () => !host.isProjectDirty() && !host.blockReload?.isRunning();
149
+ return {
150
+ detach() {current = null;},
151
+ get canSave() {return current !== null;},
152
+ get busy() {return busy;},
153
+ get reloadState() {return reloadState();},
154
+ get reloadKind() {return reloadKind();},
155
+ /** A partial change that has stayed the same across two scans and may be applied without asking. */
156
+ get canAutoReload() {
157
+ const pending = current?.pending;
158
+ return reloadState() === 'ready' && typeof pending === 'object' && pending !== null && pending.stable;
159
+ },
160
+ /** True while a change is new or looks incomplete, so a host can look again sooner than its interval. */
161
+ get settling() {
162
+ const pending = current?.pending;
163
+ return pending === 'waiting' || (typeof pending === 'object' && pending !== null && !pending.stable);
164
+ },
165
+ /** Identifies the pending project file version, so a host can attempt an automatic apply only once. */
166
+ get pendingVersion() {
167
+ const pending = current?.pending;
168
+ return typeof pending === 'object' && pending !== null ? pending.update.version : null;
169
+ },
170
+ get directory() {return current?.source.directory ?? null;},
171
+ refresh(): Promise<void> {
172
+ if (disposed || busy || !current || !host.blockReload) return Promise.resolve();
173
+ if (scanning) return scanning;
174
+ const session = current;
175
+ const baseline = session.baseline;
176
+ scanning = readUpdate(session).then(pending => {
177
+ if (current === session && session.baseline === baseline && !busy) session.pending = pending;
178
+ }).finally(() => {scanning = null;});
179
+ return scanning;
180
+ },
181
+ async reload(): Promise<boolean> {
182
+ if (!current || reloadState() !== 'ready' || !host.blockReload) return false;
183
+ const session = current;
184
+ active(session);
185
+ busy = true;
186
+ try {
187
+ const editRevision = revision;
188
+ const pending = await readUpdate(session);
189
+ if (current !== session || disposed || vm.runtime.getTargetForStage() !== session.stage) return false;
190
+ session.pending = pending;
191
+ if (!pending || typeof pending === 'string' || pending.edits === null || editRevision !== revision || !canApply()) {
192
+ return false;
193
+ }
194
+ let targets: readonly ReloadTarget[];
195
+ try {
196
+ targets = applyBlockReload(vm.runtime.targets ?? [], pending.edits);
197
+ } catch (error) {
198
+ if (error instanceof FolderError) session.pending = {...pending, edits: null};
199
+ throw error;
200
+ }
201
+ session.baseline = snapshot();
202
+ session.source.project = pending.update.project;
203
+ session.source.files.set(projectFile, pending.update.bytes);
204
+ session.source.versions.set(projectFile, pending.update.version);
205
+ session.pending = null;
206
+ host.blockReload.onApplied(targets);
207
+ return true;
208
+ } finally {
209
+ busy = false;
210
+ }
211
+ },
212
+ /**
213
+ * Reads the open folder again and replaces the project, for changes a partial reload cannot apply. Unsaved
214
+ * edits are discarded only when `confirmReplace` agrees. The VM is left untouched while a project runs.
215
+ */
216
+ reloadAll(confirmReplace: () => boolean): Promise<OpenResult> {
217
+ const session = current;
218
+ if (!session || !session.pending || session.pending === 'waiting' || host.blockReload?.isRunning()) {
219
+ return Promise.resolve('cancelled');
220
+ }
221
+ return openFrom(() => Promise.resolve(current === session ? session.source.directory : null), confirmReplace);
222
+ },
223
+ open(pick: FileSystemPicker, confirmReplace: () => boolean): Promise<OpenResult> {
224
+ return openFrom(async () => {
225
+ try {
226
+ return await pick({id: 'turbowarp-plus-project-folder', mode: 'readwrite'});
227
+ } catch (error) {
228
+ if (error instanceof DOMException && error.name === 'AbortError') return null;
229
+ throw error;
230
+ }
231
+ }, confirmReplace);
232
+ },
233
+ openDirectory(directory: FileSystemDirectoryHandle, confirmReplace: () => boolean): Promise<OpenResult> {
234
+ return openFrom(() => Promise.resolve(directory), confirmReplace);
235
+ },
236
+ async save(): Promise<SaveResult> {
237
+ if (!current || busy) throw new FolderError('conflict');
238
+ const session = current;
239
+ active(session);
240
+ busy = true;
241
+ try {
242
+ const saveRevision = revision;
243
+ const edited = snapshot();
244
+ const result = projectChanges(session.source.project, session.baseline, edited);
245
+ await assertFolderUnchanged(session.source);
246
+ active(session);
247
+ if (!result) {
248
+ if (revision === saveRevision) host.onSaved();
249
+ return 'unchanged';
250
+ }
251
+ const text = `${JSON.stringify(result, null, 2)}\n`;
252
+ const file = await session.source.directory.getFileHandle(projectFile);
253
+ const options = {mode: 'exclusive'} as FileSystemCreateWritableOptions;
254
+ const writable = await file.createWritable(options);
255
+ try {
256
+ await writable.write(text);
257
+ await assertFolderUnchanged(session.source);
258
+ active(session);
259
+ await writable.close();
260
+ } catch (error) {
261
+ await writable.abort().catch(() => {});
262
+ throw error;
263
+ }
264
+ session.source.project = result;
265
+ session.source.files.set(projectFile, new TextEncoder().encode(text));
266
+ session.source.versions.delete(projectFile);
267
+ session.baseline = edited;
268
+ session.pending = null;
269
+ if (current === session && revision === saveRevision) host.onSaved();
270
+ return 'saved';
271
+ } finally {
272
+ busy = false;
273
+ }
274
+ },
275
+ dispose
276
+ };
277
+ }
package/src/source.ts ADDED
@@ -0,0 +1,256 @@
1
+ export type Json = null | boolean | number | string | Json[] | {[key: string]: Json};
2
+ export type JsonObject = {[key: string]: Json};
3
+ export type Project = JsonObject & {targets: Target[]};
4
+ type Target = JsonObject & {isStage: boolean; name: string};
5
+
6
+ export const projectFile = 'project.source.json';
7
+ const manifestFile = 'sb3-source.json';
8
+ const extensionsFile = 'embedded-extensions.json';
9
+
10
+ export class FolderError extends Error {
11
+ code: 'conflict' | 'unsupported';
12
+ constructor(code: FolderError['code'], detail?: string) {
13
+ super(detail ?? code);
14
+ this.code = code;
15
+ }
16
+ }
17
+
18
+ export const unsupported = (detail: string): never => {throw new FolderError('unsupported', detail);};
19
+ export const isObject = (value: Json | undefined): value is JsonObject => value !== null && typeof value === 'object' && !Array.isArray(value);
20
+ const readObject = (text: string): JsonObject => {
21
+ const value = JSON.parse(text);
22
+ if (!isObject(value)) return unsupported('Expected a JSON object');
23
+ return value;
24
+ };
25
+ const targetKey = (target: Target) => target.isStage ? 'stage' : `sprite:${target.name}`;
26
+
27
+ export function parseProject(text: string): Project {
28
+ const project = readObject(text);
29
+ if (!Array.isArray(project.targets)) return unsupported('Missing targets');
30
+ const keys = new Set<string>();
31
+ let stages = 0;
32
+ for (const target of project.targets) {
33
+ if (!isObject(target) || typeof target.isStage !== 'boolean' || typeof target.name !== 'string') {
34
+ return unsupported('Invalid target');
35
+ }
36
+ const key = targetKey(target as Target);
37
+ if (keys.has(key)) return unsupported('Ambiguous target names');
38
+ keys.add(key);
39
+ if (target.isStage) stages++;
40
+ if (target.blocks !== undefined && !isObject(target.blocks)) return unsupported('Invalid blocks');
41
+ if (target.comments !== undefined && !isObject(target.comments)) return unsupported('Invalid comments');
42
+ }
43
+ if (stages !== 1) return unsupported('Expected one stage');
44
+ return project as Project;
45
+ }
46
+
47
+ export interface AssetType {name: string}
48
+ export interface Asset {assetId: string; dataFormat: string; data: Uint8Array}
49
+ export interface Storage {
50
+ AssetType: {Sound: AssetType; ImageVector: AssetType; ImageBitmap: AssetType};
51
+ createAsset(type: AssetType, format: string, data: Uint8Array, id: null, generateId: true): Asset;
52
+ addHelper(helper: {load(type: AssetType, id: string, format: string): Promise<Asset> | null}, priority: number): void;
53
+ }
54
+
55
+ type FolderFiles = {
56
+ versions: Map<string, string>;
57
+ files: Map<string, Uint8Array>;
58
+ directory: FileSystemDirectoryHandle;
59
+ bytes: Map<string, Uint8Array>;
60
+ };
61
+ export type FolderSource = FolderFiles & {project: Project; projectText: string; storageAssets: Map<string, Asset>};
62
+
63
+ const getFile = async (dir: FileSystemDirectoryHandle, name: string) => (await dir.getFileHandle(name)).getFile();
64
+ const fileVersion = (file: File) => `${file.size}:${file.lastModified}`;
65
+ const fileBytes = async (file: File) => new Uint8Array(await file.arrayBuffer());
66
+ const readBytes = async (dir: FileSystemDirectoryHandle, name: string) => fileBytes(await getFile(dir, name));
67
+ const readNames = async (dir: FileSystemDirectoryHandle) => {
68
+ const names = new Set<string>();
69
+ // Directory iteration is available alongside the picker, but absent from older DOM typings.
70
+ for await (const entry of (dir as FileSystemDirectoryHandle & {values(): AsyncIterable<FileSystemHandle>}).values()) {
71
+ if (entry.kind !== 'file') return unsupported('Nested entries are outside the supported source format');
72
+ names.add(entry.name);
73
+ }
74
+ return names;
75
+ };
76
+ const sameNames = (actual: Set<string>, expected: Iterable<string>) => {
77
+ const expectedNames = new Set(expected);
78
+ return actual.size === expectedNames.size && [...actual].every(name => expectedNames.has(name));
79
+ };
80
+
81
+ export const assetKey = (type: AssetType, id: string, format: string) => `${type.name}/${id}.${format}`;
82
+
83
+ export async function readFolder(directory: FileSystemDirectoryHandle, storage: Storage): Promise<FolderSource> {
84
+ const versions = new Map<string, string>();
85
+ const readEntry = async (dir: FileSystemDirectoryHandle, name: string, prefix = '') => {
86
+ const file = await getFile(dir, name);
87
+ versions.set(prefix + name, fileVersion(file));
88
+ return [name, await fileBytes(file)] as const;
89
+ };
90
+ const filenames = [projectFile, manifestFile, extensionsFile];
91
+ const files = new Map(await Promise.all(filenames.map(name => readEntry(directory, name))));
92
+ const decoder = new TextDecoder('utf-8', {fatal: true});
93
+ const projectText = decoder.decode(files.get(projectFile));
94
+ const project = parseProject(projectText);
95
+ const manifest = readObject(decoder.decode(files.get(manifestFile)));
96
+ const embedded = readObject(decoder.decode(files.get(extensionsFile)));
97
+ if (manifest.formatVersion !== 1 || manifest.project !== projectFile || manifest.embeddedExtensions !== extensionsFile ||
98
+ manifest.assetsDirectory !== 'assets' || !Array.isArray(manifest.archiveEntries)) {
99
+ return unsupported('Expected an sb3-toolchain v1 folder');
100
+ }
101
+ if (embedded.formatVersion !== 1 || !Array.isArray(embedded.extensions) || embedded.extensions.length ||
102
+ (embedded.extensionBundles !== undefined && (!Array.isArray(embedded.extensionBundles) || embedded.extensionBundles.length)) ||
103
+ project.turboWarpPlus !== undefined || project.customFonts !== undefined ||
104
+ (project.extensionURLs !== undefined && (!isObject(project.extensionURLs) || Object.keys(project.extensionURLs).length))) {
105
+ return unsupported('Custom extensions and fonts are outside the prototype scope');
106
+ }
107
+ const expected = new Set(['project.json']);
108
+ const references = new Map<string, {id: string; format: string; type: AssetType; name: string}>();
109
+ for (const target of project.targets) {
110
+ for (const kind of ['costumes', 'sounds'] as const) {
111
+ const entries = target[kind] ?? [];
112
+ if (!Array.isArray(entries)) return unsupported('Invalid asset list');
113
+ for (const entry of entries) {
114
+ if (!isObject(entry) || typeof entry.assetId !== 'string' || !/^[a-f0-9]{32}$/u.test(entry.assetId) ||
115
+ typeof entry.dataFormat !== 'string') return unsupported('Invalid asset reference');
116
+ const {assetId: id, dataFormat: format} = entry;
117
+ const name = `${id}.${format}`;
118
+ const type = kind === 'sounds' ?
119
+ (/^(wav|mp3)$/u.test(format) ? storage.AssetType.Sound : null) :
120
+ (format === 'svg' ? storage.AssetType.ImageVector :
121
+ (/^(png|bmp|jpg|jpeg|gif)$/u.test(format) ? storage.AssetType.ImageBitmap : null));
122
+ if (!type || entry.md5ext !== name) return unsupported(`Unsupported asset reference: ${name}`);
123
+ expected.add(name);
124
+ references.set(assetKey(type, id, format), {id, format, type, name});
125
+ }
126
+ }
127
+ }
128
+ if (manifest.archiveEntries.length !== expected.size || !sameNames(new Set(manifest.archiveEntries as string[]), expected)) {
129
+ return unsupported('Asset references and archiveEntries do not match');
130
+ }
131
+ expected.delete('project.json');
132
+ const [assets, extensions] = await Promise.all([directory.getDirectoryHandle('assets'), directory.getDirectoryHandle('extensions')]);
133
+ if (!sameNames(await readNames(assets), expected) || (await readNames(extensions)).size) {
134
+ return unsupported('Unexpected or missing source files');
135
+ }
136
+ const bytes = new Map(await Promise.all([...expected].map(name => readEntry(assets, name, 'assets/'))));
137
+ const storageAssets = new Map<string, Asset>();
138
+ for (const [key, {id, format, type, name}] of references) {
139
+ const asset = storage.createAsset(type, format, bytes.get(name)!.slice(), null, true);
140
+ if (asset.assetId !== id) return unsupported(`Asset hash mismatch: ${name}`);
141
+ storageAssets.set(key, asset);
142
+ }
143
+ return {versions, files, directory, bytes, project, projectText, storageAssets};
144
+ }
145
+
146
+ const sameBytes = (a: Uint8Array, b: Uint8Array) => a.length === b.length && a.every((value, index) => value === b[index]);
147
+
148
+ export type FolderUpdate = {version: string; bytes: Uint8Array; project: Project};
149
+ export type DiskChange = FolderUpdate | 'structure' | 'waiting' | null;
150
+
151
+ // Metadata probes do not read file contents. Only a changed project JSON can be applied partially; changes to
152
+ // assets, the manifest or extensions report 'structure' so that the host can offer a whole reload instead.
153
+ export async function readFolderUpdate(source: FolderSource, previous: FolderUpdate | null): Promise<DiskChange> {
154
+ const {directory, versions} = source;
155
+ try {
156
+ const [assets, extensions, project] = await Promise.all([
157
+ directory.getDirectoryHandle('assets'), directory.getDirectoryHandle('extensions'), getFile(directory, projectFile)
158
+ ]);
159
+ const [assetNames, extensionNames] = await Promise.all([readNames(assets), readNames(extensions)]);
160
+ if (!sameNames(assetNames, source.bytes.keys()) || extensionNames.size) return 'structure';
161
+ const unchanged = await Promise.all([
162
+ ...[manifestFile, extensionsFile].map(async name => fileVersion(await getFile(directory, name)) === versions.get(name)),
163
+ ...[...assetNames].map(async name => fileVersion(await getFile(assets, name)) === versions.get(`assets/${name}`))
164
+ ]);
165
+ if (unchanged.includes(false)) return 'structure';
166
+ const version = fileVersion(project);
167
+ if (version === versions.get(projectFile)) return null;
168
+ if (previous?.version === version) return previous;
169
+ const bytes = await fileBytes(project);
170
+ // An editor may update the timestamp without changing the bytes, including our own save.
171
+ if (sameBytes(bytes, source.files.get(projectFile)!)) {
172
+ versions.set(projectFile, version);
173
+ return null;
174
+ }
175
+ return {version, bytes, project: parseProject(new TextDecoder('utf-8', {fatal: true}).decode(bytes))};
176
+ } catch (error) {
177
+ // Well-formed JSON outside the partial scope needs a whole reload. Anything else may be a write in
178
+ // progress, such as truncated JSON or a file replaced between the probe and the read, and is retried.
179
+ return error instanceof FolderError ? 'structure' : 'waiting';
180
+ }
181
+ }
182
+
183
+ export async function assertFolderUnchanged(source: FolderSource) {
184
+ try {
185
+ const assets = await source.directory.getDirectoryHandle('assets');
186
+ const extensions = await source.directory.getDirectoryHandle('extensions');
187
+ if (!sameNames(await readNames(assets), source.bytes.keys()) || (await readNames(extensions)).size) throw new FolderError('conflict');
188
+ for (const [name, bytes] of source.files) {
189
+ if (!sameBytes(await readBytes(source.directory, name), bytes)) throw new FolderError('conflict');
190
+ }
191
+ for (const [name, bytes] of source.bytes) {
192
+ if (!sameBytes(await readBytes(assets, name), bytes)) throw new FolderError('conflict');
193
+ }
194
+ } catch (error) {
195
+ if (error instanceof FolderError || (error instanceof DOMException && ['NotFoundError', 'TypeMismatchError'].includes(error.name))) {
196
+ throw new FolderError('conflict');
197
+ }
198
+ throw error;
199
+ }
200
+ }
201
+
202
+ export const equal = (left: Json | undefined, right: Json | undefined): boolean => {
203
+ if (left === right) return true;
204
+ if (Array.isArray(left) && Array.isArray(right)) {
205
+ return left.length === right.length && left.every((item, index) => equal(item, right[index]));
206
+ }
207
+ if (!isObject(left) || !isObject(right)) return false;
208
+ const keys = Object.keys(left);
209
+ return keys.length === Object.keys(right).length &&
210
+ keys.every(key => Object.hasOwn(right, key) && equal(left[key], right[key]));
211
+ };
212
+
213
+ const applyChanges = (source: Json | undefined, before: Json, after: Json): Json => {
214
+ if (equal(before, after)) return source === undefined ? after : source;
215
+ if (!isObject(before) || !isObject(after)) return after;
216
+ const result: JsonObject = Object.assign(Object.create(null), isObject(source) ? source : {});
217
+ for (const key of Object.keys(before)) {
218
+ if (!Object.hasOwn(after, key)) delete result[key];
219
+ else if (!equal(before[key], after[key])) {
220
+ result[key] = applyChanges(Object.hasOwn(result, key) ? result[key] : undefined, before[key], after[key]);
221
+ }
222
+ }
223
+ for (const key of Object.keys(after)) {
224
+ if (!Object.hasOwn(before, key)) result[key] = after[key];
225
+ }
226
+ return result;
227
+ };
228
+
229
+ export function projectChanges(source: Project, before: Project, after: Project): Project | null {
230
+ const {targets: beforeTargets, ...beforeOther} = before;
231
+ 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');
241
+ const key = targetKey(target);
242
+ const original = originalTargets.get(key);
243
+ 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
+ }
250
+ }
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
+ })};
256
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,16 @@
1
+ {
2
+ "compilerOptions": {
3
+ "target": "ES2017",
4
+ "lib": ["ES2023", "DOM", "DOM.Iterable"],
5
+ "module": "NodeNext",
6
+ "moduleResolution": "NodeNext",
7
+ "types": [],
8
+ "strict": true,
9
+ "verbatimModuleSyntax": true,
10
+ "declaration": true,
11
+ "emitDeclarationOnly": true,
12
+ "rootDir": "src",
13
+ "outDir": "dist"
14
+ },
15
+ "include": ["src/**/*.ts"]
16
+ }
package/vite.config.ts ADDED
@@ -0,0 +1,9 @@
1
+ import {defineConfig} from 'vite';
2
+
3
+ export default defineConfig({
4
+ build: {
5
+ // The pinned Scratch GUI still parses the library with Webpack 4.
6
+ target: 'es2017',
7
+ lib: {entry: 'src/index.ts', formats: ['es'], fileName: () => 'index.js'}
8
+ }
9
+ });