@kubohiroya/turbowarp-plus-editor-project-folder 0.9.1 → 0.9.3

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.
@@ -2,6 +2,7 @@ import {extensionsFile, fileVersion, FolderError, manifestFile, projectFile, rea
2
2
  import type {Storage} from './source.js';
3
3
 
4
4
  const manifests = new Set<string>([projectFile, manifestFile, extensionsFile]);
5
+ const sourceDirectories = ['assets', 'extensions'];
5
6
  const sourcePath = /^(?:assets\/[a-f0-9]{32}\.[A-Za-z0-9]+|extensions\/[A-Za-z0-9._-]+\.(?:js|manifest\.json))$/u;
6
7
 
7
8
  type IterableDirectory = FileSystemDirectoryHandle & {values(): AsyncIterable<FileSystemHandle>};
@@ -10,17 +11,28 @@ function missing(error: unknown) {
10
11
  return error instanceof DOMException && error.name === 'NotFoundError';
11
12
  }
12
13
 
13
- async function assertEmpty(directory: FileSystemDirectoryHandle) {
14
- for await (const _entry of (directory as IterableDirectory).values()) {
15
- throw new FolderError('conflict', 'Choose an empty project folder');
16
- }
14
+ export async function isProjectFolderEmpty(directory: FileSystemDirectoryHandle) {
15
+ for await (const _entry of (directory as IterableDirectory).values()) return false;
16
+ return true;
17
+ }
18
+
19
+ export function projectFolderOverwriteWarning(locale = 'en') {
20
+ return locale.startsWith('ja') ? '指定されたフォルダに保存されている内容は上書きされます' :
21
+ 'Contents in the selected folder will be overwritten.';
22
+ }
23
+
24
+ async function directoryEntries(directory: FileSystemDirectoryHandle) {
25
+ const entries = new Map<string, FileSystemHandle>();
26
+ for await (const entry of (directory as IterableDirectory).values()) entries.set(entry.name, entry);
27
+ return entries;
17
28
  }
18
29
 
19
30
  /** Create and validate a project-folder snapshot in a directory chosen by the user. */
20
- export async function createProjectFolder({directory, files, storage, current = () => true}: {
31
+ export async function createProjectFolder({directory, files, storage, overwrite = false, current = () => true}: {
21
32
  directory: FileSystemDirectoryHandle;
22
33
  files: ReadonlyMap<string, Uint8Array>;
23
34
  storage: Storage;
35
+ overwrite?: boolean;
24
36
  current?: () => boolean;
25
37
  }) {
26
38
  for (const filename of manifests) {
@@ -34,60 +46,120 @@ export async function createProjectFolder({directory, files, storage, current =
34
46
  const assertCurrent = () => {
35
47
  if (!current()) throw new FolderError('conflict', 'The project changed before the folder was saved');
36
48
  };
37
- await assertEmpty(directory);
38
- const directories = new Map<string, FileSystemDirectoryHandle>();
49
+ const existing = await directoryEntries(directory);
50
+ if (existing.size && !overwrite) throw new FolderError('conflict', 'The destination folder is no longer empty');
51
+ const directories = new Map<string, {handle: FileSystemDirectoryHandle; entries: Map<string, FileSystemHandle>}>();
39
52
  const undo: (() => Promise<void>)[] = [];
53
+ const getFile = (parent: FileSystemDirectoryHandle, name: string) => parent.getFileHandle(name).catch(error => {
54
+ if (missing(error)) return null;
55
+ throw error;
56
+ });
57
+ const getDirectory = (parent: FileSystemDirectoryHandle, name: string) => parent.getDirectoryHandle(name).catch(error => {
58
+ if (missing(error)) return null;
59
+ throw error;
60
+ });
61
+ const write = async (file: FileSystemFileHandle, data: Uint8Array, guard: () => void | Promise<void>) => {
62
+ const writable = await file.createWritable({mode: 'exclusive'} as FileSystemCreateWritableOptions);
63
+ try {
64
+ await writable.write(data as Uint8Array<ArrayBuffer>);
65
+ await guard();
66
+ await writable.close();
67
+ } catch (error) {
68
+ await writable.abort().catch(() => {});
69
+ throw error;
70
+ }
71
+ };
72
+ const remove = async (parent: FileSystemDirectoryHandle, entry: FileSystemHandle,
73
+ restoreParent = async () => parent): Promise<void> => {
74
+ const {name} = entry;
75
+ if (entry.kind === 'directory') {
76
+ const child = await getDirectory(parent, name);
77
+ if (!child || !await child.isSameEntry(entry)) throw new FolderError('conflict');
78
+ const restoreChild = async () => (await restoreParent()).getDirectoryHandle(name);
79
+ for (const nested of (await directoryEntries(child)).values()) await remove(child, nested, restoreChild);
80
+ assertCurrent();
81
+ await parent.removeEntry(name);
82
+ undo.push(async () => {await (await restoreParent()).getDirectoryHandle(name, {create: true});});
83
+ } else {
84
+ const file = await getFile(parent, name);
85
+ if (!file || !await file.isSameEntry(entry)) throw new FolderError('conflict');
86
+ const initial = await file.getFile();
87
+ const bytes = new Uint8Array(await initial.arrayBuffer());
88
+ if (fileVersion(await file.getFile()) !== fileVersion(initial)) throw new FolderError('conflict');
89
+ assertCurrent();
90
+ await parent.removeEntry(name);
91
+ undo.push(async () => {
92
+ const destination = await restoreParent();
93
+ if (await getFile(destination, name)) return;
94
+ const restored = await destination.getFileHandle(name, {create: true});
95
+ await write(restored, bytes, async () => {
96
+ if ((await restored.getFile()).size) throw new FolderError('conflict');
97
+ });
98
+ });
99
+ }
100
+ };
40
101
  try {
102
+ // The source format owns these directories and requires exactly the files in the snapshot.
103
+ for (const name of sourceDirectories) {
104
+ const entry = existing.get(name);
105
+ const needed = [...files.keys()].some(path => path.startsWith(`${name}/`));
106
+ if (entry?.kind === 'file') await remove(directory, entry);
107
+ const previous = await getDirectory(directory, name);
108
+ if (previous && (!entry || entry.kind !== 'directory' || !await previous.isSameEntry(entry))) {
109
+ throw new FolderError('conflict');
110
+ }
111
+ if (!needed && !previous) continue;
112
+ assertCurrent();
113
+ const handle = previous ?? await directory.getDirectoryHandle(name, {create: true});
114
+ if (!previous) undo.push(async () => {
115
+ const found = await getDirectory(directory, name);
116
+ if (found && await found.isSameEntry(handle)) await directory.removeEntry(name);
117
+ });
118
+ const children = await directoryEntries(handle);
119
+ for (const child of children.values()) {
120
+ if (child.kind === 'file' && files.has(`${name}/${child.name}`) && previous) continue;
121
+ if (!previous) throw new FolderError('conflict');
122
+ await remove(handle, child);
123
+ children.delete(child.name);
124
+ }
125
+ directories.set(name, {handle, entries: children});
126
+ }
41
127
  // Publish the project JSON last, after the files it refers to.
42
128
  const entries = [...files].sort(([a], [b]) => Number(manifests.has(a)) - Number(manifests.has(b)) ||
43
129
  Number(a === projectFile) - Number(b === projectFile));
44
130
  for (const [filename, bytes] of entries) {
45
131
  assertCurrent();
46
132
  const [first, basename] = filename.split('/');
47
- let parent = directory;
48
- if (basename !== undefined) {
49
- const existing = directories.get(first);
50
- if (existing) parent = existing;
51
- else {
52
- const unexpected = await directory.getDirectoryHandle(first).catch(error => {
53
- if (missing(error)) return null;
54
- throw error;
55
- });
56
- if (unexpected) throw new FolderError('conflict');
57
- parent = await directory.getDirectoryHandle(first, {create: true});
58
- directories.set(first, parent);
59
- undo.push(async () => {
60
- const entry = await directory.getDirectoryHandle(first);
61
- if (await entry.isSameEntry(parent)) await directory.removeEntry(first);
62
- });
63
- }
64
- }
133
+ const subdirectory = basename === undefined ? undefined : directories.get(first)!;
134
+ const parent = subdirectory?.handle ?? directory;
65
135
  const name = basename ?? first;
66
- const existing = await parent.getFileHandle(name).catch(error => {
67
- if (missing(error)) return null;
68
- throw error;
69
- });
70
- if (existing) throw new FolderError('conflict');
71
- const file = await parent.getFileHandle(name, {create: true});
136
+ const entry = (subdirectory?.entries ?? existing).get(name);
137
+ if (entry?.kind === 'directory') await remove(parent, entry);
138
+ const previous = await getFile(parent, name);
139
+ if (entry?.kind === 'file' ? !previous || !await previous.isSameEntry(entry) : previous) {
140
+ throw new FolderError('conflict');
141
+ }
142
+ const file = previous ?? await parent.getFileHandle(name, {create: true});
72
143
  const initial = await file.getFile();
73
- if (initial.size !== 0) throw new FolderError('conflict');
74
- let expected: Uint8Array = new Uint8Array();
144
+ if (!previous && initial.size !== 0) throw new FolderError('conflict');
145
+ const backup = previous ? new Uint8Array(await initial.arrayBuffer()) : null;
146
+ let committed = false;
75
147
  undo.push(async () => {
76
- const entry = await parent.getFileHandle(name);
77
- if (!await entry.isSameEntry(file)) return;
78
- if (sameBytes(new Uint8Array(await (await entry.getFile()).arrayBuffer()), expected)) await parent.removeEntry(name);
148
+ if (backup && !committed) return;
149
+ const found = await getFile(parent, name);
150
+ if (!found || !await found.isSameEntry(file)) return;
151
+ const latest = await found.getFile();
152
+ if (!sameBytes(new Uint8Array(await latest.arrayBuffer()), committed ? bytes : new Uint8Array())) return;
153
+ if (backup) await write(found, backup, async () => {
154
+ if (fileVersion(await found.getFile()) !== fileVersion(latest)) throw new FolderError('conflict');
155
+ });
156
+ else await parent.removeEntry(name);
79
157
  });
80
- const writable = await file.createWritable({mode: 'exclusive'} as FileSystemCreateWritableOptions);
81
- try {
82
- await writable.write(bytes as Uint8Array<ArrayBuffer>);
83
- assertCurrent();
158
+ await write(file, bytes, async () => {
84
159
  if (fileVersion(await file.getFile()) !== fileVersion(initial)) throw new FolderError('conflict');
85
- await writable.close();
86
- expected = bytes;
87
- } catch (error) {
88
- await writable.abort().catch(() => {});
89
- throw error;
90
- }
160
+ assertCurrent();
161
+ });
162
+ committed = true;
91
163
  }
92
164
  const source = await readFolder(directory, storage);
93
165
  assertCurrent();
@@ -5,7 +5,7 @@ export const actionMessages = (locale = 'en') => locale.toLowerCase().startsWith
5
5
  actions: 'ファイルとフォルダの操作', rename: '名前を変更…', renameTitle: '名前を変更', delete: '削除…', deleteTitle: '削除',
6
6
  createFolder: '新規フォルダを作成', folderName: 'フォルダ名', newName: '新しい名前', cancel: 'キャンセル',
7
7
  remove: (name: string, folder: boolean) => folder ? `「${name}」とその中身を削除しますか?` : `「${name}」を削除しますか?`,
8
- stage: 'Git にステージ', unstage: 'Git のステージを解除',
8
+ stage: '次のコミットに含める', unstage: '次のコミットから外す',
9
9
  working: '処理中…', copyFailed: 'コピーできませんでした', filesOnly: 'ファイルをドロップしてください。',
10
10
  invalidName: 'この名前は使用できません。', exists: '同じ名前のファイルまたはフォルダがあります。',
11
11
  invalidDestination: 'このフォルダには移動できません。',