@ghostlytools/cli 1.6.1 → 1.7.1
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/README.md +36 -12
- package/dist/assets/{api-BpNU2LQh.js → api-CD9JbPuA.js} +99 -28
- package/dist/assets/api-CD9JbPuA.js.map +1 -0
- package/dist/assets/{api-Cx8ZCntM.js → api-CJM3R93b.js} +2 -2
- package/dist/assets/{apiKit-d1wi3raD.js → apiKit-BmnROpCN.js} +8 -4
- package/dist/assets/{apiKit-d1wi3raD.js.map → apiKit-BmnROpCN.js.map} +1 -1
- package/dist/assets/{apps-C-HiIRCA.js → apps-CJ2dvKSz.js} +1 -1
- package/dist/assets/{apps-B1QjRWqq.js → apps-DVA60Tg6.js} +34 -11
- package/dist/assets/apps-DVA60Tg6.js.map +1 -0
- package/dist/assets/{arkade-B5g4r3Ea.js → arkade-CHqwEHFd.js} +2 -2
- package/dist/assets/{arkade-B5g4r3Ea.js.map → arkade-CHqwEHFd.js.map} +1 -1
- package/dist/assets/{backup-Boqn5Y35.js → backup-B4dSNvzb.js} +5 -5
- package/dist/assets/{backup-Boqn5Y35.js.map → backup-B4dSNvzb.js.map} +1 -1
- package/dist/assets/{backup-BS9HwGyn.js → backup-C4CbTEcj.js} +1 -1
- package/dist/assets/{blobFiles-B6nf0gCG.js → blobFiles-Bckz9fjp.js} +2 -2
- package/dist/assets/{blobFiles-B6nf0gCG.js.map → blobFiles-Bckz9fjp.js.map} +1 -1
- package/dist/assets/buttons-BMVGYXpR.js +2 -0
- package/dist/assets/{buttons-Bjc51aod.js → buttons-C13rK2mH.js} +3 -3
- package/dist/assets/{buttons-Bjc51aod.js.map → buttons-C13rK2mH.js.map} +1 -1
- package/dist/assets/{daemonProof-ui8jtIw0.js → daemonProof-B41oSfon.js} +2 -2
- package/dist/assets/{daemonProof-ui8jtIw0.js.map → daemonProof-B41oSfon.js.map} +1 -1
- package/dist/assets/{envelope-DvZMFRzg.js → envelope-4TXDx3vD.js} +2 -2
- package/dist/assets/{envelope-DvZMFRzg.js.map → envelope-4TXDx3vD.js.map} +1 -1
- package/dist/assets/{fileBytes-BMEBas7S.js → fileBytes-BD0v3rRG.js} +10 -2
- package/dist/assets/{fileBytes-BMEBas7S.js.map → fileBytes-BD0v3rRG.js.map} +1 -1
- package/dist/assets/{fileBytes-CtwagJ8h.js → fileBytes-OolN5cSY.js} +1 -1
- package/dist/assets/{fileBytes-CFNrRfcl.js → fileBytes-_fd-2JRY.js} +2 -2
- package/dist/assets/{fileBytes-CFNrRfcl.js.map → fileBytes-_fd-2JRY.js.map} +1 -1
- package/dist/assets/fileBytesIdb-CsSQcSxD.js +2 -0
- package/dist/assets/{fileBytesIdb-BXAN7i-N.js → fileBytesIdb-NtA8r9EM.js} +2 -2
- package/dist/assets/{fileBytesIdb-BXAN7i-N.js.map → fileBytesIdb-NtA8r9EM.js.map} +1 -1
- package/dist/assets/{fileBytesOpfs-Do1Vpkis.js → fileBytesOpfs-B8fJwkwM.js} +3 -3
- package/dist/assets/{fileBytesOpfs-Do1Vpkis.js.map → fileBytesOpfs-B8fJwkwM.js.map} +1 -1
- package/dist/assets/{ghostly_iroh_web-BXCsSxxo.js → ghostly_iroh_web-CO0onry8.js} +33 -27
- package/dist/assets/ghostly_iroh_web-CO0onry8.js.map +1 -0
- package/dist/assets/ghostly_iroh_web_bg.wasm +0 -0
- package/dist/assets/{groupFiles-y4lGrOC-.js → groupFiles-ajZgZ6P8.js} +41 -25
- package/dist/assets/groupFiles-ajZgZ6P8.js.map +1 -0
- package/dist/assets/{host-DFGS8vJE.js → host-CVeNtA2_.js} +43 -20
- package/dist/assets/host-CVeNtA2_.js.map +1 -0
- package/dist/assets/{hyperdhtRelay-CZLnOc4e.js → hyperdhtRelay-CI2ISE-g.js} +2 -2
- package/dist/assets/{hyperdhtRelay-CZLnOc4e.js.map → hyperdhtRelay-CI2ISE-g.js.map} +1 -1
- package/dist/assets/{irohWeb-Y9wt8zG7.js → irohWeb-DcRJdhce.js} +3 -3
- package/dist/assets/{irohWeb-Y9wt8zG7.js.map → irohWeb-DcRJdhce.js.map} +1 -1
- package/dist/assets/{main-xgWC0qPZ.js → main-CjO0KGiF.js} +272 -79
- package/dist/assets/main-CjO0KGiF.js.map +1 -0
- package/dist/assets/{mainline-CjQ3pmvq.js → mainline-WM-WItCV.js} +27 -8
- package/dist/assets/mainline-WM-WItCV.js.map +1 -0
- package/dist/assets/{networkReason-i9wu5ZJs.js → networkReason-380j5yMs.js} +2 -2
- package/dist/assets/{networkReason-i9wu5ZJs.js.map → networkReason-380j5yMs.js.map} +1 -1
- package/dist/assets/{nwc-yO0nHt9S.js → nwc-D5dkC1xg.js} +3 -3
- package/dist/assets/{nwc-yO0nHt9S.js.map → nwc-D5dkC1xg.js.map} +1 -1
- package/dist/assets/{nwcProvider-BEg4I5Bk.js → nwcProvider-p_rMwtDv.js} +2 -2
- package/dist/assets/{nwcProvider-BEg4I5Bk.js.map → nwcProvider-p_rMwtDv.js.map} +1 -1
- package/dist/assets/{profiles-CEnZfN78.js → profiles-BFd0tpCZ.js} +91 -19
- package/dist/assets/profiles-BFd0tpCZ.js.map +1 -0
- package/dist/assets/{registry-CBDcdRPx.js → registry-BKffx4ZU.js} +1 -1
- package/dist/assets/{registry-DyGu5C-Z.js → registry-BfNcA6kF.js} +3 -3
- package/dist/assets/registry-BfNcA6kF.js.map +1 -0
- package/dist/assets/{resolve-CnkY--2E.js → resolve-hUsgRkmm.js} +2 -2
- package/dist/assets/{resolve-CnkY--2E.js.map → resolve-hUsgRkmm.js.map} +1 -1
- package/dist/assets/{server-CH142eWc.js → server-C3tJZFnv.js} +422 -149
- package/dist/assets/server-C3tJZFnv.js.map +1 -0
- package/dist/assets/{src-BXeGLwWV.js → src-BMHgbkli.js} +246 -62
- package/dist/assets/src-BMHgbkli.js.map +1 -0
- package/dist/assets/translate-DJUutSis.js +1067 -0
- package/dist/assets/translate-DJUutSis.js.map +1 -0
- package/dist/assets/types-C4_KafL_.js.map +1 -1
- package/dist/assets/{usdt-CdSNFUzO.js → usdt-glkUxsDe.js} +3 -3
- package/dist/assets/{usdt-CdSNFUzO.js.map → usdt-glkUxsDe.js.map} +1 -1
- package/dist/assets/{words-DA5feEav.js → words-DyW9b27T.js} +2 -2
- package/dist/assets/{words-DA5feEav.js.map → words-DyW9b27T.js.map} +1 -1
- package/dist/ghostly.mjs +1 -1
- package/package.json +1 -1
- package/dist/assets/api-BpNU2LQh.js.map +0 -1
- package/dist/assets/apps-B1QjRWqq.js.map +0 -1
- package/dist/assets/buttons-CugVarw3.js +0 -2
- package/dist/assets/fileBytesIdb-C20oXDdr.js +0 -2
- package/dist/assets/ghostly_iroh_web-BXCsSxxo.js.map +0 -1
- package/dist/assets/groupFiles-y4lGrOC-.js.map +0 -1
- package/dist/assets/host-DFGS8vJE.js.map +0 -1
- package/dist/assets/main-xgWC0qPZ.js.map +0 -1
- package/dist/assets/mainline-CjQ3pmvq.js.map +0 -1
- package/dist/assets/profiles-CEnZfN78.js.map +0 -1
- package/dist/assets/registry-DyGu5C-Z.js.map +0 -1
- package/dist/assets/server-CH142eWc.js.map +0 -1
- package/dist/assets/src-BXeGLwWV.js.map +0 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"daemonProof-ui8jtIw0.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = Date.now, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n"],"mappings":";;;;AAMA,IAAa,aAAa;CAAC;CAAM;CAAO;CAAO;CAAO;AAAK;AAE3D,IAAa,eAAyB;AAEtC,IAAa,gBAAgB,SAA4B,OAAA,KAAmB;AAC5E,IAAa,cAAc,SAA2B,aAAa,IAAI,IAAI;AAC3E,IAAa,aAAa,MAAgB,UAA0B,KAAK,MAAO,QAAQ,IAAI,OAAQ,GAAI;AAExG,SAAgB,WAAW,OAAmC;CAC5D,OAAO,WAAW,SAAS,KAAiB;AAC9C;;AAGA,IAAa,eAAe;;;;;AAY5B,IAAa,gBAAb,MAA2B;CAWJ;CAAiC;CAVtD,SAA2B,CAAC;CAC5B,OAAe;CACf,SAAiB;CACjB,WAAmB;CACnB;CACA;CACA;;CAEA,UAAU;CAEV,YAAY,MAAyB,MAAqC,KAAK,KAAK,QAAQ,cAAc;EAArF,KAAA,OAAA;EAAiC,KAAA,MAAA;EACpD,KAAK,QAAQ,WAAW,IAAI;EAE5B,KAAK,MAAM,KAAK,MAAO,OAAO,QAAS,GAAI,IAAI;EAC/C,KAAK,UAAU,OAAO,MAAM,KAAK,KAAK;CACxC;;CAGA,KAAK,OAAuB;EAC1B,IAAI,CAAC,MAAM,QAAQ,OAAO;EAC1B,KAAK,WAAW,KAAK,IAAI;EACzB,MAAM,OAAO,KAAK,MAAM,KAAK;EAC7B,MAAM,OAAO,MAAM,UAAU,OAAO,QAAQ,MAAM,SAAS,GAAG,KAAK,IAAI,GAAG,IAAI,CAAC;EAC/E,MAAM,OAAO,MAAM,SAAS,KAAK;EACjC,KAAK,WA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I,OAAO,KAAK,MAAM,KAAK,IAAI;CAClE,QAAQ;EAAE,OAAO;CAAM;AACzB;;AAGA,SAAgB,aAAa,QAAgB,OAAe,QAA0B;CACpF,MAAM,QAAS,QAAuC;CACtD,IAAI,OAAO,UAAU,YAAY,CAAC,iBAAiB,KAAK,KAAK,GAAG,OAAO;CACvE,OAAO,gBAAgB,OAAO,KAAK,OAAO,KAAK,GAAG,OAAO,KAAK,MAAM,QAAQ,UAAU,KAAK,GAAG,KAAK,CAAC;AACtG"}
|
|
1
|
+
{"version":3,"file":"daemonProof-B41oSfon.js","names":[],"sources":["../../src/calls/pcm.ts","../../src/daemonProof.ts"],"sourcesContent":["/**\n * The audio a call hands to an outside program, and takes from it (WISP 1100 § Calls): raw PCM, signed 16-bit\n * little-endian, mono, at the call's rate, in frames of 20 ms. Opus runs at every one of these rates itself, so\n * nothing is resampled.\n */\nexport const FRAME_MS = 20;\nexport const CALL_RATES = [8000, 12000, 16000, 24000, 48000] as const;\nexport type CallRate = (typeof CALL_RATES)[number];\nexport const DEFAULT_RATE: CallRate = 48000;\n\nexport const frameSamples = (rate: CallRate): number => (rate * FRAME_MS) / 1000;\nexport const frameBytes = (rate: CallRate): number => frameSamples(rate) * 2;\nexport const bytesToMs = (rate: CallRate, bytes: number): number => Math.round((bytes / 2 / rate) * 1000);\n\nexport function isCallRate(value: unknown): value is CallRate {\n return CALL_RATES.includes(value as CallRate);\n}\n\n/** The most a program may queue ahead of the call: five minutes of speech. What goes past it is dropped. */\nexport const MAX_QUEUE_MS = 5 * 60_000;\n\n/**\n * A partial frame waits this long for the rest of it before it is played padded with silence: a program writing at\n * real time, a little late, is not cut into gaps; a program that stopped mid-frame is still heard to its end.\n */\nexport const PARTIAL_WAIT_MS = 60;\n\n/**\n * What the program wrote, waiting to be sent: taken one 20 ms frame per tick, silence when there is nothing, and\n * dropped whole by a flush (barge-in). The program may write any amount at any time, faster than real time too.\n */\nexport class PlaybackQueue {\n private chunks: Buffer[] = [];\n private head = 0;\n private length = 0;\n private lastPush = 0;\n private readonly frame: number;\n private readonly max: number;\n private readonly silence: Buffer;\n /** Bytes dropped because the queue was full, since the start. */\n dropped = 0;\n\n constructor(readonly rate: CallRate, private readonly now: () => number = Date.now, maxMs = MAX_QUEUE_MS) {\n this.frame = frameBytes(rate);\n // Whole samples only: an odd byte waits for its other half.\n this.max = Math.floor((rate * maxMs) / 1000) * 2;\n this.silence = Buffer.alloc(this.frame);\n }\n\n /** Adds what the program wrote. Returns the bytes it could not keep (the queue was full). */\n push(chunk: Buffer): number {\n if (!chunk.length) return 0;\n this.lastPush = this.now();\n const room = this.max - this.length;\n const kept = chunk.length <= room ? chunk : chunk.subarray(0, Math.max(0, room));\n const lost = chunk.length - kept.length;\n this.dropped += lost;\n if (kept.length) { this.chunks.push(Buffer.from(kept)); this.length += kept.length; }\n return lost;\n }\n\n /** Queued audio, in milliseconds (whole frames and a partial one). */\n get queuedMs(): number {\n return bytesToMs(this.rate, this.length - (this.length % 2));\n }\n\n /** One frame to send now, and whether it is the program's audio or silence. */\n next(): { frame: Buffer; silent: boolean } {\n if (this.length >= this.frame) return { frame: this.take(this.frame), silent: false };\n const whole = this.length - (this.length % 2);\n if (whole > 0 && this.now() - this.lastPush >= PARTIAL_WAIT_MS) {\n const frame = Buffer.alloc(this.frame);\n this.take(whole).copy(frame);\n return { frame, silent: false };\n }\n return { frame: this.silence, silent: true };\n }\n\n /** Drops everything queued; returns how much, in milliseconds. */\n flush(): number {\n const ms = this.queuedMs;\n this.chunks = [];\n this.head = 0;\n this.length = 0;\n return ms;\n }\n\n /** Drops up to that much from the front, in whole frames (audio whose time went by); returns how much, in milliseconds. */\n skip(ms: number): number {\n const frames = Math.min(Math.floor(ms / FRAME_MS), Math.floor(this.length / this.frame));\n if (frames > 0) this.take(frames * this.frame);\n return Math.max(0, frames) * FRAME_MS;\n }\n\n private take(bytes: number): Buffer {\n const out = Buffer.allocUnsafe(bytes);\n let filled = 0;\n while (filled < bytes) {\n const chunk = this.chunks[0];\n const n = Math.min(bytes - filled, chunk.length - this.head);\n chunk.copy(out, filled, this.head, this.head + n);\n filled += n;\n this.head += n;\n if (this.head === chunk.length) { this.chunks.shift(); this.head = 0; }\n }\n this.length -= bytes;\n return out;\n }\n}\n","import { createHmac, randomBytes, timingSafeEqual } from \"node:crypto\";\nimport { closeSync, lstatSync, openSync, readFileSync, rmSync, writeSync } from \"node:fs\";\nimport { join } from \"node:path\";\nimport { lockPath } from \"./profiles\";\n\n/**\n * How a client knows the process on the profile's socket is the profile's daemon (WISP 1100 § Local control API).\n * On Windows the socket is a named pipe whose name follows from the profile's path, and any account of the machine\n * may open that name first; the pipe itself has no owner a client can check. So the daemon writes a fresh random\n * secret in the profile's owner-only folder at every start, and the client sends nothing but a `daemon.hello` with a\n * nonce of its own until the answer proves, over that nonce, that its sender read the secret. Same on every platform.\n *\n * Before even the hello, the daemon speaks first: a greeting that proves, with the same secret, its pid (the\n * profile's lock holder) and the time. The client writes nothing at all until the greeting checks out. A process\n * holding `SeImpersonatePrivilege` that opened the pipe's name first can impersonate the client from the first\n * message it reads (Node's pipe client sets no security quality of service, so the level is SecurityImpersonation),\n * and Windows refuses to impersonate a pipe's client until data has been read from it (ERROR_CANNOT_IMPERSONATE):\n * a client that writes nothing to it cannot be impersonated.\n */\nexport const HELLO = \"daemon.hello\";\n\n/**\n * How far a greeting's time may be from the client's clock (the same machine's): a greeting is no fresh challenge, so\n * one copied from a daemon that has since died could otherwise stand in for it as long as its secret file is left.\n */\nexport const GREETING_WINDOW_MS = 10_000;\n\nexport interface Greeting { pid: number; at: number; proof: string }\n\nexport function daemonSecretPath(dir: string): string {\n return join(dir, \"daemon.secret\");\n}\n\n/** HMAC-SHA256 over the role's domain and the nonce, hex: a daemon's proof is never a client's, nor one for another nonce. */\nexport function proof(secret: Buffer, role: \"daemon\" | \"client\" | \"greeting\", nonce: string): string {\n return createHmac(\"sha256\", secret).update(`ghostly-${role}:${nonce}`).digest(\"hex\");\n}\n\nexport function newNonce(): string {\n return randomBytes(16).toString(\"hex\");\n}\n\n/**\n * The daemon's: a new secret, 32 random bytes as hex, made 0600 (`wx`, so a file or link put there in the meantime is\n * an error, not something written through). The one a daemon before it left is removed first: whoever could have\n * read that one learns nothing about this one.\n */\nexport function newDaemonSecret(dir: string): Buffer {\n const file = daemonSecretPath(dir);\n rmSync(file, { force: true });\n const secret = randomBytes(32);\n const fd = openSync(file, \"wx\", 0o600);\n try { writeSync(fd, secret.toString(\"hex\") + \"\\n\"); } finally { closeSync(fd); }\n return secret;\n}\n\n/** The daemon's, when it stops: a greeting copied from it proves nothing once it is gone. */\nexport function removeDaemonSecret(dir: string): void {\n rmSync(daemonSecretPath(dir), { force: true });\n}\n\n/** The daemon's first line on every connection, before it has read anything. */\nexport function greeting(secret: Buffer, pid = process.pid, at = Date.now()): { greeting: Greeting } {\n return { greeting: { pid, at, proof: proof(secret, \"greeting\", `${pid}:${at}`) } };\n}\n\n/**\n * Whether `message` (the first line the client read) is the profile's daemon's greeting: proved with the secret, made\n * within `GREETING_WINDOW_MS` of `now`, by the process that holds the profile's lock, alive and one this user may\n * signal (`process.kill(pid, 0)`: EPERM on Unix for another user's; on Windows libuv opens the process to terminate\n * it, which another account's process normally denies). A greeting copied from a daemon that died fails on its pid,\n * unless a process this user may signal took that pid within the window.\n */\nexport function provesGreeting(secret: Buffer, dir: string, message: unknown, now = Date.now()): boolean {\n const given = (message as { greeting?: Partial<Greeting> } | null)?.greeting;\n if (!given || !Number.isSafeInteger(given.pid) || (given.pid as number) <= 0 || !Number.isSafeInteger(given.at)) return false;\n if (typeof given.proof !== \"string\" || !/^[0-9a-f]{64}$/.test(given.proof)) return false;\n const { pid, at } = given as Greeting;\n if (Math.abs(now - at) > GREETING_WINDOW_MS) return false;\n if (!timingSafeEqual(Buffer.from(given.proof, \"hex\"), Buffer.from(proof(secret, \"greeting\", `${pid}:${at}`), \"hex\"))) return false;\n return holdsProfile(dir, pid);\n}\n\n/**\n * Whether a daemon of this release holds the profile: its secret is there (an older release's never writes one, and a\n * daemon removes its own when it stops) and the lock's holder is alive and this user's. One whose greeting is late is\n * busy (its event loop held by one long task), not something else on its socket: the client waits for it.\n */\nexport function daemonOfThisRelease(dir: string): boolean {\n if (!readDaemonSecret(dir)) return false;\n let pid: number;\n try { pid = Number(readFileSync(lockPath(dir), \"utf8\").trim()); } catch { return false; }\n return Number.isSafeInteger(pid) && pid > 0 && holdsProfile(dir, pid);\n}\n\nfunction holdsProfile(dir: string, pid: number): boolean {\n try {\n if (readFileSync(lockPath(dir), \"utf8\").trim() !== String(pid)) return false;\n process.kill(pid, 0);\n return true;\n } catch { return false; }\n}\n\n/**\n * The client's: the secret the profile's daemon wrote, or null when there is none, or it is not a file of this user's\n * alone (a link, another user's file, one others may read): then it proves nothing. On Windows the file has the\n * folder's ACL (owner-only in the user's home); Node can check no more than that it is a plain file.\n */\nexport function readDaemonSecret(dir: string): Buffer | null {\n const file = daemonSecretPath(dir);\n try {\n const info = lstatSync(file);\n if (!info.isFile()) return null;\n if (process.platform !== \"win32\" && ((process.getuid && info.uid !== process.getuid()) || (info.mode & 0o077) !== 0)) return null;\n const text = readFileSync(file, \"utf8\").trim();\n return /^[0-9a-f]{64}$/.test(text) ? Buffer.from(text, \"hex\") : null;\n } catch { return null; }\n}\n\n/** Whether `answer` (the result of a `daemon.hello` with `nonce`) is the daemon's proof over it, in constant time. */\nexport function provesDaemon(secret: Buffer, nonce: string, answer: unknown): boolean {\n const given = (answer as { proof?: unknown } | null)?.proof;\n if (typeof given !== \"string\" || !/^[0-9a-f]{64}$/.test(given)) return false;\n return timingSafeEqual(Buffer.from(given, \"hex\"), Buffer.from(proof(secret, \"daemon\", nonce), \"hex\"));\n}\n"],"mappings":";;;;AAMA,IAAa,aAAa;CAAC;CAAM;CAAO;CAAO;CAAO;AAAK;AAE3D,IAAa,eAAyB;AAEtC,IAAa,gBAAgB,SAA4B,OAAA,KAAmB;AAC5E,IAAa,cAAc,SAA2B,aAAa,IAAI,IAAI;AA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Base64Url(text) {
|
|
4
4
|
if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error("Invalid base64url");
|
|
@@ -87,4 +87,4 @@ async function open(text, passphrase) {
|
|
|
87
87
|
//#endregion
|
|
88
88
|
export { fromBase64Url as i, MAX_BACKUP_BYTES as n, open as r, BACKUP_MEDIA_TYPE as t };
|
|
89
89
|
|
|
90
|
-
//# sourceMappingURL=envelope-
|
|
90
|
+
//# sourceMappingURL=envelope-4TXDx3vD.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"envelope-DvZMFRzg.js","names":[],"sources":["../../../browser/src/backup/codec.ts","../../../browser/src/backup/envelope.ts"],"sourcesContent":["import { toBase64Url } from \"@ghostly/core\";\n\n/**\n * Base64url without padding. Core's encoder, not `btoa`: every picture, voice note and kept file (up to 16 MiB each)\n * goes through it on the page's thread, where `btoa` spends over a second per 16 MiB.\n */\nexport { toBase64Url };\nexport function fromBase64Url(text: string): Uint8Array {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error(\"Invalid base64url\");\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\".repeat((4 - (text.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\ntype Tagged = { $ghostly: \"bigint\" | \"bytes\" | \"blob\"; value: string; type?: string };\n/** Data that happens to look like a tag (a contact can send anything) travels as its entries instead. */\ntype Escaped = { $ghostly: \"object\"; entries: [string, unknown][] };\n\n/**\n * Blobs cannot be read synchronously: turn them into tagged values first, everywhere in the tree. An\n * object of the data's own with a `$ghostly` key is escaped, so it comes back as it was and not as a tag.\n */\nasync function inlineBlobs(value: unknown): Promise<unknown> {\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return { $ghostly: \"blob\", type: value.type, value: toBase64Url(new Uint8Array(await value.arrayBuffer())) } satisfies Tagged;\n if (Array.isArray(value)) return Promise.all(value.map(inlineBlobs));\n if (value && typeof value === \"object\" && !(value instanceof Uint8Array) && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) out[k] = await inlineBlobs(v);\n return Object.prototype.hasOwnProperty.call(out, \"$ghostly\") ? ({ $ghostly: \"object\", entries: Object.entries(out) } satisfies Escaped) : out;\n }\n return value;\n}\n\n/** JSON that also carries what IndexedDB holds: bigints, bytes and blobs (WISP 05). */\nexport async function encode(value: unknown): Promise<string> {\n return JSON.stringify(await inlineBlobs(value), (_key, v) => {\n if (typeof v === \"bigint\") return { $ghostly: \"bigint\", value: String(v) } satisfies Tagged;\n if (v instanceof Uint8Array) return { $ghostly: \"bytes\", value: toBase64Url(v) } satisfies Tagged;\n if (v instanceof ArrayBuffer) return { $ghostly: \"bytes\", value: toBase64Url(new Uint8Array(v)) } satisfies Tagged;\n return v;\n });\n}\n/** Never throws on a tag it cannot read: that value stays as it is, and the rest of the backup restores. */\nexport function decode(text: string): unknown {\n return JSON.parse(text, (_key, v) => {\n const escaped = v as Partial<Escaped> | null;\n if (escaped && typeof escaped === \"object\" && escaped.$ghostly === \"object\" && Array.isArray(escaped.entries)) {\n const out: Record<string, unknown> = {};\n for (const entry of escaped.entries) if (Array.isArray(entry) && typeof entry[0] === \"string\") Object.defineProperty(out, entry[0], { value: entry[1], enumerable: true, writable: true, configurable: true });\n return out;\n }\n const tag = v as Partial<Tagged> | null;\n if (!tag || typeof tag !== \"object\" || typeof tag.$ghostly !== \"string\" || typeof tag.value !== \"string\") return v;\n if (tag.$ghostly === \"bigint\") return /^-?\\d+$/.test(tag.value) ? BigInt(tag.value) : v;\n if (!/^[A-Za-z0-9_-]*$/.test(tag.value)) return v;\n if (tag.$ghostly === \"bytes\") return fromBase64Url(tag.value);\n if (tag.$ghostly === \"blob\") return new Blob([fromBase64Url(tag.value) as BlobPart], { type: typeof tag.type === \"string\" ? tag.type : \"\" });\n return v;\n });\n}\n","import { fromBase64Url, toBase64Url } from \"./codec\";\n\n/** The clear part of a bundle (WISP 05): only what decryption needs. */\nexport interface Envelope {\n format: \"ghostly-backup\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n compression: \"gzip\" | \"none\";\n ciphertext: string;\n}\nexport const BACKUP_MEDIA_TYPE = \"application/vnd.ghostly.backup+json\";\nconst ITERATIONS = 600_000;\n\nasync function keyFrom(passphrase: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(passphrase), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"PBKDF2\", hash: \"SHA-256\", salt: salt as BufferSource, iterations }, material, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n}\n/** A profile with years of files is large, but not this large: past it, a bundle is refused, not read. */\nexport const MAX_BACKUP_BYTES = 1024 * 1024 * 1024;\n\nasync function through(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {\n const reader = new Blob([bytes as BlobPart]).stream().pipeThrough(stream).getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (let next = await reader.read(); !next.done; next = await reader.read()) {\n size += next.value.length;\n if (size > MAX_BACKUP_BYTES) { await reader.cancel(); throw new Error(\"This backup is too large to restore\"); }\n chunks.push(next.value);\n }\n const out = new Uint8Array(size);\n let at = 0;\n for (const chunk of chunks) { out.set(chunk, at); at += chunk.length; }\n return out;\n}\n\n/**\n * The clear header is authenticated with the ciphertext (AES-GCM associated data): changing any of it,\n * the compression included, makes the bundle fail to open instead of being read differently.\n */\nconst header = (e: Pick<Envelope, \"format\" | \"version\" | \"kdf\" | \"cipher\" | \"compression\">) =>\n new TextEncoder().encode([e.format, e.version, e.kdf.name, e.kdf.iterations, e.kdf.salt, e.cipher.name, e.cipher.iv, e.compression].join(\"\\n\"));\nconst canCompress = () => typeof CompressionStream !== \"undefined\";\n\n/** Compresses and encrypts a payload under a passphrase the person chose. */\nexport async function seal(payload: string, passphrase: string): Promise<string> {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the backup passphrase\");\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const plain = new TextEncoder().encode(payload);\n const compression = canCompress() ? \"gzip\" : \"none\";\n const body = compression === \"gzip\" ? await through(plain, new CompressionStream(\"gzip\")) : plain;\n const clear = { format: \"ghostly-backup\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, compression } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await keyFrom(passphrase, salt, ITERATIONS), body as BufferSource));\n const envelope: Envelope = { ...clear, ciphertext: toBase64Url(ciphertext) };\n return JSON.stringify(envelope);\n}\n\n/** Checks, decrypts and decompresses a bundle. Nothing from a bundle is used before this succeeds. */\nexport async function open(text: string, passphrase: string): Promise<string> {\n if (text.length > MAX_BACKUP_BYTES * 1.4) throw new Error(\"This backup is too large to restore\");\n let envelope: Envelope;\n try { envelope = JSON.parse(text) as Envelope; } catch { throw new Error(\"This is not a Ghostly backup\"); }\n if (envelope?.format !== \"ghostly-backup\") throw new Error(\"This is not a Ghostly backup\");\n if (envelope.version !== 1) throw new Error(\"This backup comes from a newer Ghostly; update to restore it\");\n if (envelope.kdf?.name !== \"PBKDF2-SHA256\" || !(envelope.kdf.iterations >= ITERATIONS) || envelope.kdf.iterations > 10_000_000 || envelope.cipher?.name !== \"AES-256-GCM\" || ![\"gzip\", \"none\"].includes(envelope.compression)) throw new Error(\"Unsupported backup encryption\");\n let body: Uint8Array;\n try {\n body = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: fromBase64Url(envelope.cipher.iv) as BufferSource, additionalData: header(envelope) as BufferSource }, await keyFrom(passphrase, fromBase64Url(envelope.kdf.salt), envelope.kdf.iterations), fromBase64Url(envelope.ciphertext) as BufferSource));\n } catch { throw new Error(\"Wrong passphrase, or the backup was changed\"); }\n const plain = envelope.compression === \"gzip\" ? await through(body, new DecompressionStream(\"gzip\")) : body;\n return new TextDecoder().decode(plain);\n}\n"],"mappings":";;AAOA,SAAgB,cAAc,MAA0B;CACtD,IAAI,CAAC,mBAAmB,KAAK,IAAI,GAAG,MAAM,IAAI,MAAM,mBAAmB;CACvE,MAAM,SAAS,KAAK,KAAK,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG,IAAI,IAAI,QAAQ,IAAK,KAAK,SAAS,KAAM,CAAC,CAAC;CACxG,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;CACtE,OAAO;AACT;;;ACFA,IAAa,oBAAoB;AACjC,IAAM,aAAa;AAEnB,eAAe,QAAQ,YAAoB,MAAkB,YAAwC;CACnG,MAAM,WAAW,MAAM,OAAO,OAAO,UAAU,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,UAAU,GAAG,UAAU,OAAO,CAAC,WAAW,CAAC;CAC1H,OAAO,OAAO,OAAO,UAAU;EAAE,MAAM;EAAU,MAAM;EAAiB;EAAsB;CAAW,GAAG,UAAU;EAAE,MAAM;EAAW,QAAQ;CAAI,GAAG,OAAO,CAAC,WAAW,SAAS,CAAC;AACvL;;AAEA,IAAa,mBAAmB;AAEhC,eAAe,QAAQ,OAAmB,QAAsE;CAC9G,MAAM,SAAS,IAAI,KAAK,CAAC,KAAiB,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,YAAY,MAAM,CAAC,CAAC,UAAU;CACpF,MAAM,SAAuB,CAAC;CAC9B,IAAI,OAAO;CACX,KAAK,IAAI,OAAO,MAAM,OAAO,KA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,EAAE;GAAmB,gBAAgB,OAAO,QAAQ;EAAkB,GAAG,MAAM,QAAQ,YAAY,cAAc,SAAS,IAAI,IAAI,GAAG,SAAS,IAAI,UAAU,GAAG,cAAc,SAAS,UAAU,CAAiB,CAAC;CAC3T,QAAQ;EAAE,MAAM,IAAI,MAAM,6CAA6C;CAAG;CAC1E,MAAM,QAAQ,SAAS,gBAAgB,SAAS,MAAM,QAAQ,MAAM,IAAI,oBAAoB,MAAM,CAAC,IAAI;CACvG,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;AACvC"}
|
|
1
|
+
{"version":3,"file":"envelope-4TXDx3vD.js","names":[],"sources":["../../../browser/src/backup/codec.ts","../../../browser/src/backup/envelope.ts"],"sourcesContent":["import { toBase64Url } from \"@ghostly/core\";\n\n/**\n * Base64url without padding. Core's encoder, not `btoa`: every picture, voice note and kept file (up to 16 MiB each)\n * goes through it on the page's thread, where `btoa` spends over a second per 16 MiB.\n */\nexport { toBase64Url };\nexport function fromBase64Url(text: string): Uint8Array {\n if (!/^[A-Za-z0-9_-]*$/.test(text)) throw new Error(\"Invalid base64url\");\n const binary = atob(text.replace(/-/g, \"+\").replace(/_/g, \"/\") + \"=\".repeat((4 - (text.length % 4)) % 4));\n const bytes = new Uint8Array(binary.length);\n for (let i = 0; i < binary.length; i++) bytes[i] = binary.charCodeAt(i);\n return bytes;\n}\n\ntype Tagged = { $ghostly: \"bigint\" | \"bytes\" | \"blob\"; value: string; type?: string };\n/** Data that happens to look like a tag (a contact can send anything) travels as its entries instead. */\ntype Escaped = { $ghostly: \"object\"; entries: [string, unknown][] };\n\n/**\n * Blobs cannot be read synchronously: turn them into tagged values first, everywhere in the tree. An\n * object of the data's own with a `$ghostly` key is escaped, so it comes back as it was and not as a tag.\n */\nasync function inlineBlobs(value: unknown): Promise<unknown> {\n if (typeof Blob !== \"undefined\" && value instanceof Blob) return { $ghostly: \"blob\", type: value.type, value: toBase64Url(new Uint8Array(await value.arrayBuffer())) } satisfies Tagged;\n if (Array.isArray(value)) return Promise.all(value.map(inlineBlobs));\n if (value && typeof value === \"object\" && !(value instanceof Uint8Array) && !(value instanceof ArrayBuffer) && !ArrayBuffer.isView(value)) {\n const out: Record<string, unknown> = {};\n for (const [k, v] of Object.entries(value)) out[k] = await inlineBlobs(v);\n return Object.prototype.hasOwnProperty.call(out, \"$ghostly\") ? ({ $ghostly: \"object\", entries: Object.entries(out) } satisfies Escaped) : out;\n }\n return value;\n}\n\n/** JSON that also carries what IndexedDB holds: bigints, bytes and blobs (WISP 05). */\nexport async function encode(value: unknown): Promise<string> {\n return JSON.stringify(await inlineBlobs(value), (_key, v) => {\n if (typeof v === \"bigint\") return { $ghostly: \"bigint\", value: String(v) } satisfies Tagged;\n if (v instanceof Uint8Array) return { $ghostly: \"bytes\", value: toBase64Url(v) } satisfies Tagged;\n if (v instanceof ArrayBuffer) return { $ghostly: \"bytes\", value: toBase64Url(new Uint8Array(v)) } satisfies Tagged;\n return v;\n });\n}\n/** Never throws on a tag it cannot read: that value stays as it is, and the rest of the backup restores. */\nexport function decode(text: string): unknown {\n return JSON.parse(text, (_key, v) => {\n const escaped = v as Partial<Escaped> | null;\n if (escaped && typeof escaped === \"object\" && escaped.$ghostly === \"object\" && Array.isArray(escaped.entries)) {\n const out: Record<string, unknown> = {};\n for (const entry of escaped.entries) if (Array.isArray(entry) && typeof entry[0] === \"string\") Object.defineProperty(out, entry[0], { value: entry[1], enumerable: true, writable: true, configurable: true });\n return out;\n }\n const tag = v as Partial<Tagged> | null;\n if (!tag || typeof tag !== \"object\" || typeof tag.$ghostly !== \"string\" || typeof tag.value !== \"string\") return v;\n if (tag.$ghostly === \"bigint\") return /^-?\\d+$/.test(tag.value) ? BigInt(tag.value) : v;\n if (!/^[A-Za-z0-9_-]*$/.test(tag.value)) return v;\n if (tag.$ghostly === \"bytes\") return fromBase64Url(tag.value);\n if (tag.$ghostly === \"blob\") return new Blob([fromBase64Url(tag.value) as BlobPart], { type: typeof tag.type === \"string\" ? tag.type : \"\" });\n return v;\n });\n}\n","import { fromBase64Url, toBase64Url } from \"./codec\";\n\n/** The clear part of a bundle (WISP 05): only what decryption needs. */\nexport interface Envelope {\n format: \"ghostly-backup\";\n version: 1;\n kdf: { name: \"PBKDF2-SHA256\"; iterations: number; salt: string };\n cipher: { name: \"AES-256-GCM\"; iv: string };\n compression: \"gzip\" | \"none\";\n ciphertext: string;\n}\nexport const BACKUP_MEDIA_TYPE = \"application/vnd.ghostly.backup+json\";\nconst ITERATIONS = 600_000;\n\nasync function keyFrom(passphrase: string, salt: Uint8Array, iterations: number): Promise<CryptoKey> {\n const material = await crypto.subtle.importKey(\"raw\", new TextEncoder().encode(passphrase), \"PBKDF2\", false, [\"deriveKey\"]);\n return crypto.subtle.deriveKey({ name: \"PBKDF2\", hash: \"SHA-256\", salt: salt as BufferSource, iterations }, material, { name: \"AES-GCM\", length: 256 }, false, [\"encrypt\", \"decrypt\"]);\n}\n/** A profile with years of files is large, but not this large: past it, a bundle is refused, not read. */\nexport const MAX_BACKUP_BYTES = 1024 * 1024 * 1024;\n\nasync function through(bytes: Uint8Array, stream: CompressionStream | DecompressionStream): Promise<Uint8Array> {\n const reader = new Blob([bytes as BlobPart]).stream().pipeThrough(stream).getReader();\n const chunks: Uint8Array[] = [];\n let size = 0;\n for (let next = await reader.read(); !next.done; next = await reader.read()) {\n size += next.value.length;\n if (size > MAX_BACKUP_BYTES) { await reader.cancel(); throw new Error(\"This backup is too large to restore\"); }\n chunks.push(next.value);\n }\n const out = new Uint8Array(size);\n let at = 0;\n for (const chunk of chunks) { out.set(chunk, at); at += chunk.length; }\n return out;\n}\n\n/**\n * The clear header is authenticated with the ciphertext (AES-GCM associated data): changing any of it,\n * the compression included, makes the bundle fail to open instead of being read differently.\n */\nconst header = (e: Pick<Envelope, \"format\" | \"version\" | \"kdf\" | \"cipher\" | \"compression\">) =>\n new TextEncoder().encode([e.format, e.version, e.kdf.name, e.kdf.iterations, e.kdf.salt, e.cipher.name, e.cipher.iv, e.compression].join(\"\\n\"));\nconst canCompress = () => typeof CompressionStream !== \"undefined\";\n\n/** Compresses and encrypts a payload under a passphrase the person chose. */\nexport async function seal(payload: string, passphrase: string): Promise<string> {\n if (passphrase.length < 12) throw new Error(\"Use at least 12 characters for the backup passphrase\");\n const salt = crypto.getRandomValues(new Uint8Array(16)), iv = crypto.getRandomValues(new Uint8Array(12));\n const plain = new TextEncoder().encode(payload);\n const compression = canCompress() ? \"gzip\" : \"none\";\n const body = compression === \"gzip\" ? await through(plain, new CompressionStream(\"gzip\")) : plain;\n const clear = { format: \"ghostly-backup\", version: 1, kdf: { name: \"PBKDF2-SHA256\", iterations: ITERATIONS, salt: toBase64Url(salt) }, cipher: { name: \"AES-256-GCM\", iv: toBase64Url(iv) }, compression } as const;\n const ciphertext = new Uint8Array(await crypto.subtle.encrypt({ name: \"AES-GCM\", iv, additionalData: header(clear) as BufferSource }, await keyFrom(passphrase, salt, ITERATIONS), body as BufferSource));\n const envelope: Envelope = { ...clear, ciphertext: toBase64Url(ciphertext) };\n return JSON.stringify(envelope);\n}\n\n/** Checks, decrypts and decompresses a bundle. Nothing from a bundle is used before this succeeds. */\nexport async function open(text: string, passphrase: string): Promise<string> {\n if (text.length > MAX_BACKUP_BYTES * 1.4) throw new Error(\"This backup is too large to restore\");\n let envelope: Envelope;\n try { envelope = JSON.parse(text) as Envelope; } catch { throw new Error(\"This is not a Ghostly backup\"); }\n if (envelope?.format !== \"ghostly-backup\") throw new Error(\"This is not a Ghostly backup\");\n if (envelope.version !== 1) throw new Error(\"This backup comes from a newer Ghostly; update to restore it\");\n if (envelope.kdf?.name !== \"PBKDF2-SHA256\" || !(envelope.kdf.iterations >= ITERATIONS) || envelope.kdf.iterations > 10_000_000 || envelope.cipher?.name !== \"AES-256-GCM\" || ![\"gzip\", \"none\"].includes(envelope.compression)) throw new Error(\"Unsupported backup encryption\");\n let body: Uint8Array;\n try {\n body = new Uint8Array(await crypto.subtle.decrypt({ name: \"AES-GCM\", iv: fromBase64Url(envelope.cipher.iv) as BufferSource, additionalData: header(envelope) as BufferSource }, await keyFrom(passphrase, fromBase64Url(envelope.kdf.salt), envelope.kdf.iterations), fromBase64Url(envelope.ciphertext) as BufferSource));\n } catch { throw new Error(\"Wrong passphrase, or the backup was changed\"); }\n const plain = envelope.compression === \"gzip\" ? await through(body, new DecompressionStream(\"gzip\")) : body;\n return new TextDecoder().decode(plain);\n}\n"],"mappings":";;AAOA,SAAgB,cAAc,MAA0B;CACtD,IAAI,CAAC,mBAAmB,KAAK,IAAI,GAAG,MAAM,IAAI,MAAM,mBAAmB;CACvE,MAAM,SAAS,KAAK,KAAK,QAAQ,MAAM,GAAG,CAAC,CAAC,QAAQ,MAAM,GAAG,IAAI,IAAI,QAAQ,IAAK,KAAK,SAAS,KAAM,CAAC,CAAC;CACxG,MAAM,QAAQ,IAAI,WAAW,OAAO,MAAM;CAC1C,KAAK,IAAI,IAAI,GAAG,IAAI,OAAO,QAAQ,KAAK,MAAM,KAAK,OAAO,WAAW,CAAC;CACtE,OAAO;AACT;;;ACFA,IAAa,oBAAoB;AACjC,IAAM,aAAa;AAEnB,eAAe,QAAQ,YAAoB,MAAkB,YAAwC;CACnG,MAAM,WAAW,MAAM,OAAO,OAAO,UAAU,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,UAAU,GAAG,UAAU,OAAO,CAAC,WAAW,CAAC;CAC1H,OAAO,OAAO,OAAO,UAAU;EAAE,MAAM;EAAU,MAAM;EAAiB;EAAsB;CAAW,GAAG,UAAU;EAAE,MAAM;EAAW,QAAQ;CAAI,GAAG,OAAO,CAAC,WAAW,SAAS,CAAC;AACvL;;AAEA,IAAa,mBAAmB;AAEhC,eAAe,QAAQ,OAAmB,QAAsE;CAC9G,MAAM,SAAS,IAAI,KAAK,CAAC,KAAiB,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,YAAY,MAAM,CAAC,CAAC,UAAU;CACpF,MAAM,SAAuB,CAAC;CAC9B,IAAI,OAAO;CACX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AAM;GAAW,IAAI,cAAc,SAAS,OAAO,EAAE;GAAmB,gBAAgB,OAAO,QAAQ;EAAkB,GAAG,MAAM,QAAQ,YAAY,cAAc,SAAS,IAAI,IAAI,GAAG,SAAS,IAAI,UAAU,GAAG,cAAc,SAAS,UAAU,CAAiB,CAAC;CAC3T,QAAQ;EAAE,MAAM,IAAI,MAAM,6CAA6C;CAAG;CAC1E,MAAM,QAAQ,SAAS,gBAAgB,SAAS,MAAM,QAAQ,MAAM,IAAI,oBAAoB,MAAM,CAAC,IAAI;CACvG,OAAO,IAAI,YAAY,CAAC,CAAC,OAAO,KAAK;AACvC"}
|
|
@@ -41,6 +41,14 @@ function fileSpace() {
|
|
|
41
41
|
* found here"), which failed a voice note after all its bytes had arrived.
|
|
42
42
|
*/
|
|
43
43
|
async function blobDigest(blob, onProgress) {
|
|
44
|
+
const subtle = globalThis.crypto?.subtle;
|
|
45
|
+
if (subtle && blob.size <= 16777216) {
|
|
46
|
+
const bytes = await blob.arrayBuffer();
|
|
47
|
+
if (bytes.byteLength !== blob.size) throw new Error("The file is shorter than it says");
|
|
48
|
+
const digest = new Uint8Array(await subtle.digest("SHA-256", bytes));
|
|
49
|
+
onProgress?.(blob.size);
|
|
50
|
+
return digestText(digest);
|
|
51
|
+
}
|
|
44
52
|
const hash = sha256.create();
|
|
45
53
|
for (let done = 0; done < blob.size;) {
|
|
46
54
|
const part = new Uint8Array(await blob.slice(done, Math.min(blob.size, done + FILE_BYTES_STEP)).arrayBuffer());
|
|
@@ -51,7 +59,7 @@ async function blobDigest(blob, onProgress) {
|
|
|
51
59
|
}
|
|
52
60
|
return digestText(hash.digest());
|
|
53
61
|
}
|
|
54
|
-
var makers = /* @__PURE__ */ new Map([["opfs", () => import("./fileBytesOpfs-
|
|
62
|
+
var makers = /* @__PURE__ */ new Map([["opfs", () => import("./fileBytesOpfs-B8fJwkwM.js").then((m) => m.OpfsFileBytes.open())], ["idb", () => import("./fileBytesIdb-CsSQcSxD.js").then((m) => new m.IdbFileBytes())]]);
|
|
55
63
|
var made = /* @__PURE__ */ new Map();
|
|
56
64
|
var preferred = ["opfs", "idb"];
|
|
57
65
|
/** How a backend is made. The platform registers its own (Desktop: `native`) before anything uses it. */
|
|
@@ -95,4 +103,4 @@ function resetFileBytes(order = ["opfs", "idb"]) {
|
|
|
95
103
|
//#endregion
|
|
96
104
|
export { dropFileSpace as a, fileSpace as c, resetFileBytes as d, FILE_BYTES_STEP as f, checkFileId as i, registerFileBytes as l, SMALL_FILE_BYTES as n, fileBytes as o, digestText as p, blobDigest as r, fileBytesOf as s, NO_ROOM_TO_PLAY as t, removeFileBytes as u };
|
|
97
105
|
|
|
98
|
-
//# sourceMappingURL=fileBytes-
|
|
106
|
+
//# sourceMappingURL=fileBytes-BD0v3rRG.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileBytes-BMEBas7S.js","names":[],"sources":["../../../browser/src/shared/fileBytesCommon.ts","../../../browser/src/shared/fileBytes.ts"],"sourcesContent":["/** What `fileBytes.ts` and its worker share: the worker is built alone, so this imports nothing. */\n\n/** Reads and copies move this much at a time. */\nexport const FILE_BYTES_STEP = 1024 * 1024;\n\nconst BASE64URL = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n/** base64url without padding (the worker has no @ghostly/core). */\nexport function digestText(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i += 3) {\n const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);\n out += BASE64URL[(n >> 18) & 63] + BASE64URL[(n >> 12) & 63];\n if (i + 1 < bytes.length) out += BASE64URL[(n >> 6) & 63];\n if (i + 2 < bytes.length) out += BASE64URL[n & 63];\n }\n return out;\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { databaseName } from \"./idb\";\nimport { digestText, FILE_BYTES_STEP } from \"./fileBytesCommon\";\n\n/**\n * Where the bytes of a file live when they may be more than memory holds: a file sent or received in a chat.\n * Every implementation keeps one file per id under the profile's space (`databaseName()`), is written in\n * order (`append` at the stored size, `truncate` to go back), and is read in ranges, so no caller ever needs\n * the whole file at once.\n *\n * - `opfs`: the origin-private file system, written by a worker with sync access handles (web, extension).\n * - `native`: a real file in the app's data folder, through Rust (Desktop).\n * - `idb`: 1 MiB records in IndexedDB, where neither of those exists (and in tests).\n */\nexport interface FileBytes {\n readonly kind: FileBytesKind;\n /** Copies a picked file in, hashing it on the way. Resolves to its SHA-256, base64url. */\n stage(id: string, source: Blob, onProgress?: (copied: number) => void): Promise<string>;\n /** Writes at `offset`, which must be the stored size. Resolves once written; `flush` makes it durable. */\n append(id: string, offset: number, bytes: Uint8Array): Promise<void>;\n /** What was appended so far survives a crash. */\n flush(id: string): Promise<void>;\n /** Writing is over for now: flushed, and the file let go so it can be read elsewhere. */\n close(id: string): Promise<void>;\n /** Bytes stored, or null when there is no such file. */\n size(id: string): Promise<number | null>;\n /** Cuts the file to `size` bytes (a transfer going back to its last durable point). */\n truncate(id: string, size: number): Promise<void>;\n /** At most `length` bytes from `offset`; fewer only at the end of the file. */\n read(id: string, offset: number, length: number): Promise<Uint8Array>;\n /** SHA-256 of what is stored, base64url: read back from storage, so it checks what was written. */\n digest(id: string): Promise<string>;\n /**\n * The file as a Blob to show or save, backed by storage rather than memory, or null where this platform\n * cannot hand one out (Desktop, above `NATIVE_BLOB_MAX`: saved with `save` instead).\n */\n blob(id: string, type: string): Promise<Blob | null>;\n remove(id: string): Promise<void>;\n /** Removes every file whose id starts with `prefix` (\"\" for all of this space). */\n removeWhere(prefix: string): Promise<void>;\n /** Bytes this device can still take for files, or null when the platform does not say. */\n room(): Promise<number | null>;\n /** Saves a copy where the person chooses, where the platform has a dialog for it. False when they cancelled. */\n save?(id: string, name: string): Promise<boolean>;\n /**\n * A URL a `<video>` or `<audio>` plays the stored file from, served in ranges by the platform (Desktop, for a file\n * too large for `blob`), or null when there is no such file. The URL works until `release`. Rejects with\n * `NO_ROOM_TO_PLAY` when the disk has no room for the copy the player makes of it (Linux's WebKitGTK): save it instead.\n */\n stream?(id: string, type: string): Promise<FileStream | null>;\n /**\n * What this space's files take on disk, where they are real files (Desktop): the files, and the copies staged for a\n * save (a backup, a file on its way through the save dialog) apart. Absent elsewhere: there the browser's own\n * estimate counts them.\n */\n usage?(): Promise<FileUsage>;\n /** Removes another profile's folder (a deleted profile). IndexedDB pieces go with the profile's database. */\n dropSpace?(space: string): Promise<void>;\n /**\n * The same storage for another profile's space: a backup of a profile that is not the active one reads its files\n * through it, and a restore writes a new profile's files through it before that profile exists. Absent where files\n * are pieces in the profile's own database (`idb`): those are read and written with that database.\n */\n forSpace?(space: string): FileBytes;\n}\n\nexport type FileBytesKind = \"opfs\" | \"native\" | \"idb\";\n\n/** Bytes a space's files take (`FileBytes.usage`): the files and how many, and the copies staged for a save. */\nexport interface FileUsage { files: number; count: number; staged: number }\n\n/** Why `FileBytes.stream` refused a file this device holds: no room on the disk for the player's copy of it. */\nexport const NO_ROOM_TO_PLAY = \"no_room_to_play\";\n\n/** A stored file being served to a media element: its URL, and how to stop serving it. */\nexport interface FileStream {\n url: string;\n release(): void;\n}\n\n/** Files sent from memory-sized sources stay whole in IndexedDB; anything larger goes through a `FileBytes`. */\nexport const SMALL_FILE_BYTES = 16 * 1024 * 1024;\n\nexport { FILE_BYTES_STEP, digestText } from \"./fileBytesCommon\";\n\nconst ID = /^[A-Za-z0-9_-]{1,200}$/;\nconst SPACE = /^[A-Za-z0-9_.-]{1,100}$/;\n\n/** A file id every backend accepts as a file name as it is: never a path. */\nexport function checkFileId(id: string): string {\n if (!ID.test(id)) throw new Error(\"Invalid file id\");\n return id;\n}\n\n/** This profile's folder name. */\nexport function fileSpace(): string {\n const space = databaseName();\n if (!SPACE.test(space)) throw new Error(\"Invalid profile space\");\n return space;\n}\n\n/**\n * SHA-256 of a Blob, read a step at a time: memory stays at one step. Read with `slice().arrayBuffer()`, not\n * `stream()`: in WebKit a Blob kept in IndexedDB that reads fine in slices failed as a stream (\"The object can not be\n * found here\"), which failed a voice note after all its bytes had arrived.\n */\nexport async function blobDigest(blob: Blob, onProgress?: (done: number) => void): Promise<string> {\n const hash = sha256.create();\n for (let done = 0; done < blob.size;) {\n const part = new Uint8Array(await blob.slice(done, Math.min(blob.size, done + FILE_BYTES_STEP)).arrayBuffer());\n if (!part.length) throw new Error(\"The file is shorter than it says\");\n hash.update(part);\n done += part.length;\n onProgress?.(done);\n }\n return digestText(hash.digest());\n}\n\ntype Maker = () => Promise<FileBytes | null>;\nconst makers = new Map<FileBytesKind, Maker>([\n [\"opfs\", () => import(\"./fileBytesOpfs\").then((m) => m.OpfsFileBytes.open())],\n [\"idb\", () => import(\"./fileBytesIdb\").then((m) => new m.IdbFileBytes())],\n]);\nconst made = new Map<FileBytesKind, Promise<FileBytes | null>>();\nlet preferred: FileBytesKind[] = [\"opfs\", \"idb\"];\n\n/** How a backend is made. The platform registers its own (Desktop: `native`) before anything uses it. */\nexport function registerFileBytes(kind: FileBytesKind, make: Maker, prefer = false): void {\n makers.set(kind, make);\n made.delete(kind);\n if (prefer) preferred = [kind, ...preferred.filter((k) => k !== kind)];\n}\n\n/** The backend of this kind, or null where this platform has none. */\nexport function fileBytesOf(kind: FileBytesKind): Promise<FileBytes | null> {\n let backend = made.get(kind);\n if (!backend) {\n const make = makers.get(kind);\n backend = make ? make().catch(() => null) : Promise.resolve(null);\n made.set(kind, backend);\n }\n return backend;\n}\n\n/** Where new files go: the first backend this platform has. */\nexport async function fileBytes(): Promise<FileBytes> {\n for (const kind of preferred) {\n const backend = await fileBytesOf(kind);\n if (backend) return backend;\n }\n throw new Error(\"This device has no storage for files\");\n}\n\n/** \"Clear all data\" and a deleted chat: the bytes of its files go with it, wherever they are. */\nexport async function removeFileBytes(prefix = \"\"): Promise<void> {\n await Promise.all([...makers.keys()].map(async (kind) => (await fileBytesOf(kind))?.removeWhere(prefix)));\n}\n\n/** A deleted profile's files, wherever they are. */\nexport async function dropFileSpace(space: string): Promise<void> {\n if (!SPACE.test(space)) throw new Error(\"Invalid profile space\");\n await Promise.all([...makers.keys()].map(async (kind) => (await fileBytesOf(kind))?.dropSpace?.(space)));\n}\n\n/** Tests: forget what was made and which backend comes first. */\nexport function resetFileBytes(order: FileBytesKind[] = [\"opfs\", \"idb\"]): void {\n made.clear();\n preferred = order;\n}\n"],"mappings":";;;;;AAGA,IAAa,kBAAkB;AAE/B,IAAM,YAAY;;AAGlB,SAAgB,WAAW,OAA2B;CACpD,IAAI,MAAM;CACV,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxC,MAAM,IAAK,MAAM,MAAM,MAAQ,MAAM,IAAI,MAAM,MAAM,KAAM,MAAM,IAAI,MAAM;EAC3E,OAAO,UAAW,KAAK,KAAM,MAAM,UAAW,KAAK,KAAM;EACzD,IAAI,IAAI,IAAI,MAAM,QAAQ,OAAO,UAAW,KAAK,IAAK;EACtD,IAAI,IAAI,IAAI,MAAM,QAAQ,OAAO,UAAU,IAAI;CACjD;CACA,OAAO;AACT;;;;ACuDA,IAAa,kBAAkB;;AAS/B,IAAa,mBAAmB;AAIhC,IAAM,KAAK;AACX,IAAM,QAAQ;;AAGd,SAAgB,YAAY,IAAoB;CAC9C,IAAI,CAAC,GAAG,KAAK,EAAE,GAAG,MAAM,IAAI,MAAM,iBAAiB;CACnD,OAAO;AACT;;AAGA,SAAgB,YAAoB;CAClC,MAAM,QAAQ,aAAa;CAC3B,IAAI,CAAC,MAAM,KAAK,KAAK,GAAG,MAAM,IAAI,MAAM,uBAAuB;CAC/D,OAAO;AACT;;;;;;AAOA,eAAsB,WAAW,MAAY,YAAsD;CACjG,MAAM,OAAO,OAAO,OAAO;CAC3B,KAAK,IAAI,OAAO,GAAG,OAAO,KAAK,OAAO;EACpC,MAAM,OAAO,IAAI,WAAW,MAAM,KAAK,MAAM,MAAM,KAAK,IAAI,KAAK,MAAM,OAAO,eAAe,CAAC,CAAC,C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C,CAAC;AAC1G;;AAGA,eAAsB,cAAc,OAA8B;CAChE,IAAI,CAAC,MAAM,KAAK,KAAK,GAAG,MAAM,IAAI,MAAM,uBAAuB;CAC/D,MAAM,QAAQ,IAAI,CAAC,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,OAAO,UAAU,MAAM,YAAY,IAAI,EAAA,EAAI,YAAY,KAAK,CAAC,CAAC;AACzG;;AAGA,SAAgB,eAAe,QAAyB,CAAC,QAAQ,KAAK,GAAS;CAC7E,KAAK,MAAM;CACX,YAAY;AACd"}
|
|
1
|
+
{"version":3,"file":"fileBytes-BD0v3rRG.js","names":[],"sources":["../../../browser/src/shared/fileBytesCommon.ts","../../../browser/src/shared/fileBytes.ts"],"sourcesContent":["/** What `fileBytes.ts` and its worker share: the worker is built alone, so this imports nothing. */\n\n/** Reads and copies move this much at a time. */\nexport const FILE_BYTES_STEP = 1024 * 1024;\n\nconst BASE64URL = \"ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_\";\n\n/** base64url without padding (the worker has no @ghostly/core). */\nexport function digestText(bytes: Uint8Array): string {\n let out = \"\";\n for (let i = 0; i < bytes.length; i += 3) {\n const n = (bytes[i] << 16) | ((bytes[i + 1] ?? 0) << 8) | (bytes[i + 2] ?? 0);\n out += BASE64URL[(n >> 18) & 63] + BASE64URL[(n >> 12) & 63];\n if (i + 1 < bytes.length) out += BASE64URL[(n >> 6) & 63];\n if (i + 2 < bytes.length) out += BASE64URL[n & 63];\n }\n return out;\n}\n","import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { databaseName } from \"./idb\";\nimport { digestText, FILE_BYTES_STEP } from \"./fileBytesCommon\";\n\n/**\n * Where the bytes of a file live when they may be more than memory holds: a file sent or received in a chat.\n * Every implementation keeps one file per id under the profile's space (`databaseName()`), is written in\n * order (`append` at the stored size, `truncate` to go back), and is read in ranges, so no caller ever needs\n * the whole file at once.\n *\n * - `opfs`: the origin-private file system, written by a worker with sync access handles (web, extension).\n * - `native`: a real file in the app's data folder, through Rust (Desktop).\n * - `idb`: 1 MiB records in IndexedDB, where neither of those exists (and in tests).\n */\nexport interface FileBytes {\n readonly kind: FileBytesKind;\n /** Copies a picked file in, hashing it on the way. Resolves to its SHA-256, base64url. */\n stage(id: string, source: Blob, onProgress?: (copied: number) => void): Promise<string>;\n /** Writes at `offset`, which must be the stored size. Resolves once written; `flush` makes it durable. */\n append(id: string, offset: number, bytes: Uint8Array): Promise<void>;\n /** What was appended so far survives a crash. */\n flush(id: string): Promise<void>;\n /** Writing is over for now: flushed, and the file let go so it can be read elsewhere. */\n close(id: string): Promise<void>;\n /** Bytes stored, or null when there is no such file. */\n size(id: string): Promise<number | null>;\n /** Cuts the file to `size` bytes (a transfer going back to its last durable point). */\n truncate(id: string, size: number): Promise<void>;\n /** At most `length` bytes from `offset`; fewer only at the end of the file. */\n read(id: string, offset: number, length: number): Promise<Uint8Array>;\n /** SHA-256 of what is stored, base64url: read back from storage, so it checks what was written. */\n digest(id: string): Promise<string>;\n /**\n * The file as a Blob to show or save, backed by storage rather than memory, or null where this platform\n * cannot hand one out (Desktop, above `NATIVE_BLOB_MAX`: saved with `save` instead).\n */\n blob(id: string, type: string): Promise<Blob | null>;\n remove(id: string): Promise<void>;\n /** Removes every file whose id starts with `prefix` (\"\" for all of this space). */\n removeWhere(prefix: string): Promise<void>;\n /** Bytes this device can still take for files, or null when the platform does not say. */\n room(): Promise<number | null>;\n /** Saves a copy where the person chooses, where the platform has a dialog for it. False when they cancelled. */\n save?(id: string, name: string): Promise<boolean>;\n /**\n * A URL a `<video>` or `<audio>` plays the stored file from, served in ranges by the platform (Desktop, for a file\n * too large for `blob`), or null when there is no such file. The URL works until `release`. Rejects with\n * `NO_ROOM_TO_PLAY` when the disk has no room for the copy the player makes of it (Linux's WebKitGTK): save it instead.\n */\n stream?(id: string, type: string): Promise<FileStream | null>;\n /**\n * What this space's files take on disk, where they are real files (Desktop): the files, and the copies staged for a\n * save (a backup, a file on its way through the save dialog) apart. Absent elsewhere: there the browser's own\n * estimate counts them.\n */\n usage?(): Promise<FileUsage>;\n /** Removes another profile's folder (a deleted profile). IndexedDB pieces go with the profile's database. */\n dropSpace?(space: string): Promise<void>;\n /**\n * The same storage for another profile's space: a backup of a profile that is not the active one reads its files\n * through it, and a restore writes a new profile's files through it before that profile exists. Absent where files\n * are pieces in the profile's own database (`idb`): those are read and written with that database.\n */\n forSpace?(space: string): FileBytes;\n}\n\nexport type FileBytesKind = \"opfs\" | \"native\" | \"idb\";\n\n/** Bytes a space's files take (`FileBytes.usage`): the files and how many, and the copies staged for a save. */\nexport interface FileUsage { files: number; count: number; staged: number }\n\n/** Why `FileBytes.stream` refused a file this device holds: no room on the disk for the player's copy of it. */\nexport const NO_ROOM_TO_PLAY = \"no_room_to_play\";\n\n/** A stored file being served to a media element: its URL, and how to stop serving it. */\nexport interface FileStream {\n url: string;\n release(): void;\n}\n\n/** Files sent from memory-sized sources stay whole in IndexedDB; anything larger goes through a `FileBytes`. */\nexport const SMALL_FILE_BYTES = 16 * 1024 * 1024;\n\nexport { FILE_BYTES_STEP, digestText } from \"./fileBytesCommon\";\n\nconst ID = /^[A-Za-z0-9_-]{1,200}$/;\nconst SPACE = /^[A-Za-z0-9_.-]{1,100}$/;\n\n/** A file id every backend accepts as a file name as it is: never a path. */\nexport function checkFileId(id: string): string {\n if (!ID.test(id)) throw new Error(\"Invalid file id\");\n return id;\n}\n\n/** This profile's folder name. */\nexport function fileSpace(): string {\n const space = databaseName();\n if (!SPACE.test(space)) throw new Error(\"Invalid profile space\");\n return space;\n}\n\n/**\n * SHA-256 of a Blob, read a step at a time: memory stays at one step. Read with `slice().arrayBuffer()`, not\n * `stream()`: in WebKit a Blob kept in IndexedDB that reads fine in slices failed as a stream (\"The object can not be\n * found here\"), which failed a voice note after all its bytes had arrived.\n */\nexport async function blobDigest(blob: Blob, onProgress?: (done: number) => void): Promise<string> {\n // A Blob this side holds in memory anyway (at most `SMALL_FILE_BYTES`, a send's small path): the platform's digest, off\n // the page's script. noble's, a step at a time on the main thread, was 16 long tasks of 65-90 ms for 16 MiB on a\n // phone-class CPU, ~13-16x slower than crypto.subtle (agents#1765). Read whole with `arrayBuffer()` too, not `stream()`.\n const subtle = globalThis.crypto?.subtle;\n if (subtle && blob.size <= SMALL_FILE_BYTES) {\n const bytes = await blob.arrayBuffer();\n if (bytes.byteLength !== blob.size) throw new Error(\"The file is shorter than it says\");\n const digest = new Uint8Array(await subtle.digest(\"SHA-256\", bytes));\n onProgress?.(blob.size);\n return digestText(digest);\n }\n const hash = sha256.create();\n for (let done = 0; done < blob.size;) {\n const part = new Uint8Array(await blob.slice(done, Math.min(blob.size, done + FILE_BYTES_STEP)).arrayBuffer());\n if (!part.length) throw new Error(\"The file is shorter than it says\");\n hash.update(part);\n done += part.length;\n onProgress?.(done);\n }\n return digestText(hash.digest());\n}\n\ntype Maker = () => Promise<FileBytes | null>;\nconst makers = new Map<FileBytesKind, Maker>([\n [\"opfs\", () => import(\"./fileBytesOpfs\").then((m) => m.OpfsFileBytes.open())],\n [\"idb\", () => import(\"./fileBytesIdb\").then((m) => new m.IdbFileBytes())],\n]);\nconst made = new Map<FileBytesKind, Promise<FileBytes | null>>();\nlet preferred: FileBytesKind[] = [\"opfs\", \"idb\"];\n\n/** How a backend is made. The platform registers its own (Desktop: `native`) before anything uses it. */\nexport function registerFileBytes(kind: FileBytesKind, make: Maker, prefer = false): void {\n makers.set(kind, make);\n made.delete(kind);\n if (prefer) preferred = [kind, ...preferred.filter((k) => k !== kind)];\n}\n\n/** The backend of this kind, or null where this platform has none. */\nexport function fileBytesOf(kind: FileBytesKind): Promise<FileBytes | null> {\n let backend = made.get(kind);\n if (!backend) {\n const make = makers.get(kind);\n backend = make ? make().catch(() => null) : Promise.resolve(null);\n made.set(kind, backend);\n }\n return backend;\n}\n\n/** Where new files go: the first backend this platform has. */\nexport async function fileBytes(): Promise<FileBytes> {\n for (const kind of preferred) {\n const backend = await fileBytesOf(kind);\n if (backend) return backend;\n }\n throw new Error(\"This device has no storage for files\");\n}\n\n/** \"Clear all data\" and a deleted chat: the bytes of its files go with it, wherever they are. */\nexport async function removeFileBytes(prefix = \"\"): Promise<void> {\n await Promise.all([...makers.keys()].map(async (kind) => (await fileBytesOf(kind))?.removeWhere(prefix)));\n}\n\n/** A deleted profile's files, wherever they are. */\nexport async function dropFileSpace(space: string): Promise<void> {\n if (!SPACE.test(space)) throw new Error(\"Invalid profile space\");\n await Promise.all([...makers.keys()].map(async (kind) => (await fileBytesOf(kind))?.dropSpace?.(space)));\n}\n\n/** Tests: forget what was made and which backend comes first. */\nexport function resetFileBytes(order: FileBytesKind[] = [\"opfs\", \"idb\"]): void {\n made.clear();\n preferred = order;\n}\n"],"mappings":";;;;;AAGA,IAAa,kBAAkB;AAE/B,IAAM,YAAY;;AAGlB,SAAgB,WAAW,OAA2B;CACpD,IAAI,MAAM;CACV,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK,GAAG;EACxC,MAAM,IAAK,MAAM,MAAM,MAAQ,MAAM,IAAI,MAAM,MAAM,KAAM,MAAM,IAAI,MAAM;EAC3E,OAAO,UAAW,KAAK,KAAM,MAAM,UAAW,KAAK,KAAM;EACzD,IAAI,IAAI,IAAI,MAAM,QAAQ,OAAO,UAAW,KAAK,IAAK;EACtD,IAAI,IAAI,IAAI,MAAM,QAAQ,OAAO,UAAU,IAAI;CACjD;CACA,OAAO;AACT;;;;ACuDA,IAAa,kBAAkB;;AAS/B,IAAa,mBAAmB;AAIhC,IAAM,KAAK;AACX,IAAM,QAAQ;;AAGd,SAAgB,YAAY,IAAoB;CAC9C,IAAI,CAAC,GAAG,KAAK,EAAE,GAAG,MAAM,IAAI,MAAM,iBAAiB;CACnD,OAAO;AACT;;AAGA,SAAgB,YAAoB;CAClC,MAAM,QAAQ,aAAa;CAC3B,IAAI,CAAC,MAAM,KAAK,KAAK,GAAG,MAAM,IAAI,MAAM,uBAAuB;CAC/D,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AI,IAAI;CAC3B,IAAI,CAAC,SAAS;EACZ,MAAM,OAAO,OAAO,IAAI,IAAI;EAC5B,UAAU,OAAO,KAAK,CAAC,CAAC,YAAY,IAAI,IAAI,QAAQ,QAAQ,IAAI;EAChE,KAAK,IAAI,MAAM,OAAO;CACxB;CACA,OAAO;AACT;;AAGA,eAAsB,YAAgC;CACpD,KAAK,MAAM,QAAQ,WAAW;EAC5B,MAAM,UAAU,MAAM,YAAY,IAAI;EACtC,IAAI,SAAS,OAAO;CACtB;CACA,MAAM,IAAI,MAAM,sCAAsC;AACxD;;AAGA,eAAsB,gBAAgB,SAAS,IAAmB;CAChE,MAAM,QAAQ,IAAI,CAAC,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,OAAO,UAAU,MAAM,YAAY,IAAI,EAAA,EAAI,YAAY,MAAM,CAAC,CAAC;AAC1G;;AAGA,eAAsB,cAAc,OAA8B;CAChE,IAAI,CAAC,MAAM,KAAK,KAAK,GAAG,MAAM,IAAI,MAAM,uBAAuB;CAC/D,MAAM,QAAQ,IAAI,CAAC,GAAG,OAAO,KAAK,CAAC,CAAC,CAAC,IAAI,OAAO,UAAU,MAAM,YAAY,IAAI,EAAA,EAAI,YAAY,KAAK,CAAC,CAAC;AACzG;;AAGA,SAAgB,eAAe,QAAyB,CAAC,QAAQ,KAAK,GAAS;CAC7E,KAAK,MAAM;CACX,YAAY;AACd"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import { a as dropFileSpace, c as fileSpace, d as resetFileBytes, f as FILE_BYTES_STEP, i as checkFileId, l as registerFileBytes, n as SMALL_FILE_BYTES, o as fileBytes, p as digestText, r as blobDigest, s as fileBytesOf, t as NO_ROOM_TO_PLAY, u as removeFileBytes } from "./fileBytes-
|
|
1
|
+
import { a as dropFileSpace, c as fileSpace, d as resetFileBytes, f as FILE_BYTES_STEP, i as checkFileId, l as registerFileBytes, n as SMALL_FILE_BYTES, o as fileBytes, p as digestText, r as blobDigest, s as fileBytesOf, t as NO_ROOM_TO_PLAY, u as removeFileBytes } from "./fileBytes-BD0v3rRG.js";
|
|
2
2
|
export { FILE_BYTES_STEP, NO_ROOM_TO_PLAY, SMALL_FILE_BYTES, blobDigest, checkFileId, digestText, dropFileSpace, fileBytes, fileBytesOf, fileSpace, registerFileBytes, removeFileBytes, resetFileBytes };
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { c as fileSpace, f as FILE_BYTES_STEP, i as checkFileId, p as digestText } from "./fileBytes-
|
|
1
|
+
import { c as fileSpace, f as FILE_BYTES_STEP, i as checkFileId, p as digestText } from "./fileBytes-BD0v3rRG.js";
|
|
2
2
|
import { mkdir, open, readdir, rm, stat, statfs } from "node:fs/promises";
|
|
3
3
|
import { join } from "node:path";
|
|
4
4
|
import { createHash } from "node:crypto";
|
|
@@ -154,4 +154,4 @@ var NodeFileBytes = class {
|
|
|
154
154
|
//#endregion
|
|
155
155
|
export { NodeFileBytes };
|
|
156
156
|
|
|
157
|
-
//# sourceMappingURL=fileBytes-
|
|
157
|
+
//# sourceMappingURL=fileBytes-_fd-2JRY.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileBytes-
|
|
1
|
+
{"version":3,"file":"fileBytes-_fd-2JRY.js","names":[],"sources":["../../src/runtime/fileBytes.ts"],"sourcesContent":["import { createHash } from \"node:crypto\";\nimport { mkdir, open, readdir, rm, stat, statfs, type FileHandle } from \"node:fs/promises\";\nimport { join } from \"node:path\";\nimport { FILE_BYTES_STEP, checkFileId, digestText, fileSpace, type FileBytes } from \"@ghostly/browser/shared/fileBytes\";\n\n/**\n * Files as real files in the profile's folder (`files/<space>/<id>`, 0600 in 0700 folders), the Node twin of the\n * Desktop's `native` backend (`shared/fileBytesNative.ts`, which goes through Rust). Registered as `native` and\n * preferred, so every file of any size is a file on disk, read and written a step at a time.\n */\nexport class NodeFileBytes implements FileBytes {\n readonly kind = \"native\" as const;\n private readonly writers = new Map<string, Promise<FileHandle>>();\n\n constructor(private readonly root: string) {}\n\n private folder(space = fileSpace()): string { return join(this.root, space); }\n private path(id: string): string { return join(this.folder(), checkFileId(id)); }\n\n private writer(id: string): Promise<FileHandle> {\n const path = this.path(id);\n let handle = this.writers.get(path);\n if (!handle) {\n handle = mkdir(this.folder(), { recursive: true, mode: 0o700 }).then(() => open(path, \"a\", 0o600));\n this.writers.set(path, handle);\n handle.catch(() => this.writers.delete(path));\n }\n return handle;\n }\n\n /** Copies `source` in and gives its digest, hashed as it is copied (as the web's stores do): the file is read once, not twice. */\n async stage(id: string, source: Blob, onProgress?: (copied: number) => void): Promise<string> {\n await this.remove(id);\n try {\n const hash = createHash(\"sha256\");\n for (let offset = 0; offset < source.size; offset += FILE_BYTES_STEP) {\n const bytes = new Uint8Array(await source.slice(offset, offset + FILE_BYTES_STEP).arrayBuffer());\n hash.update(bytes);\n await this.append(id, offset, bytes);\n onProgress?.(offset + bytes.length);\n }\n if (source.size === 0) await this.append(id, 0, new Uint8Array());\n await this.close(id);\n return digestText(new Uint8Array(hash.digest()));\n } catch (error) {\n await this.remove(id).catch(() => {});\n throw error;\n }\n }\n\n async append(id: string, offset: number, bytes: Uint8Array): Promise<void> {\n const size = (await this.size(id)) ?? 0;\n if (offset !== size) throw new Error(`Append at ${offset}, but the file holds ${size} bytes`);\n const handle = await this.writer(id);\n if (bytes.length) await handle.write(bytes);\n }\n\n async flush(id: string): Promise<void> {\n const handle = this.writers.get(this.path(id));\n if (handle) await (await handle).sync();\n }\n\n async close(id: string): Promise<void> {\n const path = this.path(id);\n const handle = this.writers.get(path);\n if (!handle) return;\n this.writers.delete(path);\n const file = await handle;\n await file.sync();\n await file.close();\n }\n\n async size(id: string): Promise<number | null> {\n const path = this.path(id);\n try { return (await stat(path)).size; } catch { return null; }\n }\n\n async truncate(id: string, size: number): Promise<void> {\n await this.close(id);\n const handle = await open(this.path(id), \"r+\");\n try { await handle.truncate(size); await handle.sync(); } finally { await handle.close(); }\n }\n\n async read(id: string, offset: number, length: number): Promise<Uint8Array> {\n const handle = await open(this.path(id), \"r\");\n try {\n const buffer = Buffer.alloc(Math.min(length, 16 * FILE_BYTES_STEP));\n const { bytesRead } = await handle.read(buffer, 0, buffer.length, offset);\n return new Uint8Array(buffer.subarray(0, bytesRead));\n } finally { await handle.close(); }\n }\n\n async digest(id: string): Promise<string> {\n const hash = createHash(\"sha256\");\n const handle = await open(this.path(id), \"r\");\n try {\n for await (const chunk of handle.createReadStream({ highWaterMark: FILE_BYTES_STEP })) hash.update(chunk as Buffer);\n } finally { await handle.close().catch(() => {}); }\n return digestText(new Uint8Array(hash.digest()));\n }\n\n /** The file read into memory, to show; a large one only ever goes to disk (`ghostly file save`). */\n async blob(id: string, type: string): Promise<Blob | null> {\n const size = await this.size(id);\n if (size === null || size > 64 * 1024 * 1024) return null;\n const parts: Uint8Array[] = [];\n for (let offset = 0; offset < size; offset += FILE_BYTES_STEP) parts.push(await this.read(id, offset, FILE_BYTES_STEP));\n return new Blob(parts as BlobPart[], { type });\n }\n\n async remove(id: string): Promise<void> {\n await this.close(id).catch(() => {});\n await rm(this.path(id), { force: true });\n }\n\n async removeWhere(prefix: string): Promise<void> {\n if (prefix && !/^[A-Za-z0-9_-]{1,200}$/.test(prefix)) throw new Error(\"Invalid file id\");\n let names: string[];\n try { names = await readdir(this.folder()); } catch { return; }\n await Promise.all(names.filter((name) => name.startsWith(prefix)).map((name) => this.remove(name)));\n }\n\n async room(): Promise<number | null> {\n try {\n await mkdir(this.root, { recursive: true, mode: 0o700 });\n const fs = await statfs(this.root);\n return fs.bavail * fs.bsize;\n } catch { return null; }\n }\n\n async dropSpace(space: string): Promise<void> {\n await rm(this.folder(space), { recursive: true, force: true });\n }\n}\n"],"mappings":";;;;;;;;;;AAUA,IAAa,gBAAb,MAAgD;CAIjB;CAH7B,OAAgB;CAChB,0BAA2B,IAAI,IAAiC;CAEhE,YAAY,MAA+B;EAAd,KAAA,OAAA;CAAe;CAE5C,OAAe,QAAQ,UAAU,GAAW;EAAE,O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AM,KAAK,MAAM;IAAE,WAAW;IAAM,MAAM;GAAM,CAAC;GACvD,MAAM,KAAK,MAAM,OAAO,KAAK,IAAI;GACjC,OAAO,GAAG,SAAS,GAAG;EACxB,QAAQ;GAAE,OAAO;EAAM;CACzB;CAEA,MAAM,UAAU,OAA8B;EAC5C,MAAM,GAAG,KAAK,OAAO,KAAK,GAAG;GAAE,WAAW;GAAM,OAAO;EAAK,CAAC;CAC/D;AACF"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { f as openDb, g as wrap, i as STORES, o as committed } from "./idb-BlH8-O3R.js";
|
|
2
|
-
import { f as FILE_BYTES_STEP, i as checkFileId, p as digestText } from "./fileBytes-
|
|
2
|
+
import { f as FILE_BYTES_STEP, i as checkFileId, p as digestText } from "./fileBytes-BD0v3rRG.js";
|
|
3
3
|
import { sha256 } from "@noble/hashes/sha2.js";
|
|
4
4
|
//#region ../browser/src/shared/fileBytesIdb.ts
|
|
5
5
|
var STEP = FILE_BYTES_STEP;
|
|
@@ -228,4 +228,4 @@ async function storageRoom() {
|
|
|
228
228
|
//#endregion
|
|
229
229
|
export { storageRoom as n, IdbFileBytes as t };
|
|
230
230
|
|
|
231
|
-
//# sourceMappingURL=fileBytesIdb-
|
|
231
|
+
//# sourceMappingURL=fileBytesIdb-NtA8r9EM.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileBytesIdb-BXAN7i-N.js","names":[],"sources":["../../../browser/src/shared/fileBytesIdb.ts"],"sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { STORES, openDb, wrap, committed } from \"./idb\";\nimport { FILE_BYTES_STEP, checkFileId, digestText, type FileBytes } from \"./fileBytes\";\n\n/** One piece of a file. Every piece but the last is exactly `FILE_BYTES_STEP` long. */\ninterface Chunk { id: string; index: number; length: number; data: Blob }\n\n/** The piece being filled, kept in memory until it is full or flushed: at most one step per open file. */\ninterface Tail { index: number; bytes: Uint8Array; length: number; dirty: boolean }\n\nconst STEP = FILE_BYTES_STEP;\n\nasync function chunks(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n return (await openDb()).transaction(STORES.fileChunks, mode).objectStore(STORES.fileChunks);\n}\nconst range = (id: string) => IDBKeyRange.bound([id, 0], [id, Infinity]);\n\n/**\n * Files in IndexedDB, in 1 MiB pieces stored as Blobs (which browsers keep on disk), for platforms without\n * the origin-private file system. Reading one hands out a Blob made of the pieces, so a download never\n * loads the file into memory either.\n */\nexport class IdbFileBytes implements FileBytes {\n readonly kind = \"idb\" as const;\n private readonly tails = new Map<string, Tail>();\n /** Writes to one file run one after another. */\n private readonly queues = new Map<string, Promise<unknown>>();\n\n private serial<T>(id: string, work: () => Promise<T>): Promise<T> {\n const run = (this.queues.get(id) ?? Promise.resolve()).then(work, work);\n const settled = run.catch(() => {});\n this.queues.set(id, settled);\n void settled.then(() => { if (this.queues.get(id) === settled) this.queues.delete(id); });\n return run;\n }\n\n private async list(id: string): Promise<Omit<Chunk, \"data\">[]> {\n const store = await chunks(\"readonly\");\n const keys = (await wrap(store.getAllKeys(range(id)))) as [string, number][];\n if (!keys.length) return [];\n const last = (await wrap(store.get(keys[keys.length - 1]))) as Chunk;\n return keys.map(([, index], i) => ({ id, index, length: i === keys.length - 1 ? last.length : STEP }));\n }\n\n private async put(chunk: Chunk): Promise<void> {\n await committed((await chunks(\"readwrite\")).put(chunk));\n }\n\n /** The piece being filled, loaded from storage the first time a file is written. */\n private async tail(id: string): Promise<Tail> {\n let tail = this.tails.get(id);\n if (tail) return tail;\n const pieces = await this.list(id);\n const last = pieces[pieces.length - 1];\n tail = { index: 0, bytes: new Uint8Array(STEP), length: 0, dirty: false };\n if (last && last.length < STEP) {\n const stored = (await wrap((await chunks(\"readonly\")).get([id, last.index]))) as Chunk;\n tail.index = last.index;\n tail.bytes.set(new Uint8Array(await stored.data.arrayBuffer()));\n tail.length = last.length;\n } else if (last) tail.index = last.index + 1;\n this.tails.set(id, tail);\n return tail;\n }\n\n private async sizeNow(id: string): Promise<number | null> {\n const tail = this.tails.get(id);\n if (tail) return tail.index * STEP + tail.length;\n const pieces = await this.list(id);\n if (!pieces.length) return null;\n return (pieces.length - 1) * STEP + pieces[pieces.length - 1].length;\n }\n\n private async flushNow(id: string): Promise<void> {\n const tail = this.tails.get(id);\n if (!tail?.dirty) return;\n await this.put({ id, index: tail.index, length: tail.length, data: new Blob([tail.bytes.slice(0, tail.length)]) });\n tail.dirty = false;\n }\n\n async stage(id: string, source: Blob, onProgress?: (copied: number) => void): Promise<string> {\n checkFileId(id);\n await this.remove(id);\n const hash = sha256.create();\n let offset = 0;\n const reader = source.stream().getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n hash.update(value);\n await this.append(id, offset, value);\n offset += value.length;\n onProgress?.(offset);\n }\n await this.close(id);\n } catch (error) {\n await reader.cancel().catch(() => {});\n await this.remove(id).catch(() => {});\n throw error;\n }\n return digestText(hash.digest());\n }\n\n append(id: string, offset: number, bytes: Uint8Array): Promise<void> {\n checkFileId(id);\n return this.serial(id, async () => {\n const tail = await this.tail(id);\n if (offset !== tail.index * STEP + tail.length) throw new Error(\"File write out of order\");\n let pos = 0;\n while (pos < bytes.length) {\n const take = Math.min(STEP - tail.length, bytes.length - pos);\n tail.bytes.set(bytes.subarray(pos, pos + take), tail.length);\n tail.length += take; pos += take; tail.dirty = true;\n if (tail.length === STEP) {\n await this.flushNow(id);\n tail.index += 1; tail.length = 0;\n }\n }\n });\n }\n\n flush(id: string): Promise<void> {\n return this.serial(id, () => this.flushNow(id));\n }\n\n close(id: string): Promise<void> {\n return this.serial(id, async () => { await this.flushNow(id); this.tails.delete(id); });\n }\n\n size(id: string): Promise<number | null> {\n checkFileId(id);\n return this.serial(id, () => this.sizeNow(id));\n }\n\n truncate(id: string, size: number): Promise<void> {\n checkFileId(id);\n return this.serial(id, async () => {\n await this.flushNow(id);\n this.tails.delete(id);\n const pieces = await this.list(id);\n const keep = Math.floor(size / STEP), rest = size % STEP;\n const store = await chunks(\"readwrite\");\n await Promise.all(pieces.filter((piece) => piece.index > keep || (piece.index === keep && rest === 0))\n .map((piece) => committed(store.delete([id, piece.index]))));\n const cut = pieces.find((piece) => piece.index === keep);\n if (cut && rest > 0 && cut.length > rest) {\n const stored = (await wrap((await chunks(\"readonly\")).get([id, keep]))) as Chunk;\n await this.put({ id, index: keep, length: rest, data: stored.data.slice(0, rest) });\n }\n });\n }\n\n read(id: string, offset: number, length: number): Promise<Uint8Array> {\n checkFileId(id);\n return this.serial(id, async () => {\n await this.flushNow(id);\n const out: Uint8Array[] = [];\n const store = await chunks(\"readonly\");\n const end = offset + length;\n for (let index = Math.floor(offset / STEP); index * STEP < end; index++) {\n const piece = (await wrap(store.get([id, index]))) as Chunk | undefined;\n if (!piece) break;\n const from = Math.max(0, offset - index * STEP), to = Math.min(piece.length, end - index * STEP);\n if (from < to) out.push(new Uint8Array(await piece.data.slice(from, to).arrayBuffer()));\n if (piece.length < STEP) break;\n }\n if (out.length === 1) return out[0];\n const joined = new Uint8Array(out.reduce((n, part) => n + part.length, 0));\n let pos = 0;\n for (const part of out) { joined.set(part, pos); pos += part.length; }\n return joined;\n });\n }\n\n async digest(id: string): Promise<string> {\n const hash = sha256.create();\n for await (const part of this.pieces(id)) hash.update(new Uint8Array(await part.arrayBuffer()));\n return digestText(hash.digest());\n }\n\n private async *pieces(id: string): AsyncGenerator<Blob> {\n checkFileId(id);\n await this.flush(id);\n const pieces = await this.list(id);\n for (const piece of pieces) {\n const stored = (await wrap((await chunks(\"readonly\")).get([id, piece.index]))) as Chunk | undefined;\n if (stored) yield stored.data;\n }\n }\n\n async blob(id: string, type: string): Promise<Blob | null> {\n const parts: Blob[] = [];\n for await (const part of this.pieces(id)) parts.push(part);\n return parts.length ? new Blob(parts, { type }) : (await this.size(id)) === 0 ? new Blob([], { type }) : null;\n }\n\n remove(id: string): Promise<void> {\n checkFileId(id);\n return this.serial(id, async () => {\n this.tails.delete(id);\n await committed((await chunks(\"readwrite\")).delete(range(id)));\n });\n }\n\n async removeWhere(prefix: string): Promise<void> {\n for (const id of [...this.tails.keys()]) if (id.startsWith(prefix)) this.tails.delete(id);\n const store = await chunks(\"readwrite\");\n await committed(prefix ? store.delete(IDBKeyRange.bound([prefix, 0], [`${prefix}`, Infinity])) : store.clear());\n }\n\n async room(): Promise<number | null> {\n return storageRoom();\n }\n}\n\n/** What the browser still lets this origin store, or null when it does not say. */\nexport async function storageRoom(): Promise<number | null> {\n try {\n const estimate = await navigator.storage?.estimate?.();\n if (!estimate?.quota) return null;\n return Math.max(0, estimate.quota - (estimate.usage ?? 0));\n } catch { return null; }\n}\n"],"mappings":";;;;AAUA,IAAM,OAAO;AAEb,eAAe,OAAO,MAAmD;CACvE,QAAQ,MAAM,OAAO,EAAA,CAAG,YAAY,OAAO,YAAY,IAAI,CAAC,CAAC,YAAY,OAAO,UAAU;AAC5F;AACA,IAAM,SAAS,OAAe,YAAY,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,QAAQ,CAAC;;;;;;AAOvE,IAAa,eAAb,MAA+C;CAC7C,OAAgB;CAChB,wBAAyB,IAAI,IAAkB;;CAE/C,yBAA0B,IAAI,IAA8B;CAE5D,OAAkB,IAAY,MAAoC;EAChE,MAAM,OAAO,KAAK,OAAO,IAAI,EAAE,KAAK,QAAQ,QAAQ,EAAA,CAAG,KAAK,MAAM,IAAI;EACtE,MAAM,UAAU,IAAI,YAAY,CAAC,CAAC;EAClC,KAAK,OAAO,IAAI,IAAI,OAAO;EAC3B,QAAa,WAAW;GAAE,IAAI,KAAK,OAAO,IAAI,EAAE,MAAM,SAAS,KAAK,OAAO,OAAO,EAAE;EAAG,CAAC;EACxF,OAAO;CACT;CAEA,MAAc,KAAK,IAA4C;EAC7D,MAAM,QAAQ,MAAM,OAAO,UAAU;EACrC,MAAM,OAAQ,MAAM,KAAK,MAAM,WAAW,MAAM,EAAE,CAAC,CAAC;EACpD,IAAI,CAAC,KAAK,QAAQ,OAAO,CAAC;EAC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AAS,SAAS,SAAS,EAAE;CAC3D,QAAQ;EAAE,OAAO;CAAM;AACzB"}
|
|
1
|
+
{"version":3,"file":"fileBytesIdb-NtA8r9EM.js","names":[],"sources":["../../../browser/src/shared/fileBytesIdb.ts"],"sourcesContent":["import { sha256 } from \"@noble/hashes/sha2.js\";\nimport { STORES, openDb, wrap, committed } from \"./idb\";\nimport { FILE_BYTES_STEP, checkFileId, digestText, type FileBytes } from \"./fileBytes\";\n\n/** One piece of a file. Every piece but the last is exactly `FILE_BYTES_STEP` long. */\ninterface Chunk { id: string; index: number; length: number; data: Blob }\n\n/** The piece being filled, kept in memory until it is full or flushed: at most one step per open file. */\ninterface Tail { index: number; bytes: Uint8Array; length: number; dirty: boolean }\n\nconst STEP = FILE_BYTES_STEP;\n\nasync function chunks(mode: IDBTransactionMode): Promise<IDBObjectStore> {\n return (await openDb()).transaction(STORES.fileChunks, mode).objectStore(STORES.fileChunks);\n}\nconst range = (id: string) => IDBKeyRange.bound([id, 0], [id, Infinity]);\n\n/**\n * Files in IndexedDB, in 1 MiB pieces stored as Blobs (which browsers keep on disk), for platforms without\n * the origin-private file system. Reading one hands out a Blob made of the pieces, so a download never\n * loads the file into memory either.\n */\nexport class IdbFileBytes implements FileBytes {\n readonly kind = \"idb\" as const;\n private readonly tails = new Map<string, Tail>();\n /** Writes to one file run one after another. */\n private readonly queues = new Map<string, Promise<unknown>>();\n\n private serial<T>(id: string, work: () => Promise<T>): Promise<T> {\n const run = (this.queues.get(id) ?? Promise.resolve()).then(work, work);\n const settled = run.catch(() => {});\n this.queues.set(id, settled);\n void settled.then(() => { if (this.queues.get(id) === settled) this.queues.delete(id); });\n return run;\n }\n\n private async list(id: string): Promise<Omit<Chunk, \"data\">[]> {\n const store = await chunks(\"readonly\");\n const keys = (await wrap(store.getAllKeys(range(id)))) as [string, number][];\n if (!keys.length) return [];\n const last = (await wrap(store.get(keys[keys.length - 1]))) as Chunk;\n return keys.map(([, index], i) => ({ id, index, length: i === keys.length - 1 ? last.length : STEP }));\n }\n\n private async put(chunk: Chunk): Promise<void> {\n await committed((await chunks(\"readwrite\")).put(chunk));\n }\n\n /** The piece being filled, loaded from storage the first time a file is written. */\n private async tail(id: string): Promise<Tail> {\n let tail = this.tails.get(id);\n if (tail) return tail;\n const pieces = await this.list(id);\n const last = pieces[pieces.length - 1];\n tail = { index: 0, bytes: new Uint8Array(STEP), length: 0, dirty: false };\n if (last && last.length < STEP) {\n const stored = (await wrap((await chunks(\"readonly\")).get([id, last.index]))) as Chunk;\n tail.index = last.index;\n tail.bytes.set(new Uint8Array(await stored.data.arrayBuffer()));\n tail.length = last.length;\n } else if (last) tail.index = last.index + 1;\n this.tails.set(id, tail);\n return tail;\n }\n\n private async sizeNow(id: string): Promise<number | null> {\n const tail = this.tails.get(id);\n if (tail) return tail.index * STEP + tail.length;\n const pieces = await this.list(id);\n if (!pieces.length) return null;\n return (pieces.length - 1) * STEP + pieces[pieces.length - 1].length;\n }\n\n private async flushNow(id: string): Promise<void> {\n const tail = this.tails.get(id);\n if (!tail?.dirty) return;\n await this.put({ id, index: tail.index, length: tail.length, data: new Blob([tail.bytes.slice(0, tail.length)]) });\n tail.dirty = false;\n }\n\n async stage(id: string, source: Blob, onProgress?: (copied: number) => void): Promise<string> {\n checkFileId(id);\n await this.remove(id);\n const hash = sha256.create();\n let offset = 0;\n const reader = source.stream().getReader();\n try {\n for (;;) {\n const { done, value } = await reader.read();\n if (done) break;\n hash.update(value);\n await this.append(id, offset, value);\n offset += value.length;\n onProgress?.(offset);\n }\n await this.close(id);\n } catch (error) {\n await reader.cancel().catch(() => {});\n await this.remove(id).catch(() => {});\n throw error;\n }\n return digestText(hash.digest());\n }\n\n append(id: string, offset: number, bytes: Uint8Array): Promise<void> {\n checkFileId(id);\n return this.serial(id, async () => {\n const tail = await this.tail(id);\n if (offset !== tail.index * STEP + tail.length) throw new Error(\"File write out of order\");\n let pos = 0;\n while (pos < bytes.length) {\n const take = Math.min(STEP - tail.length, bytes.length - pos);\n tail.bytes.set(bytes.subarray(pos, pos + take), tail.length);\n tail.length += take; pos += take; tail.dirty = true;\n if (tail.length === STEP) {\n await this.flushNow(id);\n tail.index += 1; tail.length = 0;\n }\n }\n });\n }\n\n flush(id: string): Promise<void> {\n return this.serial(id, () => this.flushNow(id));\n }\n\n close(id: string): Promise<void> {\n return this.serial(id, async () => { await this.flushNow(id); this.tails.delete(id); });\n }\n\n size(id: string): Promise<number | null> {\n checkFileId(id);\n return this.serial(id, () => this.sizeNow(id));\n }\n\n truncate(id: string, size: number): Promise<void> {\n checkFileId(id);\n return this.serial(id, async () => {\n await this.flushNow(id);\n this.tails.delete(id);\n const pieces = await this.list(id);\n const keep = Math.floor(size / STEP), rest = size % STEP;\n const store = await chunks(\"readwrite\");\n await Promise.all(pieces.filter((piece) => piece.index > keep || (piece.index === keep && rest === 0))\n .map((piece) => committed(store.delete([id, piece.index]))));\n const cut = pieces.find((piece) => piece.index === keep);\n if (cut && rest > 0 && cut.length > rest) {\n const stored = (await wrap((await chunks(\"readonly\")).get([id, keep]))) as Chunk;\n await this.put({ id, index: keep, length: rest, data: stored.data.slice(0, rest) });\n }\n });\n }\n\n read(id: string, offset: number, length: number): Promise<Uint8Array> {\n checkFileId(id);\n return this.serial(id, async () => {\n await this.flushNow(id);\n const out: Uint8Array[] = [];\n const store = await chunks(\"readonly\");\n const end = offset + length;\n for (let index = Math.floor(offset / STEP); index * STEP < end; index++) {\n const piece = (await wrap(store.get([id, index]))) as Chunk | undefined;\n if (!piece) break;\n const from = Math.max(0, offset - index * STEP), to = Math.min(piece.length, end - index * STEP);\n if (from < to) out.push(new Uint8Array(await piece.data.slice(from, to).arrayBuffer()));\n if (piece.length < STEP) break;\n }\n if (out.length === 1) return out[0];\n const joined = new Uint8Array(out.reduce((n, part) => n + part.length, 0));\n let pos = 0;\n for (const part of out) { joined.set(part, pos); pos += part.length; }\n return joined;\n });\n }\n\n async digest(id: string): Promise<string> {\n const hash = sha256.create();\n for await (const part of this.pieces(id)) hash.update(new Uint8Array(await part.arrayBuffer()));\n return digestText(hash.digest());\n }\n\n private async *pieces(id: string): AsyncGenerator<Blob> {\n checkFileId(id);\n await this.flush(id);\n const pieces = await this.list(id);\n for (const piece of pieces) {\n const stored = (await wrap((await chunks(\"readonly\")).get([id, piece.index]))) as Chunk | undefined;\n if (stored) yield stored.data;\n }\n }\n\n async blob(id: string, type: string): Promise<Blob | null> {\n const parts: Blob[] = [];\n for await (const part of this.pieces(id)) parts.push(part);\n return parts.length ? new Blob(parts, { type }) : (await this.size(id)) === 0 ? new Blob([], { type }) : null;\n }\n\n remove(id: string): Promise<void> {\n checkFileId(id);\n return this.serial(id, async () => {\n this.tails.delete(id);\n await committed((await chunks(\"readwrite\")).delete(range(id)));\n });\n }\n\n async removeWhere(prefix: string): Promise<void> {\n for (const id of [...this.tails.keys()]) if (id.startsWith(prefix)) this.tails.delete(id);\n const store = await chunks(\"readwrite\");\n await committed(prefix ? store.delete(IDBKeyRange.bound([prefix, 0], [`${prefix}`, Infinity])) : store.clear());\n }\n\n async room(): Promise<number | null> {\n return storageRoom();\n }\n}\n\n/** What the browser still lets this origin store, or null when it does not say. */\nexport async function storageRoom(): Promise<number | null> {\n try {\n const estimate = await navigator.storage?.estimate?.();\n if (!estimate?.quota) return null;\n return Math.max(0, estimate.quota - (estimate.usage ?? 0));\n } catch { return null; }\n}\n"],"mappings":";;;;AAUA,IAAM,OAAO;AAEb,eAAe,OAAO,MAAmD;CACvE,QAAQ,MAAM,OAAO,EAAA,CAAG,YAAY,OAAO,YAAY,IAAI,CAAC,CAAC,YAAY,OAAO,UAAU;AAC5F;AACA,IAAM,SAAS,OAAe,YAAY,MAAM,CAAC,IAAI,CAAC,GAAG,CAAC,IAAI,QAAQ,CAAC;;;;;;AAOvE,IAAa,eAAb,MAA+C;CAC7C,OAAgB;CAChB,wBAAyB,IAAI,IAAkB;;CAE/C,yBAA0B,IAAI,IAA8B;CAE5D,OAAkB,IAAY,MAAoC;EAChE,MAAM,OAAO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AK,CAAC,GAAG,IAAI,GAAG,WAAW,MAAM,GAAG,KAAK,MAAM,OAAO,EAAE;EACxF,MAAM,QAAQ,MAAM,OAAO,WAAW;EACtC,MAAM,UAAU,SAAS,MAAM,OAAO,YAAY,MAAM,CAAC,QAAQ,CAAC,GAAG,CAAC,GAAG,OAAO,IAAI,QAAQ,CAAC,CAAC,IAAI,MAAM,MAAM,CAAC;CACjH;CAEA,MAAM,OAA+B;EACnC,OAAO,YAAY;CACrB;AACF;;AAGA,eAAsB,cAAsC;CAC1D,IAAI;EACF,MAAM,WAAW,MAAM,UAAU,SAAS,WAAW;EACrD,IAAI,CAAC,UAAU,OAAO,OAAO;EAC7B,OAAO,KAAK,IAAI,GAAG,SAAS,SAAS,SAAS,SAAS,EAAE;CAC3D,QAAQ;EAAE,OAAO;CAAM;AACzB"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
|
-
import { c as fileSpace, f as FILE_BYTES_STEP, i as checkFileId } from "./fileBytes-
|
|
2
|
-
import { n as storageRoom } from "./fileBytesIdb-
|
|
1
|
+
import { c as fileSpace, f as FILE_BYTES_STEP, i as checkFileId } from "./fileBytes-BD0v3rRG.js";
|
|
2
|
+
import { n as storageRoom } from "./fileBytesIdb-NtA8r9EM.js";
|
|
3
3
|
//#region ../browser/src/shared/fileBytesOpfs.ts
|
|
4
4
|
/**
|
|
5
5
|
* Files in the origin-private file system, written by `fileBytesWorker.ts`. Every page and the peer of one
|
|
@@ -154,4 +154,4 @@ var OpfsFileBytes = class OpfsFileBytes {
|
|
|
154
154
|
//#endregion
|
|
155
155
|
export { OpfsFileBytes };
|
|
156
156
|
|
|
157
|
-
//# sourceMappingURL=fileBytesOpfs-
|
|
157
|
+
//# sourceMappingURL=fileBytesOpfs-B8fJwkwM.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileBytesOpfs-
|
|
1
|
+
{"version":3,"file":"fileBytesOpfs-B8fJwkwM.js","names":[],"sources":["../../../browser/src/shared/fileBytesOpfs.ts"],"sourcesContent":["import { FILE_BYTES_STEP, checkFileId, fileSpace, type FileBytes } from \"./fileBytes\";\nimport { storageRoom } from \"./fileBytesIdb\";\nimport type { WorkerReply, WorkerRequest } from \"./fileBytesWorker\";\n\ntype Request = WorkerRequest extends infer R ? R extends unknown ? Omit<R, \"n\" | \"space\"> : never : never;\n\n/**\n * Files in the origin-private file system, written by `fileBytesWorker.ts`. Every page and the peer of one\n * profile see the same folder; a file is written by one of them at a time (the page copies a file it sends,\n * the peer writes one it receives), and read as a Blob only once it is closed.\n */\nexport class OpfsFileBytes implements FileBytes {\n readonly kind = \"opfs\" as const;\n /** Shared with the views `forSpace` makes: one worker, one run of request numbers. */\n private readonly counter = { next: 1 };\n /** Another profile's folder (`forSpace`); the active profile's when not set. */\n private fixedSpace?: string;\n private readonly waiting = new Map<number, { resolve(value: unknown): void; reject(error: Error): void; progress?(n: number): void }>();\n\n private constructor(private readonly worker: Worker) {\n worker.onmessage = (event: MessageEvent<WorkerReply>) => {\n const reply = event.data, pending = this.waiting.get(reply.n);\n if (!pending) return;\n if (\"progress\" in reply) return pending.progress?.(reply.progress);\n this.waiting.delete(reply.n);\n // An error keeps the name the worker gave it: \"no room left\" is told from any other failure by its name.\n if (reply.ok) pending.resolve(reply.value); else pending.reject(reply.name ? Object.assign(new Error(reply.error), { name: reply.name }) : new Error(reply.error));\n };\n worker.onerror = (event) => {\n event.preventDefault();\n for (const pending of this.waiting.values()) pending.reject(new Error(`File storage stopped: ${event.message || \"unknown error\"}`));\n this.waiting.clear();\n };\n }\n\n /** The worker, if this browser can run it and gives it sync access handles; null otherwise. */\n static async open(): Promise<OpfsFileBytes | null> {\n if (typeof Worker === \"undefined\" || typeof navigator === \"undefined\" || !navigator.storage?.getDirectory) return null;\n const store = new OpfsFileBytes(new Worker(new URL(\"./fileBytesWorker.ts\", import.meta.url), { type: \"module\" }));\n try {\n if (await store.call<boolean>({ op: \"probe\" })) return store;\n } catch { /* no OPFS here (a private window, an old engine) */ }\n store.worker.terminate();\n return null;\n }\n\n private space(): string { return this.fixedSpace ?? fileSpace(); }\n\n /** A view on the same worker that reads and writes another profile's folder. */\n forSpace(space: string): OpfsFileBytes {\n const view = Object.create(this) as OpfsFileBytes;\n view.fixedSpace = space;\n return view;\n }\n\n private call<T>(request: Request, transfer: Transferable[] = [], progress?: (n: number) => void): Promise<T> {\n const n = this.counter.next++;\n return new Promise<T>((resolve, reject) => {\n this.waiting.set(n, { resolve: resolve as (value: unknown) => void, reject, progress });\n this.worker.postMessage({ ...request, n, space: this.space() } as WorkerRequest, transfer);\n });\n }\n\n stage(id: string, source: Blob, onProgress?: (copied: number) => void): Promise<string> {\n return this.call({ op: \"stage\", id: checkFileId(id), source }, [], onProgress);\n }\n append(id: string, offset: number, bytes: Uint8Array): Promise<void> {\n // A copy goes to the worker: the caller's buffer may be a view into something it still uses.\n const copy = bytes.slice();\n return this.call({ op: \"append\", id: checkFileId(id), offset, bytes: copy }, [copy.buffer]);\n }\n flush(id: string): Promise<void> { return this.call({ op: \"flush\", id: checkFileId(id) }); }\n close(id: string): Promise<void> { return this.call({ op: \"close\", id: checkFileId(id) }); }\n size(id: string): Promise<number | null> { return this.call({ op: \"size\", id: checkFileId(id) }); }\n truncate(id: string, size: number): Promise<void> { return this.call({ op: \"truncate\", id: checkFileId(id), size }); }\n read(id: string, offset: number, length: number): Promise<Uint8Array> {\n return this.call({ op: \"read\", id: checkFileId(id), offset, length: Math.min(length, 16 * FILE_BYTES_STEP) });\n }\n digest(id: string): Promise<string> { return this.call({ op: \"digest\", id: checkFileId(id) }); }\n remove(id: string): Promise<void> { return this.call({ op: \"remove\", id: checkFileId(id) }); }\n removeWhere(prefix: string): Promise<void> { return this.call({ op: \"removeWhere\", prefix }); }\n\n async blob(id: string, type: string): Promise<Blob | null> {\n // Closed first: a file with a sync access handle open cannot be read as a Blob.\n await this.close(id);\n try {\n const root = await (await navigator.storage.getDirectory()).getDirectoryHandle(\"ghostly-files\");\n const file = await (await (await root.getDirectoryHandle(this.space())).getFileHandle(checkFileId(id))).getFile();\n // A slice with a type: still the file on disk, never read into memory.\n return file.slice(0, file.size, type);\n } catch { return null; }\n }\n\n room(): Promise<number | null> { return storageRoom(); }\n\n async dropSpace(space: string): Promise<void> {\n try {\n const root = await (await navigator.storage.getDirectory()).getDirectoryHandle(\"ghostly-files\");\n await root.removeEntry(space, { recursive: true });\n } catch (error) { if ((error as { name?: string })?.name !== \"NotFoundError\") throw error; }\n }\n}\n"],"mappings":";;;;;;;;AAWA,IAAa,gBAAb,MAAa,cAAmC;CAQT;CAPrC,OAAgB;;CAEhB,UAA2B,EAAE,MAAM,EAAE;;CAErC;CACA,0BAA2B,IAAI,IAAuG;CAEtI,YAAoB,QAAiC;EAAhB,KAAA,SAAA;EACnC,OAAO,aAAa,UAAqC;GACvD,MAAM,QAAQ,MAAM,MAAM,UAAU,KAAK,QAAQ,IAAI,MAAM,CAAC;GAC5D,IAAI,CAAC,SAAS;GACd,IAAI,cAAc,OAAO,OAAO,QAAQ,WAAW,MAAM,QAAQ;GACjE,KAAK,QAAQ,OAAO,MAAM,CAAC;GAE3B,IAAI,MAAM,IAAI,QAAQ,QAAQ,MAAM,KAAK;QAAQ,QAAQ,OAAO,MAAM,OAAO,OAAO,OAAO,IAAI,MAAM,MAAM,KAAK,GAAG,EAAE,MAAM,MAAM,KAAK,CAAC,IAAI,IAAI,MAAM,MAAM,KAAK,CAAC;EACnK;EACA,OAAO,WAAW,UAAU;GAC1B,MAAM,eAAe;GACrB,KAAK,MAAM,WAAW,KAAK,QAAQ,OAAO,GAAG,QAAQ,uBAAO,IAAI,MAAM,yBAAyB,MAAM,WAAW,iBAAiB,CAAC;GAClI,KAAK,QAAQ,MAAM;EACrB;CACF;;CAGA,aAAa,OAAsC;EACjD,IAAI,OAAO,WAAW,eAAe,OAAO,cAAc,eAAe,CAAC,UAAU,SAAS,cAAc,OAAO;EAClH,MAAM,QAAQ,IAAI,cAAc,IAAI,OAAO,IAAI,IAAI,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TextEncoder.encodeInto = functio
|
|
|
212
212
|
};
|
|
213
213
|
};
|
|
214
214
|
var WASM_VECTOR_LEN = 0;
|
|
215
|
-
function
|
|
216
|
-
wasm.
|
|
215
|
+
function __wasm_bindgen_func_elem_4186(arg0, arg1, arg2) {
|
|
216
|
+
wasm.__wasm_bindgen_func_elem_4186(arg0, arg1, addHeapObject(arg2));
|
|
217
217
|
}
|
|
218
|
-
function
|
|
219
|
-
wasm.
|
|
218
|
+
function __wasm_bindgen_func_elem_8907(arg0, arg1) {
|
|
219
|
+
wasm.__wasm_bindgen_func_elem_8907(arg0, arg1);
|
|
220
220
|
}
|
|
221
|
-
function
|
|
222
|
-
wasm.
|
|
221
|
+
function __wasm_bindgen_func_elem_3598(arg0, arg1) {
|
|
222
|
+
wasm.__wasm_bindgen_func_elem_3598(arg0, arg1);
|
|
223
223
|
}
|
|
224
|
-
function
|
|
225
|
-
wasm.
|
|
224
|
+
function __wasm_bindgen_func_elem_3637(arg0, arg1) {
|
|
225
|
+
wasm.__wasm_bindgen_func_elem_3637(arg0, arg1);
|
|
226
226
|
}
|
|
227
|
-
function
|
|
228
|
-
wasm.
|
|
227
|
+
function __wasm_bindgen_func_elem_8961(arg0, arg1, arg2) {
|
|
228
|
+
wasm.__wasm_bindgen_func_elem_8961(arg0, arg1, addHeapObject(arg2));
|
|
229
229
|
}
|
|
230
|
-
function
|
|
231
|
-
wasm.
|
|
230
|
+
function __wasm_bindgen_func_elem_3298(arg0, arg1) {
|
|
231
|
+
wasm.__wasm_bindgen_func_elem_3298(arg0, arg1);
|
|
232
232
|
}
|
|
233
|
-
function
|
|
234
|
-
wasm.
|
|
233
|
+
function __wasm_bindgen_func_elem_1646(arg0, arg1, arg2) {
|
|
234
|
+
wasm.__wasm_bindgen_func_elem_1646(arg0, arg1, addHeapObject(arg2));
|
|
235
|
+
}
|
|
236
|
+
function __wasm_bindgen_func_elem_9044(arg0, arg1, arg2, arg3) {
|
|
237
|
+
wasm.__wasm_bindgen_func_elem_9044(arg0, arg1, addHeapObject(arg2), addHeapObject(arg3));
|
|
235
238
|
}
|
|
236
239
|
var __wbindgen_enum_BinaryType = ["blob", "arraybuffer"];
|
|
237
240
|
var __wbindgen_enum_ReadableStreamType = ["bytes"];
|
|
@@ -835,7 +838,7 @@ function __wbg_get_imports() {
|
|
|
835
838
|
const a = state0.a;
|
|
836
839
|
state0.a = 0;
|
|
837
840
|
try {
|
|
838
|
-
return
|
|
841
|
+
return __wasm_bindgen_func_elem_9044(a, state0.b, arg0, arg1);
|
|
839
842
|
} finally {
|
|
840
843
|
state0.a = a;
|
|
841
844
|
}
|
|
@@ -1082,28 +1085,31 @@ function __wbg_get_imports() {
|
|
|
1082
1085
|
return getObject(arg0).wasClean;
|
|
1083
1086
|
};
|
|
1084
1087
|
imports.wbg.__wbindgen_cast_0edd631f92b0110b = function(arg0, arg1) {
|
|
1085
|
-
return addHeapObject(makeMutClosure(arg0, arg1, wasm.
|
|
1088
|
+
return addHeapObject(makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_3281, __wasm_bindgen_func_elem_3298));
|
|
1086
1089
|
};
|
|
1087
1090
|
imports.wbg.__wbindgen_cast_2241b6af4c4b2941 = function(arg0, arg1) {
|
|
1088
1091
|
return addHeapObject(getStringFromWasm0(arg0, arg1));
|
|
1089
1092
|
};
|
|
1090
1093
|
imports.wbg.__wbindgen_cast_4538106662548ce4 = function(arg0, arg1) {
|
|
1091
|
-
return addHeapObject(makeMutClosure(arg0, arg1, wasm.
|
|
1094
|
+
return addHeapObject(makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_1145, __wasm_bindgen_func_elem_1646));
|
|
1095
|
+
};
|
|
1096
|
+
imports.wbg.__wbindgen_cast_4c22cf293645a24f = function(arg0, arg1) {
|
|
1097
|
+
return addHeapObject(makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_4157, __wasm_bindgen_func_elem_4186));
|
|
1092
1098
|
};
|
|
1093
|
-
imports.wbg.
|
|
1094
|
-
return addHeapObject(makeMutClosure(arg0, arg1, wasm.
|
|
1099
|
+
imports.wbg.__wbindgen_cast_508787dc0eab30af = function(arg0, arg1) {
|
|
1100
|
+
return addHeapObject(makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_3596, __wasm_bindgen_func_elem_3598));
|
|
1095
1101
|
};
|
|
1096
|
-
imports.wbg.
|
|
1097
|
-
return addHeapObject(
|
|
1102
|
+
imports.wbg.__wbindgen_cast_5bb0c9521bd53709 = function(arg0, arg1) {
|
|
1103
|
+
return addHeapObject(makeClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_3621, __wasm_bindgen_func_elem_3637));
|
|
1104
|
+
};
|
|
1105
|
+
imports.wbg.__wbindgen_cast_a94aa01267934ec1 = function(arg0, arg1) {
|
|
1106
|
+
return addHeapObject(makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_8951, __wasm_bindgen_func_elem_8961));
|
|
1098
1107
|
};
|
|
1099
1108
|
imports.wbg.__wbindgen_cast_cb9088102bce6b30 = function(arg0, arg1) {
|
|
1100
1109
|
return addHeapObject(getArrayU8FromWasm0(arg0, arg1));
|
|
1101
1110
|
};
|
|
1102
|
-
imports.wbg.
|
|
1103
|
-
return addHeapObject(makeMutClosure(arg0, arg1, wasm.
|
|
1104
|
-
};
|
|
1105
|
-
imports.wbg.__wbindgen_cast_f5c35a25fe7a7600 = function(arg0, arg1) {
|
|
1106
|
-
return addHeapObject(makeClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_3614, __wasm_bindgen_func_elem_3630));
|
|
1111
|
+
imports.wbg.__wbindgen_cast_eea14ffc1ab98fca = function(arg0, arg1) {
|
|
1112
|
+
return addHeapObject(makeMutClosure(arg0, arg1, wasm.__wasm_bindgen_func_elem_8902, __wasm_bindgen_func_elem_8907));
|
|
1107
1113
|
};
|
|
1108
1114
|
imports.wbg.__wbindgen_object_clone_ref = function(arg0) {
|
|
1109
1115
|
return addHeapObject(getObject(arg0));
|
|
@@ -1145,4 +1151,4 @@ async function __wbg_init(module_or_path) {
|
|
|
1145
1151
|
//#endregion
|
|
1146
1152
|
export { IntoUnderlyingByteSource, IntoUnderlyingSink, IntoUnderlyingSource, IrohConn, IrohNode, __wbg_init as default, initSync };
|
|
1147
1153
|
|
|
1148
|
-
//# sourceMappingURL=ghostly_iroh_web-
|
|
1154
|
+
//# sourceMappingURL=ghostly_iroh_web-CO0onry8.js.map
|