-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathrfs.js
More file actions
2049 lines (1813 loc) · 62.4 KB
/
Copy pathrfs.js
File metadata and controls
2049 lines (1813 loc) · 62.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
const SW_URL = "./sw.min.js"; // Change if needed!
const ALWAYS_CONFIRM_LEAVE = false; // Set to true to always create the "Leave site?" prompt before unload, regardless if currentlyBusy is false.
const RFS_PREFIX = "rfs"; // OPFS prefix
const SYSTEM_FILE = "rfs_system.json"; // File with a little bit of extra data
const CHUNK_SIZE = 4194304; // 4MiB, for encrypted chunks
const CONCURRENCY = 4; // Number of "workers" for folder uploading stuff
const YIELD_TIME = 50; // Amount of ms before yielding; used for logging and pauses so UI can update.
// List of ignored internal files. If you have a custom use case for LittleExport such as transferring programming files (but want to exclude certain folders like node_modules), please add to IGNORED_NAMES or modify functionality.
const IGNORED_NAMES = new Set([
".DS_Store",
"Thumbs.db",
"desktop.ini",
"__MACOSX",
".AppleDouble",
".LSOverride",
".Trashes",
".TemporaryItems",
".Spotlight-V100",
".fseventsd",
".DocumentRevisions-V100",
"System Volume Information",
"$RECYCLE.BIN",
]);
// Headers that tell about the body of the response. openFileInPlace does not copy these into meta elements.
const BODY_HEADERS = new Set([
"content-type",
"content-length",
"content-range",
"accept-ranges",
"cache-control",
]);
// Check if a file/folder should be ignored. Can be customize
function isJunk(name) {
return (
IGNORED_NAMES.has(name) ||
name.startsWith("._") ||
name.startsWith(".Trash-")
);
}
window.addEventListener("beforeunload", function (e) {
if (ALWAYS_CONFIRM_LEAVE || currentlyBusy) {
e.preventDefault();
e.returnValue = "Changes you made may not be saved.";
return "Changes you made may not be saved."; // not that the string text here matters
}
});
let isListingFolders = false;
let currentlyBusy = false;
let folderName, dirHandle, observer;
let changes = [];
let showingSync = false;
let _registryCache = null;
// Set to true only after a read or a write of SYSTEM_FILE is successful. An empty registry that comes from a read error must not cause removal of folders.
let _registryIsTrusted = false;
let _opfsRoot = null;
async function getOpfsRoot() {
if (!_opfsRoot) _opfsRoot = await navigator.storage.getDirectory();
return _opfsRoot;
}
function setUiBusy(isBusy) {
if (currentlyBusy !== isBusy) {
currentlyBusy = isBusy;
Array.from(document.getElementsByTagName("button")).forEach(
(button) => (button.disabled = currentlyBusy),
);
}
}
function createLogger(elem, yielder) {
let lastMsg = null;
let lastDomUpdate = 0;
// Returns Promise | null
return function (msg, force = false) {
const now = Date.now();
if (msg !== lastMsg && msg !== null) {
lastMsg = msg;
if (force || now - lastDomUpdate > YIELD_TIME) {
elem.textContent = msg;
lastDomUpdate = now;
}
}
return yielder(force);
};
}
const checkYield = (function () {
let lastYield = 0;
const pendingResolvers = [];
const channel = new MessageChannel();
channel.port1.onmessage = () => {
const resolver = pendingResolvers.shift();
if (resolver) resolver();
};
const yieldToMain = () =>
new Promise((res) => {
pendingResolvers.push(res);
channel.port2.postMessage(null);
});
return function (force = false) {
if (force || Date.now() - lastYield > YIELD_TIME) {
lastYield = Date.now();
return (async () => {
if ("scheduler" in window && "yield" in scheduler) {
await scheduler.yield();
} else {
await yieldToMain();
}
})();
}
return null;
};
})();
const logProgress = createLogger(
document.getElementById("progress"),
checkYield,
);
navigator.storage
.persist()
.then((p) =>
console.log(p ? "Storage persisted." : "Storage not persisted."),
);
async function waitForController() {
if (navigator.serviceWorker.controller)
return navigator.serviceWorker.controller;
await navigator.serviceWorker.register(SW_URL);
const reg = await navigator.serviceWorker.ready;
return navigator.serviceWorker.controller || reg.active;
}
async function getRegistry() {
if (_registryCache) return _registryCache;
// Shared to allow concurrent reads but block if writing is active.
return await navigator.locks.request(
"rfs_registry_lock",
{ mode: "shared" },
async () => {
// Double check cache after acquiring lock
if (_registryCache) return _registryCache;
try {
const root = await getOpfsRoot();
const handle = await root.getFileHandle(SYSTEM_FILE);
const file = await handle.getFile();
const text = await file.text();
_registryCache = text ? JSON.parse(text) : {};
_registryIsTrusted = true;
} catch (err) {
// If file doesn't exist or is empty
_registryCache = {};
_registryIsTrusted = false;
}
return _registryCache;
},
);
}
// Tell the SW and the other tabs that the registry changed. Each one must then read the data again.
function notifyRegistryChange(name) {
if (navigator.serviceWorker.controller) {
navigator.serviceWorker.controller.postMessage({
type: "INVALIDATE_CACHE",
folderName: name,
});
}
}
// Read, change, and write the registry in one exclusive lock. All changes that first read the current data must use this function. If you read and write in two steps, a second tab can remove your change.
async function mutateRegistry(mutator, name) {
return navigator.locks.request(
"rfs_registry_lock",
{ mode: "exclusive" },
async () => {
const root = await getOpfsRoot();
let registry = {};
// Always read from the disk. The memory copy can be older than the file.
try {
const handle = await root.getFileHandle(SYSTEM_FILE);
const file = await handle.getFile();
const text = await file.text();
registry = text ? JSON.parse(text) : {};
} catch (err) {
registry = {};
}
// A mutator that returns false makes no change, thus no write is necessary.
if ((await mutator(registry)) === false) return registry;
const handle = await root.getFileHandle(SYSTEM_FILE, { create: true });
const writable = await handle.createWritable();
await writable.write(JSON.stringify(registry));
await writable.close();
// Change the memory copy only after the write to the disk is complete. If the write stops with an error, the memory copy and the file stay the same.
_registryCache = registry;
_registryIsTrusted = true;
notifyRegistryChange(name);
return registry;
},
);
}
// Write a complete registry. Prefer mutateRegistry if the new data depends on the current data.
async function saveRegistry(registry) {
await mutateRegistry((current) => {
for (const key of Object.keys(current)) delete current[key];
Object.assign(current, registry);
});
}
async function updateRegistryEntry(name, data) {
await mutateRegistry((registry) => {
if (data === null) {
delete registry[name];
} else {
registry[name] = {
...(registry[name] || {}),
...data,
lastModified: Date.now(),
};
}
}, name);
}
async function analyzeAndImportFolder(handleOrEntry, filesArray = null) {
setUiBusy(true);
try {
let isEncrypted = false;
let isSystemExport = false;
let pathPrefix = "";
async function checkFile(pathParts) {
try {
if (filesArray) {
const targetPath = pathParts.join("/");
return filesArray.some(
(f) =>
f.webkitRelativePath.endsWith(`/${targetPath}`) ||
f.webkitRelativePath === targetPath,
);
} else if (handleOrEntry.kind === "directory") {
let cur = handleOrEntry;
for (let i = 0; i < pathParts.length - 1; i++) {
cur = await cur.getDirectoryHandle(pathParts[i]);
}
await cur.getFileHandle(pathParts[pathParts.length - 1]);
return true;
} else if (handleOrEntry.isDirectory) {
return new Promise((resolve) => {
handleOrEntry.getFile(
pathParts.join("/"),
{ create: false },
() => resolve(true),
() => resolve(false),
);
});
}
} catch (err) {
return false;
}
}
if (await checkFile(["manifest.enc"])) isEncrypted = true;
if (!isEncrypted) {
if (await checkFile(["data", "custom", SYSTEM_FILE])) {
isSystemExport = true;
} else if (await checkFile(["opfs", "rfs", SYSTEM_FILE])) {
isSystemExport = true;
} else if (await checkFile(["custom", SYSTEM_FILE])) {
isSystemExport = true;
pathPrefix = "data";
} else if (await checkFile(["rfs", SYSTEM_FILE])) {
isSystemExport = true;
pathPrefix = "opfs";
} else if (await checkFile(["ls.json"])) {
isSystemExport = true;
pathPrefix = "data";
}
}
if (isEncrypted) {
const encName = prompt(
`"${handleOrEntry.name || "Folder"}" appears to be an encrypted folder. Enter a name to mount it as:`,
handleOrEntry.name,
);
if (!encName) return;
if (filesArray) {
alert(
"Encrypted folder import via file input not supported yet. Use drag-and-drop or the directory picker.",
);
} else {
if (handleOrEntry.kind === "directory") {
await processFolderSelection(encName, handleOrEntry);
} else {
alert("Please use Upload Folder for encrypted folders.");
}
}
return;
}
if (isSystemExport) {
if (
confirm(
"Found RuntimeFS data archive. Import? (This may overwrite multiple folders and already existing data.)",
)
) {
let stream;
if (filesArray) {
stream = LittleExport.folderToTarStream(filesArray, checkYield, {
pathPrefix,
});
} else {
stream = LittleExport.folderToTarStream(handleOrEntry, checkYield, {
pathPrefix,
});
}
await startImport({ stream: () => stream });
}
return;
}
const name =
document.getElementById("folderName").value.trim() ||
prompt("Enter a name for the folder:", handleOrEntry.name || "");
if (!name) return;
if (filesArray) {
await processFilesAndStore(name, filesArray);
} else if (handleOrEntry.kind === "directory") {
await processFolderSelection(name, handleOrEntry);
} else {
alert("Please use drag-and-drop for this folder.");
}
} catch (err) {
console.error("Import error:", err);
alert("An error occurred during import: " + err.message);
} finally {
setUiBusy(false);
}
}
async function uploadFolder() {
try {
if (window.showDirectoryPicker) {
setUiBusy(true);
const handle = await window.showDirectoryPicker({ mode: "read" });
await analyzeAndImportFolder(handle);
} else {
document.getElementById("folderUploadFallbackInput").click();
}
} catch (err) {
if (err.name !== "AbortError") {
console.error(err);
alert("Error accessing folder: " + err.message);
}
} finally {
setUiBusy(false);
}
}
async function uploadFolderFallback(e) {
const input = e.target;
if (!input.files.length) {
setUiBusy(false);
return;
}
await analyzeAndImportFolder({}, Array.from(input.files));
input.value = "";
}
async function processFolderSelection(name, handle) {
let failed = false;
await navigator.locks.request(`rfs_write_${name}`, async () => {
dirHandle = handle;
folderName = name;
// Look for the manifest first. Only a missing manifest means that the folder is a usual folder.
let encManifest = null;
try {
encManifest = await handle.getFileHandle("manifest.enc");
} catch (err) {}
if (!encManifest) {
await processFolderStreaming(name, handle);
return;
}
const root = await getOpfsRoot();
const rfs = await root.getDirectoryHandle(RFS_PREFIX, { create: true });
try {
await rfs.removeEntry(name, { recursive: true });
} catch (err) {
if (err.name !== "NotFoundError") {
alert(
"RuntimeFS cannot currently remove this folder; try closing other open RuntimeFS tabs.",
);
failed = true;
return;
}
}
try {
await decryptAndLoadFolderToOpfs(
handle,
encManifest,
await rfs.getDirectoryHandle(name, { create: true }),
);
} catch (err) {
// Show the cause, for example a wrong password. Do not store the encrypted files as usual files.
alert(err.message);
await rfs.removeEntry(name, { recursive: true }).catch(() => {});
failed = true;
return;
}
await updateRegistryEntry(name, { encryptionType: null });
});
if (failed) {
await logProgress("", true);
setUiBusy(false);
return;
}
if (observer) {
try {
observer.disconnect();
} catch (err) {}
observer = null;
}
if ("FileSystemObserver" in window) {
try {
observer = new FileSystemObserver((recs) => changes.push(...recs));
await observer.observe(dirHandle, { recursive: true });
if (!showingSync) {
Array.from(
document.body.getElementsByClassName("supportCheck"),
).forEach((elem) => (elem.style.display = "revert"));
showingSync = true;
}
} catch (err) {
console.warn("Observer failed:", err);
// Hide sync functionality on failure (like unsupported filesystems)
if (showingSync) {
Array.from(
document.body.getElementsByClassName("supportCheck"),
).forEach((elem) => (elem.style.display = "none"));
showingSync = false;
}
observer = null;
}
}
changes.length = 0;
document.getElementById("folderName").value = "";
document.getElementById("openFolderName").value = name;
await updateRegistryEntry(name, { encryptionType: null });
await logProgress("", true);
setUiBusy(false);
await listFolders();
}
async function decryptAndLoadFolderToOpfs(srcHandle, manifestHandle, destDir) {
const password = prompt("Enter the password to decrypt this folder:");
if (!password) throw new Error("Password required.");
const manifestFile = await manifestHandle.getFile();
const manifestBuf = await manifestFile.arrayBuffer();
const salt = manifestBuf.slice(0, 16);
const iv = manifestBuf.slice(16, 28);
const encData = manifestBuf.slice(28);
const key = await deriveKeyFromPassword(password, salt);
let manifestData;
try {
const decryptedManifestBytes = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv },
key,
encData,
);
manifestData = JSON.parse(new TextDecoder().decode(decryptedManifestBytes));
} catch (err) {
throw new Error("Decryption failed. Wrong password?");
}
const contentDir = await srcHandle.getDirectoryHandle("content");
const ENCRYPTED_CHUNK_OVERHEAD = 12 + 16;
const entries = Object.entries(manifestData);
const totalFiles = entries.length;
let processedFiles = 0;
// Each value must be a promise, because the workers chain the parent handle with .then().
const dirCache = new Map();
dirCache.set(".", Promise.resolve(destDir));
const worker = async () => {
while (entries.length > 0) {
const entryTask = entries.shift();
if (!entryTask) break;
const [originalPath, meta] = entryTask;
const p = logProgress(
`Decrypting (${processedFiles}/${totalFiles}): ${originalPath}`,
);
if (p) await p;
const pathParts = originalPath.split("/");
const fileName = pathParts.pop();
let currentDir = destDir;
if (pathParts.length > 0) {
let pathAcc = ".";
currentDir = await dirCache.get(".");
for (const part of pathParts) {
const parentPath = pathAcc;
pathAcc += "/" + part;
if (!dirCache.has(pathAcc)) {
const parentDirPromise = dirCache.get(parentPath);
const newDirPromise = parentDirPromise.then((parent) =>
parent.getDirectoryHandle(part, { create: true }),
);
dirCache.set(pathAcc, newDirPromise);
}
// Await the promise in the cache
currentDir = await dirCache.get(pathAcc);
}
}
// Stop the full operation if a file of the manifest is not available. A folder with some files only looks correct but is not.
let srcFile;
try {
const handle = await contentDir.getFileHandle(meta.id);
srcFile = await handle.getFile();
} catch (err) {
throw new Error(
`The encrypted folder has no data for ${originalPath}.`,
);
}
const destFileHandle = await currentDir.getFileHandle(fileName, {
create: true,
});
const writable = await destFileHandle.createWritable();
try {
if (meta.size > 0) {
const reader = srcFile.stream().getReader();
const totalEncChunks = Math.ceil(meta.size / CHUNK_SIZE);
// Keep the parts that arrive in a list. A buffer that grows for each read makes a copy every time, which is very slow for a large file.
let pending = [];
let pendingSize = 0;
let chunkIndex = 0;
try {
while (chunkIndex < totalEncChunks) {
const py = checkYield();
if (py) await py;
const isLast = chunkIndex === totalEncChunks - 1;
const plainSize = isLast
? meta.size % CHUNK_SIZE || CHUNK_SIZE
: CHUNK_SIZE;
const encSize = plainSize + ENCRYPTED_CHUNK_OVERHEAD;
// Collect enough data for a full encrypted chunk
while (pendingSize < encSize) {
const { done, value } = await reader.read();
if (done) break;
pending.push(value);
pendingSize += value.byteLength;
}
// The manifest gives the size, thus data that is too short shows damage. Do not write a file that is too short.
if (pendingSize < encSize)
throw new Error(
`The data for ${originalPath} is incomplete or damaged.`,
);
// Join only the bytes of this chunk, and keep the rest for the next chunk.
const chunkData = new Uint8Array(encSize);
let filled = 0;
while (filled < encSize) {
const head = pending[0];
const take = Math.min(head.byteLength, encSize - filled);
chunkData.set(head.subarray(0, take), filled);
filled += take;
pendingSize -= take;
if (take === head.byteLength) pending.shift();
else pending[0] = head.subarray(take);
}
const chunkIv = chunkData.subarray(0, 12);
const chunkCipher = chunkData.subarray(12);
const plainChunk = await crypto.subtle.decrypt(
{ name: "AES-GCM", iv: chunkIv },
key,
chunkCipher,
);
await writable.write(new Uint8Array(plainChunk));
chunkIndex++;
}
} finally {
reader.releaseLock();
}
}
await writable.close();
} catch (err) {
// Abort keeps the incomplete data out of OPFS.
try {
await writable.abort(err);
} catch (_) {}
throw err;
}
processedFiles++;
}
};
// Run in parallel
await Promise.all(Array(CONCURRENCY).fill(null).map(worker));
await logProgress("", true);
}
async function processFilesAndStore(name, fileList) {
await navigator.locks.request(`rfs_write_${name}`, async () => {
const root = await getOpfsRoot();
const rfsRoot = await root.getDirectoryHandle(RFS_PREFIX, { create: true });
try {
await rfsRoot.removeEntry(name, { recursive: true });
} catch (err) {
// Stop if the old folder stays. If you continue, the new files mix with the old files.
if (err.name !== "NotFoundError") {
alert(
"RuntimeFS cannot currently remove this folder; try closing other open RuntimeFS tabs.",
);
setUiBusy(false);
return;
}
}
const destRoot = await rfsRoot.getDirectoryHandle(name, { create: true });
let bytesUploaded = 0;
const queue = Array.from(fileList).filter((f) => !isJunk(f.name));
// Count only the files in the queue. Junk files are not uploaded.
let totalBytes = 0;
for (const file of queue) totalBytes += file.size;
const updateUI = () => {
const mb = (bytesUploaded / 1e6).toFixed(2);
const totalMb = (totalBytes / 1e6).toFixed(2);
const pct =
totalBytes > 0
? ((bytesUploaded / totalBytes) * 100).toFixed(2)
: "100.00";
return logProgress(`Uploading: ${pct}% (${mb} / ${totalMb} MB)`);
};
const worker = async () => {
const dirCache = new Map();
while (queue.length > 0) {
const file = queue.shift();
if (!file) break;
let relativePath = file.webkitRelativePath || file.name;
const pathParts = relativePath.split("/");
if (pathParts.length > 1) pathParts.shift();
relativePath = pathParts.join("/");
// Throttle progress updates to avoid saturating the yield check
let bytesSinceLastUI = 0;
await writeStreamToOpfs(destRoot, relativePath, file, {
dirCache,
onProgress: async (delta) => {
bytesUploaded += delta;
bytesSinceLastUI += delta;
if (bytesSinceLastUI > 1048576) {
let p = updateUI();
if (p) await p;
bytesSinceLastUI = 0;
}
},
});
// Always check yield after a full file completion
const p = checkYield();
if (p) await p;
}
};
const workers = Array(CONCURRENCY).fill(null).map(worker);
await Promise.all(workers);
document.getElementById("folderName").value = "";
document.getElementById("openFolderName").value = name;
await updateRegistryEntry(name, { encryptionType: null });
await logProgress("", true);
await listFolders();
});
}
async function processFolderStreaming(name, srcHandle) {
const root = await getOpfsRoot();
const rfs = await root.getDirectoryHandle(RFS_PREFIX, { create: true });
try {
await rfs.removeEntry(name, { recursive: true });
} catch (err) {
if (err.name !== "NotFoundError") {
alert(
"RuntimeFS cannot currently remove this folder; try closing other open RuntimeFS tabs.",
);
setUiBusy(false);
return;
}
}
const destRoot = await rfs.getDirectoryHandle(name, { create: true });
const uploadQueue = [];
let scanComplete = false;
let hasError = false;
let totalBytesDiscovered = 0;
let bytesUploaded = 0;
const updateUI = () => {
const uploadedMB = (bytesUploaded / 1e6).toFixed(2);
const totalFoundMB = (totalBytesDiscovered / 1e6).toFixed(2);
let msg = scanComplete
? `Finishing: ${uploadedMB} MB / ${totalFoundMB} MB`
: `Scanning: ${uploadedMB} MB / ${totalFoundMB} MB`;
return logProgress(msg);
};
const worker = async () => {
const dirCache = new Map();
while (!hasError) {
const task = uploadQueue.shift();
if (!task) {
if (scanComplete) break;
await new Promise((res) => setTimeout(res, 20));
continue;
}
// Optimization: Use the file discovered by the scanner to avoid redundant getFile()
const file = task.fileOverride;
let bytesSinceLastUI = 0;
await writeStreamToOpfs(task.dest, task.entry.name, file, {
dirCache,
onProgress: async (delta) => {
bytesUploaded += delta;
bytesSinceLastUI += delta;
if (bytesSinceLastUI > 1048576) {
let p = updateUI();
if (p) await p;
bytesSinceLastUI = 0;
}
},
});
const p = checkYield();
if (p) await p;
}
};
const scanner = async () => {
const scanStack = [{ source: srcHandle, dest: destRoot }];
while (scanStack.length > 0 && !hasError) {
const { source, dest } = scanStack.shift();
try {
for await (const entry of source.values()) {
if (hasError) break;
if (isJunk(entry.name)) continue;
if (entry.kind === "file") {
// Scanner does the heavy lifting of opening the file
const file = await entry.getFile();
totalBytesDiscovered += file.size;
uploadQueue.push({ dest, entry, fileOverride: file });
let p = updateUI();
if (p) await p;
// Backpressure loop (if IO is slow)
while (uploadQueue.length > 500 && !hasError) {
await new Promise((res) => setTimeout(res, 20));
const py = checkYield();
if (py) await py;
}
} else if (entry.kind === "directory") {
const nextDest = await dest.getDirectoryHandle(entry.name, {
create: true,
});
scanStack.push({ source: entry, dest: nextDest });
}
const p = checkYield();
if (p) await p;
}
} catch (err) {
console.warn("Error reading directory stream:", err);
}
}
scanComplete = true;
};
try {
const workerPromises = Array(CONCURRENCY).fill(null).map(worker);
await Promise.all([scanner(), ...workerPromises]);
} catch (err) {
hasError = true;
throw err;
}
document.getElementById("folderName").value = "";
document.getElementById("openFolderName").value = name;
await updateRegistryEntry(name, { encryptionType: null });
await logProgress("", true);
await listFolders();
setUiBusy(false);
}
async function writeStreamToOpfs(parentHandle, path, fileObj, options = {}) {
const { dirCache = null, onProgress = null } = options;
const parts = path.split("/");
const fileName = parts.pop();
let currentDir = parentHandle;
if (parts.length > 0) {
let pathAcc = "";
for (const part of parts) {
const parentPathAcc = pathAcc;
pathAcc += (pathAcc ? "/" : "") + part;
if (dirCache) {
if (!dirCache.has(pathAcc)) {
const parentPromise = parentPathAcc
? dirCache.get(parentPathAcc)
: Promise.resolve(parentHandle);
const dirPromise = parentPromise.then((p) =>
p.getDirectoryHandle(part, { create: true }),
);
dirCache.set(pathAcc, dirPromise);
}
currentDir = await dirCache.get(pathAcc);
} else {
currentDir = await currentDir.getDirectoryHandle(part, {
create: true,
});
}
}
}
const fileHandle = await currentDir.getFileHandle(fileName, { create: true });
const writable = await fileHandle.createWritable({ keepExistingData: false });
try {
if (!onProgress) {
await writable.write(fileObj);
} else {
const meter = new TransformStream({
async transform(chunk, controller) {
controller.enqueue(chunk);
const p = onProgress(chunk.byteLength);
if (p) await p;
},
});
await fileObj
.stream()
.pipeThrough(meter)
.pipeTo(writable, { preventClose: true });
}
// Only a close makes the data permanent. Thus the file changes in one step.
await writable.close();
} catch (err) {
// Abort keeps the file as it was. A close after an error makes the incomplete data permanent.
try {
await writable.abort(err);
} catch (_) {}
throw err;
}
}
async function cleanupOrphans() {
await navigator.locks.request(
"rfs_global_import",
{ ifAvailable: true },
async (importLock) => {
if (!importLock) return;
try {
const root = await getOpfsRoot();
const rfsRoot = await root.getDirectoryHandle(RFS_PREFIX);
const registry = await getRegistry();
// Stop if SYSTEM_FILE is not readable. An empty registry from a damaged file must not remove good folders.
if (!_registryIsTrusted) return;
const registryKeys = new Set(Object.keys(registry));
// Batch read all keys first
const diskKeys = [];
for await (const name of rfsRoot.keys()) diskKeys.push(name);
// Filter and delete only what is necessary
for (const name of diskKeys) {
if (!registryKeys.has(name)) {
await navigator.locks.request(
`rfs_write_${name}`,
{ ifAvailable: true },
async (lock) => {
if (lock)
await rfsRoot
.removeEntry(name, { recursive: true })
.catch(() => {});
},
);
}
}
} catch (err) {}
},
);
}
let listFoldersAgain = false;
async function listFolders() {
// A second call during a listing must not go away. Make a note of it and do the listing one more time, or the list can show old data.
if (isListingFolders) {
listFoldersAgain = true;
return;
}
isListingFolders = true;
const folderList = document.getElementById("folderList");
try {
do {
listFoldersAgain = false;
const registry = await getRegistry();
const fragment = document.createDocumentFragment();
const names = Object.keys(registry).sort();
names.forEach((name) => {
const meta = registry[name];
const li = document.createElement("li");
li.textContent =
meta.encryptionType === "password" ? `[Locked] ${name}` : name;
fragment.appendChild(li);
});
folderList.textContent = "";
folderList.appendChild(fragment);
} while (listFoldersAgain);
} finally {
isListingFolders = false;
}
}
async function deleteFolder(folderNameToDelete, skipConfirm = false) {
const targetFolder =
folderNameToDelete ||
document.getElementById("deleteFolderName").value.trim();
if (!targetFolder) return alert("Enter a folder name first.");
if (!skipConfirm && !confirm(`Remove "${targetFolder}"?`)) return;
setUiBusy(true);
logProgress("Deleting...", true);
// Remove the registry entry first. If the removal of the files stops, no entry points to missing data, and cleanupOrphans removes the files at the next start.
await updateRegistryEntry(targetFolder, null);
const root = await getOpfsRoot();
try {
const rfsRoot = await root.getDirectoryHandle(RFS_PREFIX);