browser-storage.js
composeApp/src/wasmJsMain/resources/browser-storage.js
1/* Origin-private file storage. Binary content is streamed to disk, never put in localStorage. */2(() => {3 'use strict';4 const decode = value => Uint8Array.from(atob(value), c => c.charCodeAt(0));5 const encode = bytes => {6 let binary = '';7 for (let i = 0; i < bytes.length; i += 32768) binary += String.fromCharCode(...bytes.subarray(i, i + 32768));8 return btoa(binary);9 };10 const stores = new Map();11 const mediaPrefix = '__yokan_files__/';12 const base = typeof document === 'undefined' ? 'http://localhost/' : new URL('.', document.currentScript?.src || document.baseURI).href;13 // The worker must control the app page, even when scripts are served from a separate assets path.14 const mediaBase = typeof document === 'undefined' ? base : new URL('.', document.baseURI).href;15 let workerReady;16 let archiveReady;17 async function prepareArchives() {18 if (globalThis.yokanBrowserArchives) return globalThis.yokanBrowserArchives;19 if (!archiveReady) archiveReady = new Promise((resolve, reject) => {20 const script = document.createElement('script');21 script.src = new URL('browser-archives.js', base).href;22 script.onload = () => resolve(globalThis.yokanBrowserArchives);23 script.onerror = () => reject(new Error('Archive support could not load.'));24 document.head.append(script);25 }).catch(error => { archiveReady = null; throw error; });26 return archiveReady;27 }2829 async function prepareMediaWorker() {30 if (!workerReady) workerReady = (async () => {31 if (!navigator.serviceWorker) throw new Error('Offline media requires service-worker support.');32 const registration = await navigator.serviceWorker.register(new URL('browser-files-sw.js', mediaBase), { scope: new URL('.', mediaBase).pathname });33 const candidate = registration.installing || registration.waiting;34 if (candidate && candidate.state !== 'activated') await new Promise((resolve, reject) => {35 const timer = setTimeout(() => { cleanup(); reject(new Error('Offline media update timed out. Reload to retry.')); }, 15000);36 const changed = () => {37 if (candidate.state === 'activated') { cleanup(); resolve(); }38 else if (candidate.state === 'redundant') { cleanup(); reject(new Error('Offline media could not update. Reload to retry.')); }39 };40 const cleanup = () => { clearTimeout(timer); candidate.removeEventListener('statechange', changed); };41 candidate.addEventListener('statechange', changed); changed();42 });43 // navigator.serviceWorker.ready can wait forever when the registration does not cover this page.44 if (!registration.active && candidate?.state !== 'activated') throw new Error('Offline media worker did not activate.');45 if (!navigator.serviceWorker.controller) await new Promise((resolve, reject) => {46 const timer = setTimeout(() => { cleanup(); reject(new Error('Offline media could not start. Reload to retry.')); }, 15000);47 const changed = () => { if (navigator.serviceWorker.controller) { cleanup(); resolve(); } };48 const cleanup = () => { clearTimeout(timer); navigator.serviceWorker.removeEventListener('controllerchange', changed); };49 navigator.serviceWorker.addEventListener('controllerchange', changed);50 changed();51 });52 })().catch(error => { workerReady = null; throw error; });53 return workerReady;54 }5556 function openStore(rootPath) {57 if (stores.has(rootPath)) return stores.get(rootPath);58 if (rootPath !== '/yokan' && !/^\/yokan\/profiles\/p_[0-9a-f]{32}$/.test(rootPath)) throw new Error('Invalid profile storage root.');59 const inventory = new Map();60 const children = new Map();61 const directories = new Map();62 const knownDirectories = new Set([rootPath]);63 const directoryChildren = new Map();64 const textCache = new Map();65 const writers = new Map();66 let tail = Promise.resolve(), firstFailure = null, prepared = false, retired = false;67 function knowDirectory(path) {68 if (!(path === rootPath || path.startsWith(rootPath + '/'))) return;69 knownDirectories.add(path);70 if (path === rootPath) return;71 const parent = path.slice(0, path.lastIndexOf('/'));72 if (!directoryChildren.has(parent)) directoryChildren.set(parent, new Set());73 directoryChildren.get(parent).add(path);74 }75 function forgetDirectories(path) {76 for (const directory of knownDirectories) if (directory === path || directory.startsWith(path + '/')) {77 knownDirectories.delete(directory); directoryChildren.delete(directory);78 const parent = directory.slice(0, directory.lastIndexOf('/'));79 directoryChildren.get(parent)?.delete(directory);80 if (!directoryChildren.get(parent)?.size) directoryChildren.delete(parent);81 }82 }83 function adjustParents(path, count, bytes) {84 let parent = path.slice(0, path.lastIndexOf('/'));85 while (parent.length >= rootPath.length) {86 knowDirectory(parent);87 const before = directories.get(parent) || { count: 0, bytes: 0 };88 const after = { count: before.count + count, bytes: before.bytes + bytes };89 if (after.count > 0) directories.set(parent, after); else directories.delete(parent);90 parent = parent.slice(0, parent.lastIndexOf('/'));91 }92 }93 function register(entry) {94 const before = inventory.get(entry.path);95 inventory.set(entry.path, entry);96 const parent = entry.path.slice(0, entry.path.lastIndexOf('/'));97 if (!children.has(parent)) children.set(parent, new Map());98 children.get(parent).set(entry.path, entry);99 adjustParents(entry.path, before ? 0 : 1, entry.sizeBytes - (before?.sizeBytes || 0));100 }101 function forget(path) {102 const before = inventory.get(path);103 if (!before) return;104 inventory.delete(path); textCache.delete(path);105 const parent = path.slice(0, path.lastIndexOf('/'));106 children.get(parent)?.delete(path);107 if (!children.get(parent)?.size) children.delete(parent);108 adjustParents(path, -1, -before.sizeBytes);109 }110 const segments = path => {111 if (typeof path !== 'string' || !(path === rootPath || path.startsWith(rootPath + '/'))) throw new Error('File is outside this profile.');112 if (rootPath === '/yokan' && (path === '/yokan/profiles' || path.startsWith('/yokan/profiles/'))) throw new Error('File belongs to another profile.');113 const parts = path.split('/').slice(1);114 if (parts.some(p => !p || p === '.' || p === '..' || p.includes('\\') || p.includes('\0'))) throw new Error('Invalid file path.');115 return parts;116 };117 async function parentFor(path, create = false) {118 const parts = segments(path);119 let directory = await navigator.storage.getDirectory();120 for (const part of parts.slice(0, -1)) directory = await directory.getDirectoryHandle(part, { create });121 return [directory, parts.at(-1)];122 }123 async function fileFor(path, create = false) {124 const [parent, name] = await parentFor(path, create);125 return parent.getFileHandle(name, { create });126 }127 const ready = (async () => {128 if (!navigator.storage?.getDirectory) throw new Error('Downloads require a browser with origin-private file storage.');129 const [parent, name] = await parentFor(rootPath, true);130 const root = await parent.getDirectoryHandle(name, { create: true });131 async function visit(directory, path) {132 knowDirectory(path);133 for await (const [name, handle] of directory.entries()) {134 if (path === '/yokan' && name === 'profiles') continue;135 const child = path + '/' + name;136 if (handle.kind === 'directory') await visit(handle, child);137 else {138 const file = await handle.getFile();139 register({ path: child, name, sizeBytes: file.size, lastModified: file.lastModified });140 if (name === 'metadata.json' && file.size <= 65536) textCache.set(child, encode(new Uint8Array(await file.arrayBuffer())));141 }142 }143 }144 await visit(root, rootPath);145 prepared = true;146 })();147 ready.catch(() => {}); // The owning coroutine observes and reports preparation failures.148 const assertOpen = () => { if (retired) throw new Error('Profile file storage is closed.'); };149 const assertPrepared = () => { assertOpen(); if (!prepared) throw new Error('Profile file storage has not been prepared.'); };150 const enqueue = action => {151 assertOpen();152 const work = tail.then(async () => { await ready; assertOpen(); return action(); });153 tail = work.catch(error => { if (!firstFailure) firstFailure = error; });154 return work;155 };156 async function update(path) {157 const file = await (await fileFor(path)).getFile();158 register({ path, name: path.split('/').at(-1), sizeBytes: file.size, lastModified: file.lastModified });159 }160 async function write(path, bytes) {161 segments(path);162 if (writers.has(path)) throw new Error('File is already being written.');163 const handle = await fileFor(path, true);164 const stream = await handle.createWritable();165 try { await stream.write(bytes); await stream.close(); }166 catch (error) { await stream.abort().catch(() => {}); throw error; }167 await update(path);168 if (path.endsWith('/metadata.json') && bytes.length <= 65536) textCache.set(path, encode(bytes));169 }170 async function flush() {171 await tail;172 if (firstFailure) { const error = firstFailure; firstFailure = null; throw error; }173 }174 function localEntries(path, extensions) {175 segments(path); assertPrepared();176 if (!knownDirectories.has(path)) return null;177 const readable = new Set(extensions.split(','));178 const supported = entry => readable.has(entry.name.split('.').at(-1).toLowerCase());179 const result = [];180 const pending = [path];181 while (pending.length) {182 const current = pending.pop();183 for (const file of children.get(current)?.values() || []) if (supported(file)) {184 result.push({ path: file.path, name: file.name.replace(/\.[^.]+$/, ''), isArchive: true });185 }186 for (const directory of directoryChildren.get(current) || []) {187 if ([...(children.get(directory)?.values() || [])].some(supported)) {188 result.push({ path: directory, name: directory.slice(directory.lastIndexOf('/') + 1), isArchive: false });189 } else pending.push(directory);190 }191 }192 const compare = (left, right) => left < right ? -1 : left > right ? 1 : 0;193 return result.sort((left, right) => compare(left.name.toLowerCase(), right.name.toLowerCase()) || compare(left.path, right.path));194 }195 const store = {196 prepare: () => ready,197 flush,198 entries: () => { assertPrepared(); return JSON.stringify([...inventory.values()]); },199 list: path => { segments(path); assertPrepared(); return JSON.stringify([...(children.get(path)?.values() || [])]); },200 localEntries: (path, extensions) => JSON.stringify(localEntries(path, extensions)),201 directoryEntries: path => {202 segments(path); assertPrepared();203 if (!knownDirectories.has(path)) return 'null';204 return JSON.stringify([205 ...[...(children.get(path)?.values() || [])].map(file => ({ path: file.path, name: file.name, isDirectory: false })),206 ...[...(directoryChildren.get(path) || [])].map(directory => ({ path: directory, name: directory.slice(directory.lastIndexOf('/') + 1), isDirectory: true })),207 ].sort((a, b) => a.name.toLowerCase() < b.name.toLowerCase() ? -1 : a.name.toLowerCase() > b.name.toLowerCase() ? 1 : 0));208 },209 exists: path => { segments(path); assertPrepared(); return inventory.has(path) || knownDirectories.has(path); },210 size: path => { segments(path); assertPrepared(); return inventory.get(path)?.sizeBytes || directories.get(path)?.bytes || 0; },211 cached: path => { segments(path); return textCache.get(path) ?? null; },212 archiveEntries: path => enqueue(async () => {213 segments(path);214 const archives = await prepareArchives();215 return JSON.stringify(await archives.index(await (await fileFor(path)).getFile()));216 }),217 openArchive: path => enqueue(async () => {218 segments(path);219 const archives = await prepareArchives();220 const session = await archives.openRead(await (await fileFor(path)).getFile());221 return {222 read: async (name, maximum) => {223 assertOpen();224 const bytes = await session.read(name, maximum);225 assertOpen();226 return bytes === null ? null : encode(bytes);227 },228 close: () => session.close(),229 };230 }),231 zip: (directory, deleteSource) => enqueue(async () => {232 segments(directory);233 if (directory === rootPath) throw new Error('Cannot archive the profile root.');234 if ([...writers.keys()].some(path => path === directory || path.startsWith(directory + '/'))) throw new Error('Chapter is being written.');235 const entries = [...(children.get(directory)?.values() || [])];236 const supported = entry => /\.(jpe?g|png|gif|webp|bmp|avif)$/i.test(entry.name) || entry.name === 'metadata.json';237 const selected = entries.filter(supported);238 if (!selected.some(entry => entry.name !== 'metadata.json')) return null;239 if (deleteSource && entries.some(entry => !supported(entry) && !/\.(complete|part|resume)$|\.split\.json$/.test(entry.name))) throw new Error('Chapter has files that cannot be archived.');240 if (deleteSource && [...inventory.keys()].some(path => path.startsWith(directory + '/') && path.slice(directory.length + 1).includes('/'))) throw new Error('Chapter has nested files that cannot be archived.');241 const archives = await prepareArchives();242 const target = directory + '.cbz', temporary = target + '.part';243 if (writers.has(target) || writers.has(temporary)) throw new Error('Archive is being written.');244 const blobs = [];245 for (const entry of selected) blobs.push({ name: entry.name, bytes: await (await fileFor(entry.path)).getFile() });246 const output = await (await fileFor(temporary, true)).createWritable();247 const archiveWriter = output.getWriter();248 const archiveOutput = new WritableStream({ write: bytes => archiveWriter.write(bytes) });249 writers.set(temporary, output);250 try {251 await archives.write(blobs, archiveOutput);252 await archiveWriter.close();253 const staged = await (await fileFor(temporary)).getFile();254 const index = await archives.index(staged);255 if (index.length !== blobs.length || blobs.some(blob => !index.some(entry => entry.name === blob.name && entry.size === blob.bytes.size))) throw new Error('Incomplete chapter archive.');256 const destination = await (await fileFor(target, true)).createWritable();257 await staged.stream().pipeTo(destination);258 await update(target);259 const [tempParent, tempName] = await parentFor(temporary);260 await tempParent.removeEntry(tempName); forget(temporary);261 if (deleteSource) {262 const [parent, name] = await parentFor(directory);263 await parent.removeEntry(name, { recursive: true });264 for (const key of inventory.keys()) if (key.startsWith(directory + '/')) forget(key);265 forgetDirectories(directory);266 }267 return target;268 } catch (error) {269 await archiveWriter.abort().catch(() => {});270 throw error;271 } finally { archiveWriter.releaseLock(); writers.delete(temporary); }272 }),273 write: (path, base64) => enqueue(() => write(path, decode(base64))),274 read: async (path, maximum) => {275 segments(path); await ready; await flush(); assertOpen();276 const file = await (await fileFor(path)).getFile();277 if (file.size > maximum) throw new Error('File exceeds the read limit.');278 return encode(new Uint8Array(await file.arrayBuffer()));279 },280 begin: async (path, append) => {281 segments(path); await ready; await flush(); assertOpen();282 if (writers.has(path)) throw new Error('File is already being written.');283 // Reserve before awaiting the browser lock so concurrent admissions cannot race.284 writers.set(path, null);285 try {286 const handle = await fileFor(path, true);287 const size = append ? (await handle.getFile()).size : 0;288 const stream = await handle.createWritable({ keepExistingData: append });289 if (size) await stream.seek(size);290 writers.set(path, stream);291 } catch (error) { writers.delete(path); throw error; }292 },293 chunk: async (path, base64) => {294 assertOpen();295 const stream = writers.get(path);296 if (!stream) throw new Error('No file writer.');297 await stream.write(decode(base64));298 },299 end: async (path, commit) => {300 const stream = writers.get(path);301 if (!stream) throw new Error('No file writer.');302 try {303 if (commit) {304 try { await stream.close(); await update(path); }305 catch (error) { await stream.abort().catch(() => {}); throw error; }306 }307 else await stream.abort();308 } finally { writers.delete(path); }309 },310 promote: (source, target) => enqueue(async () => {311 segments(source); segments(target);312 if (writers.has(source) || writers.has(target)) throw new Error('File is being written.');313 const sourceFile = await (await fileFor(source)).getFile();314 const output = await (await fileFor(target, true)).createWritable();315 try { await sourceFile.stream().pipeTo(output); }316 catch (error) { await output.abort().catch(() => {}); throw error; }317 await update(target);318 const [parent, name] = await parentFor(source);319 await parent.removeEntry(name);320 forget(source);321 return true;322 }),323 remove: path => enqueue(async () => {324 segments(path);325 if (path === rootPath) throw new Error('Cannot remove the profile root.');326 if ([...writers.keys()].some(p => p === path || p.startsWith(path + '/'))) throw new Error('File is being written.');327 try { const [parent, name] = await parentFor(path); await parent.removeEntry(name, { recursive: true }); }328 catch (error) { if (error.name !== 'NotFoundError') throw error; }329 for (const key of inventory.keys()) if (key === path || key.startsWith(path + '/')) forget(key);330 forgetDirectories(path);331 return true;332 }),333 url: async path => {334 segments(path); await ready; await flush(); assertOpen();335 if (!inventory.has(path)) throw new Error('Offline file no longer exists.');336 await prepareMediaWorker();337 return new URL(mediaPrefix + segments(path).map(encodeURIComponent).join('/'), mediaBase).href;338 },339 close: async () => {340 if (retired) return;341 await ready.catch(() => {});342 if (writers.size) throw new Error('File writers are still active.');343 await flush(); retired = true; inventory.clear(); children.clear(); directories.clear(); knownDirectories.clear(); directoryChildren.clear(); textCache.clear(); stores.delete(rootPath);344 },345 };346 stores.set(rootPath, store);347 return store;348 }349 async function deleteProfile(rootPath) {350 if (!/^\/yokan\/profiles\/p_[0-9a-f]{32}$/.test(rootPath)) throw new Error('Cannot delete this profile root.');351 if (stores.has(rootPath)) throw new Error('Close the profile before deleting its storage.');352 if (!navigator.storage?.getDirectory) return;353 try {354 let directory = await navigator.storage.getDirectory();355 for (const segment of rootPath.split('/').slice(1, -1)) directory = await directory.getDirectoryHandle(segment);356 await directory.removeEntry(rootPath.split('/').at(-1), { recursive: true });357 } catch (error) { if (error.name !== 'NotFoundError') throw error; }358 }359 function selectedMedia(selected) {360 if (selected.length > 10000) throw new Error('Select at most 10000 files.');361 let files = Array.from(selected), closed = false;362 return {363 metadata: () => {364 if (closed) throw new Error('File selection is closed.');365 return JSON.stringify(files.map(file => ({ path: file.webkitRelativePath || file.name, size: file.size })));366 },367 chunk: async (index, offset) => {368 if (closed) throw new Error('File selection is closed.');369 const file = files[index];370 if (!file || !Number.isSafeInteger(offset) || offset < 0 || offset >= file.size) throw new Error('Invalid selected-file read.');371 // Bounded slice reads avoid whole-file FileReader/arrayBuffer allocations, including videos.372 const bytes = new Uint8Array(await file.slice(offset, Math.min(file.size, offset + 65536)).arrayBuffer());373 if (closed) throw new Error('File selection is closed.');374 return encode(bytes);375 },376 close: () => { closed = true; files = []; },377 };378 }379 function pickMedia(directory) {380 const input = document.createElement('input');381 input.type = 'file'; input.hidden = true; input.multiple = true;382 if (directory) input.setAttribute('webkitdirectory', '');383 document.body.append(input);384 let finished = false, selection = null, resolveResult, rejectResult;385 const result = new Promise((resolve, reject) => { resolveResult = resolve; rejectResult = reject; });386 const cleanup = () => { input.onchange = null; input.oncancel = null; input.remove(); };387 const cancel = () => {388 selection?.close();389 if (!finished) { finished = true; cleanup(); resolveResult(null); }390 };391 input.oncancel = cancel;392 input.onchange = () => {393 if (finished) return;394 finished = true;395 try { selection = input.files?.length ? selectedMedia(input.files) : null; resolveResult(selection); }396 catch (error) { rejectResult(error); }397 finally { cleanup(); }398 };399 try { input.click(); } catch (error) { finished = true; cleanup(); rejectResult(error); }400 return { result, cancel };401 }402 globalThis.yokanBrowserFiles = { open: openStore, deleteProfile, pickMedia, selectedMedia };403})();404