@powersync/web 2.6.0 → 2.7.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (70) hide show
  1. package/dist/index.react_native_web.js +667 -140
  2. package/dist/index.react_native_web.js.map +1 -1
  3. package/dist/worker/{OPFSCoopSyncVFS-CDNBPKfy.js → OPFSCoopSyncVFS-Dujy2ZwX.js} +2 -2
  4. package/dist/worker/{OPFSCoopSyncVFS-CDNBPKfy.js.map → OPFSCoopSyncVFS-Dujy2ZwX.js.map} +1 -1
  5. package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js +2 -0
  6. package/dist/worker/SimpleOpfsFileSystem-6GYD1Xui.js.map +1 -0
  7. package/dist/worker/worker.js +1 -1
  8. package/dist/worker/worker.js.map +1 -1
  9. package/lib/db/NavigatorTriggerClaimManager.js +1 -1
  10. package/lib/db/NavigatorTriggerClaimManager.js.map +1 -1
  11. package/lib/db/PowerSyncDatabase.js +1 -1
  12. package/lib/db/PowerSyncDatabase.js.map +1 -1
  13. package/lib/db/adapters/options.d.ts +25 -2
  14. package/lib/db/adapters/options.js.map +1 -1
  15. package/lib/db/adapters/wa-sqlite/ConcurrentConnection.d.ts +56 -7
  16. package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js +130 -25
  17. package/lib/db/adapters/wa-sqlite/ConcurrentConnection.js.map +1 -1
  18. package/lib/db/adapters/wa-sqlite/DatabaseClient.d.ts +13 -0
  19. package/lib/db/adapters/wa-sqlite/DatabaseClient.js.map +1 -1
  20. package/lib/db/adapters/wa-sqlite/RawSqliteConnection.d.ts +2 -1
  21. package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js +12 -6
  22. package/lib/db/adapters/wa-sqlite/RawSqliteConnection.js.map +1 -1
  23. package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.d.ts +30 -0
  24. package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.js +210 -0
  25. package/lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.js.map +1 -0
  26. package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.d.ts +1 -0
  27. package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js +178 -75
  28. package/lib/db/adapters/wa-sqlite/WASQLiteOpenFactory.js.map +1 -1
  29. package/lib/db/adapters/wa-sqlite/vfs.d.ts +30 -4
  30. package/lib/db/adapters/wa-sqlite/vfs.js +53 -2
  31. package/lib/db/adapters/wa-sqlite/vfs.js.map +1 -1
  32. package/lib/db/sync/SharedWebStreamingSyncImplementation.js +1 -1
  33. package/lib/db/sync/SharedWebStreamingSyncImplementation.js.map +1 -1
  34. package/lib/db/sync/WebStreamingSyncImplementation.js +1 -1
  35. package/lib/db/sync/WebStreamingSyncImplementation.js.map +1 -1
  36. package/lib/shared/{tab_close_signal.d.ts → locks.d.ts} +13 -0
  37. package/lib/shared/locks.js +56 -0
  38. package/lib/shared/locks.js.map +1 -0
  39. package/lib/worker/db/MultiDatabaseServer.js +37 -12
  40. package/lib/worker/db/MultiDatabaseServer.js.map +1 -1
  41. package/lib/worker/sync/SharedSyncImplementation.js +1 -1
  42. package/lib/worker/sync/SharedSyncImplementation.js.map +1 -1
  43. package/lib/worker/sync/WorkerClient.js +1 -1
  44. package/lib/worker/sync/WorkerClient.js.map +1 -1
  45. package/lib/worker/worker.js +67 -1
  46. package/lib/worker/worker.js.map +1 -1
  47. package/package.json +3 -3
  48. package/src/db/NavigatorTriggerClaimManager.ts +1 -1
  49. package/src/db/PowerSyncDatabase.ts +1 -1
  50. package/src/db/adapters/options.ts +27 -2
  51. package/src/db/adapters/wa-sqlite/ConcurrentConnection.ts +148 -34
  52. package/src/db/adapters/wa-sqlite/DatabaseClient.ts +16 -0
  53. package/src/db/adapters/wa-sqlite/RawSqliteConnection.ts +16 -7
  54. package/src/db/adapters/wa-sqlite/SimpleOpfsFileSystem.ts +249 -0
  55. package/src/db/adapters/wa-sqlite/WASQLiteOpenFactory.ts +236 -97
  56. package/src/db/adapters/wa-sqlite/vfs.ts +61 -7
  57. package/src/db/sync/SharedWebStreamingSyncImplementation.ts +1 -1
  58. package/src/db/sync/WebStreamingSyncImplementation.ts +1 -1
  59. package/src/shared/locks.ts +66 -0
  60. package/src/worker/db/MultiDatabaseServer.ts +46 -12
  61. package/src/worker/sync/SharedSyncImplementation.ts +1 -1
  62. package/src/worker/sync/WorkerClient.ts +1 -1
  63. package/src/worker/worker.ts +82 -3
  64. package/lib/shared/navigator.d.ts +0 -1
  65. package/lib/shared/navigator.js +0 -7
  66. package/lib/shared/navigator.js.map +0 -1
  67. package/lib/shared/tab_close_signal.js +0 -27
  68. package/lib/shared/tab_close_signal.js.map +0 -1
  69. package/src/shared/navigator.ts +0 -9
  70. package/src/shared/tab_close_signal.ts +0 -28
@@ -1,2 +1,2 @@
1
- import{F as e}from"./FacadeVFS-d1ZDvud7.js";import{r as s,f as t,j as a,k as r,S as i,l as n,m as l,n as c,o,p as h,q as d,t as u,u as p,v as g,w as F,e as f,B as w,D as H,d as m}from"./worker.js";const y=new Set(["NoModificationAllowedError","InvalidStateError"]),R=["","-journal","-wal"],b=new FinalizationRegistry(e=>e());class k{path;flags;accessHandle;persistentFile;constructor(e,s){this.path=e,this.flags=s}}class L{fileHandle;accessHandle=null;isLockBusy=!1;isFileLocked=!1;isRequestInProgress=!1;handleLockReleaser=null;handleRequestChannel;isHandleRequested=!1;constructor(e){this.fileHandle=e}}class A extends e{mapIdToFile=new Map;lastError=null;log=null;persistentFiles=new Map;boundAccessHandles=new Map;unboundAccessHandles=new Set;accessiblePaths=new Set;releaser=null;options={getRoot:()=>navigator.storage.getDirectory(),prefix:""};static async create(e,s,t={}){const a=new A(e,s,t);return await Promise.all([a.isReady(),a.#e(10)]),a}constructor(e,s,t={}){super(e,s),Object.assign(this.options,t)}async#e(e){const s=await this.options.getRoot();for await(const e of s.values())"directory"===e.kind&&e.name.startsWith(".ahp-")&&await navigator.locks.request(e.name,{ifAvailable:!0},async t=>{t?(this.log?.(`Deleting temporary directory ${e.name}`),await s.removeEntry(e.name,{recursive:!0}).catch(e=>{if("NotFoundError"!==e?.name)throw e})):this.log?.(`Temporary directory ${e.name} is in use`)});const t=`.ahp-${Math.random().toString(36).slice(2)}`;this.releaser=await new Promise(e=>{navigator.locks.request(t,()=>new Promise(s=>{e(s)}))}),b.register(this,this.releaser);const a=await s.getDirectoryHandle(t,{create:!0});for(let s=0;s<e;s++){const e=await a.getFileHandle(`${s}.tmp`,{create:!0}),t=await e.createSyncAccessHandle();this.unboundAccessHandles.add(t)}}jOpen(e,n,l,c){try{const o=new URL(e||Math.random().toString(36).slice(2),"file://").pathname;if(l&s){const e=this.persistentFiles.get(o);if(e?.isRequestInProgress)return t;if(!e){this.log?.(`creating persistent file for ${o}`);const e=!!(l&a);return this._module.retryOps.push((async()=>{try{let s=await this.options.getRoot();const t=o.split("/").filter(e=>e),a=t.pop();for(const a of t)s=await s.getDirectoryHandle(a,{create:e});for(const t of R){const r=await s.getFileHandle(a+t,{create:e});await this.#s(r)}const r=new k(o,l);r.persistentFile=this.persistentFiles.get(o),await this.#t(r)}catch(e){const s=new L(null);this.persistentFiles.set(o,s),this.lastError=e,console.error(e)}})()),t}if(!e.fileHandle)return this.persistentFiles.delete(o),r;if(!e.accessHandle)return this._module.retryOps.push((async()=>{const e=new k(o,l);e.persistentFile=this.persistentFiles.get(o),await this.#t(e)})()),t}if(!(this.accessiblePaths.has(o)||l&a))throw new Error(`File ${o} not found`);const h=new k(o,l);return this.mapIdToFile.set(n,h),this.persistentFiles.has(o)?h.persistentFile=this.persistentFiles.get(o):this.boundAccessHandles.has(o)?h.accessHandle=this.boundAccessHandles.get(o):this.unboundAccessHandles.size&&(h.accessHandle=this.unboundAccessHandles.values().next().value,h.accessHandle.truncate(0),this.unboundAccessHandles.delete(h.accessHandle),this.boundAccessHandles.set(o,h.accessHandle)),this.accessiblePaths.add(o),c.setInt32(0,l,!0),i}catch(e){return this.lastError=e,r}}jDelete(e,s){try{const s=new URL(e,"file://").pathname;if(this.persistentFiles.has(s)){this.persistentFiles.get(s).accessHandle.truncate(0)}else this.boundAccessHandles.get(s)?.truncate(0);return this.accessiblePaths.delete(s),i}catch(e){return this.lastError=e,n}}jAccess(e,s,t){try{const s=new URL(e,"file://").pathname;return t.setInt32(0,this.accessiblePaths.has(s)?1:0,!0),i}catch(e){return this.lastError=e,l}}jClose(e){try{const t=this.mapIdToFile.get(e);return this.mapIdToFile.delete(e),t?.flags&s?t.persistentFile?.handleLockReleaser&&this.#a(t):t?.flags&c&&(t.accessHandle.truncate(0),this.accessiblePaths.delete(t.path),this.persistentFiles.has(t.path)||(this.boundAccessHandles.delete(t.path),this.unboundAccessHandles.add(t.accessHandle))),i}catch(e){return this.lastError=e,o}}jRead(e,t,a){try{const r=this.mapIdToFile.get(e),n=(r.accessHandle||r.persistentFile.accessHandle).read(t.subarray(),{at:a});return r.flags&s&&!r.persistentFile.isFileLocked&&this.#a(r),n<t.byteLength?(t.fill(0,n),h):i}catch(e){return this.lastError=e,d}}jWrite(e,s,t){try{const a=this.mapIdToFile.get(e),r=a.accessHandle||a.persistentFile.accessHandle;if(r.write(s.subarray(),{at:t})!==s.byteLength)throw new Error("short write");return i}catch(e){return this.lastError=e,u}}jTruncate(e,s){try{const t=this.mapIdToFile.get(e);return(t.accessHandle||t.persistentFile.accessHandle).truncate(s),i}catch(e){return this.lastError=e,p}}jSync(e,s){try{const s=this.mapIdToFile.get(e);return(s.accessHandle||s.persistentFile.accessHandle).flush(),i}catch(e){return this.lastError=e,g}}jFileSize(e,s){try{const t=this.mapIdToFile.get(e),a=(t.accessHandle||t.persistentFile.accessHandle).getSize();return s.setBigInt64(0,BigInt(a),!0),i}catch(e){return this.lastError=e,F}}jLock(e,s){const a=this.mapIdToFile.get(e);return a.persistentFile.isRequestInProgress?(a.persistentFile.isLockBusy=!0,t):(a.persistentFile.isFileLocked=!0,a.persistentFile.handleLockReleaser?(a.persistentFile.isLockBusy=!1,i):(a.persistentFile.handleRequestChannel.onmessage=()=>{this.log?.(`received notification for ${a.path}`),a.persistentFile.isFileLocked?a.persistentFile.isHandleRequested=!0:this.#a(a),a.persistentFile.handleRequestChannel.onmessage=null},this.#t(a),this.log?.("returning SQLITE_BUSY"),a.persistentFile.isLockBusy=!0,t))}jUnlock(e,s){const t=this.mapIdToFile.get(e);return s===f&&(t.persistentFile.isLockBusy||(t.persistentFile.isFileLocked=!1,t.persistentFile.isHandleRequested&&setTimeout(()=>{!t.persistentFile.isFileLocked&&t.persistentFile.isHandleRequested&&(this.#a(t),t.persistentFile.isHandleRequested=!1)}))),i}jFileControl(e,s,t){try{const a=this.mapIdToFile.get(e);if(s===w){const e=q(t,4),s=q(t,8);if(this.log?.("xFileControl",a.path,"PRAGMA",e,s),"journal_mode"===e.toLowerCase())if(s&&!["off","memory","delete","wal"].includes(s.toLowerCase()))throw new Error('journal_mode must be "off", "memory", "delete", or "wal"')}}catch(e){return this.lastError=e,H}return m}jGetLastError(e){if(this.lastError){console.error(this.lastError);const s=e.subarray(0,e.byteLength-1),{written:t}=(new TextEncoder).encodeInto(this.lastError.message,s);e[t]=0}return i}async#s(e){const s=new L(e),t=await this.options.getRoot(),a=`/${(await t.resolve(e)).join("/")}`;s.handleRequestChannel=new BroadcastChannel(`ahp:${this.options.prefix}${a}`),this.persistentFiles.set(a,s);return(await e.getFile()).size&&this.accessiblePaths.add(a),s}#t(e){return console.assert(!e.persistentFile.handleLockReleaser),e.persistentFile.isRequestInProgress?Promise.resolve():(e.persistentFile.isRequestInProgress=!0,this._module.retryOps.push((async()=>{e.persistentFile.handleLockReleaser=await this.#r(e.persistentFile);try{this.log?.(`creating access handles for ${e.path}`);const s=performance.now()+5e3;for(;;){const t=[],a=(await Promise.allSettled(R.map(async s=>{const a=this.persistentFiles.get(e.path+s);a&&(a.accessHandle=await a.fileHandle.createSyncAccessHandle(),t.push(()=>{a.accessHandle.close(),a.accessHandle=null}))}))).find(e=>"rejected"===e.status);if(!a)break;if(!y.has(a.reason?.name)||performance.now()>=s)throw a.reason;this.log?.(`access handles held for ${e.path}, retrying`);for(const e of t)e();await new Promise(e=>setTimeout(e,10))}}catch(s){throw this.log?.(`failed to create access handles for ${e.path}`,s),this.#a(e),s}finally{e.persistentFile.isRequestInProgress=!1}})()),this._module.retryOps.at(-1))}#a(e){R.forEach(s=>{const t=this.persistentFiles.get(e.path+s);t&&(t.accessHandle?.close(),t.accessHandle=null)}),this.log?.(`access handles closed for ${e.path}`),e.persistentFile.handleLockReleaser?.(),e.persistentFile.handleLockReleaser=null,this.log?.(`lock released for ${e.path}`)}#r(e){return new Promise(s=>{const t=e.handleRequestChannel.name,a=()=>{this.log?.(`notifying for ${t}`),e.handleRequestChannel.postMessage(null)},r=setInterval(a,1e3);setTimeout(a),this.log?.(`lock requested: ${t}`),navigator.locks.request(t,e=>(this.log?.(`lock acquired: ${t}`,e),clearInterval(r),new Promise(s)))})}}function q(e,s){const t=e.getUint32(s,!0);if(t){const s=new Uint8Array(e.buffer,t);return(new TextDecoder).decode(s.subarray(0,s.indexOf(0)))}return null}export{A as OPFSCoopSyncVFS};
2
- //# sourceMappingURL=OPFSCoopSyncVFS-CDNBPKfy.js.map
1
+ import{F as e}from"./FacadeVFS-d1ZDvud7.js";import{r as s,f as t,j as a,k as r,S as i,l as n,m as l,n as c,o,p as h,q as d,t as u,u as p,v as g,w as F,e as f,B as w,D as H,d as m}from"./worker.js";const y=new Set(["NoModificationAllowedError","InvalidStateError"]),R=["","-journal","-wal"],k=new FinalizationRegistry(e=>e());class b{path;flags;accessHandle;persistentFile;constructor(e,s){this.path=e,this.flags=s}}class L{fileHandle;accessHandle=null;isLockBusy=!1;isFileLocked=!1;isRequestInProgress=!1;handleLockReleaser=null;handleRequestChannel;isHandleRequested=!1;constructor(e){this.fileHandle=e}}class A extends e{mapIdToFile=new Map;lastError=null;log=null;persistentFiles=new Map;boundAccessHandles=new Map;unboundAccessHandles=new Set;accessiblePaths=new Set;releaser=null;options={getRoot:()=>navigator.storage.getDirectory(),prefix:""};static async create(e,s,t={}){const a=new A(e,s,t);return await Promise.all([a.isReady(),a.#e(10)]),a}constructor(e,s,t={}){super(e,s),Object.assign(this.options,t)}async#e(e){const s=await this.options.getRoot();for await(const e of s.values())"directory"===e.kind&&e.name.startsWith(".ahp-")&&await navigator.locks.request(e.name,{ifAvailable:!0},async t=>{t?(this.log?.(`Deleting temporary directory ${e.name}`),await s.removeEntry(e.name,{recursive:!0}).catch(e=>{if("NotFoundError"!==e?.name)throw e})):this.log?.(`Temporary directory ${e.name} is in use`)});const t=`.ahp-${Math.random().toString(36).slice(2)}`;this.releaser=await new Promise(e=>{navigator.locks.request(t,()=>new Promise(s=>{e(s)}))}),k.register(this,this.releaser);const a=await s.getDirectoryHandle(t,{create:!0});for(let s=0;s<e;s++){const e=await a.getFileHandle(`${s}.tmp`,{create:!0}),t=await e.createSyncAccessHandle();this.unboundAccessHandles.add(t)}}jOpen(e,n,l,c){try{const o=new URL(e||Math.random().toString(36).slice(2),"file://").pathname;if(l&s){const e=this.persistentFiles.get(o);if(e?.isRequestInProgress)return t;if(!e){this.log?.(`creating persistent file for ${o}`);const e=!!(l&a);return this._module.retryOps.push((async()=>{try{let s=await this.options.getRoot();const t=o.split("/").filter(e=>e),a=t.pop();for(const a of t)s=await s.getDirectoryHandle(a,{create:e});for(const t of R){const r=await s.getFileHandle(a+t,{create:e});await this.#s(r)}const r=new b(o,l);r.persistentFile=this.persistentFiles.get(o),await this.#t(r)}catch(e){const s=new L(null);this.persistentFiles.set(o,s),this.lastError=e,console.error(e)}})()),t}if(!e.fileHandle)return this.persistentFiles.delete(o),r;if(!e.accessHandle)return this._module.retryOps.push((async()=>{const e=new b(o,l);e.persistentFile=this.persistentFiles.get(o),await this.#t(e)})()),t}if(!(this.accessiblePaths.has(o)||l&a))throw new Error(`File ${o} not found`);const h=new b(o,l);return this.mapIdToFile.set(n,h),this.persistentFiles.has(o)?h.persistentFile=this.persistentFiles.get(o):this.boundAccessHandles.has(o)?h.accessHandle=this.boundAccessHandles.get(o):this.unboundAccessHandles.size&&(h.accessHandle=this.unboundAccessHandles.values().next().value,h.accessHandle.truncate(0),this.unboundAccessHandles.delete(h.accessHandle),this.boundAccessHandles.set(o,h.accessHandle)),this.accessiblePaths.add(o),c.setInt32(0,l,!0),i}catch(e){return this.lastError=e,r}}jDelete(e,s){try{const s=new URL(e,"file://").pathname;if(this.persistentFiles.has(s)){this.persistentFiles.get(s).accessHandle.truncate(0)}else this.boundAccessHandles.get(s)?.truncate(0);return this.accessiblePaths.delete(s),i}catch(e){return this.lastError=e,n}}jAccess(e,s,t){try{const s=new URL(e,"file://").pathname;return t.setInt32(0,this.accessiblePaths.has(s)?1:0,!0),i}catch(e){return this.lastError=e,l}}jClose(e){try{const t=this.mapIdToFile.get(e);return this.mapIdToFile.delete(e),t?.flags&s?t.persistentFile?.handleLockReleaser&&this.#a(t):t?.flags&c&&(t.accessHandle.truncate(0),this.accessiblePaths.delete(t.path),this.persistentFiles.has(t.path)||(this.boundAccessHandles.delete(t.path),this.unboundAccessHandles.add(t.accessHandle))),i}catch(e){return this.lastError=e,o}}jRead(e,t,a){try{const r=this.mapIdToFile.get(e),n=(r.accessHandle||r.persistentFile.accessHandle).read(t.subarray(),{at:a});return r.flags&s&&!r.persistentFile.isFileLocked&&this.#a(r),n<t.byteLength?(t.fill(0,n),h):i}catch(e){return this.lastError=e,d}}jWrite(e,s,t){try{const a=this.mapIdToFile.get(e),r=a.accessHandle||a.persistentFile.accessHandle;if(r.write(s.subarray(),{at:t})!==s.byteLength)throw new Error("short write");return i}catch(e){return this.lastError=e,u}}jTruncate(e,s){try{const t=this.mapIdToFile.get(e);return(t.accessHandle||t.persistentFile.accessHandle).truncate(s),i}catch(e){return this.lastError=e,p}}jSync(e,s){try{const s=this.mapIdToFile.get(e);return(s.accessHandle||s.persistentFile.accessHandle).flush(),i}catch(e){return this.lastError=e,g}}jFileSize(e,s){try{const t=this.mapIdToFile.get(e),a=(t.accessHandle||t.persistentFile.accessHandle).getSize();return s.setBigInt64(0,BigInt(a),!0),i}catch(e){return this.lastError=e,F}}jLock(e,s){const a=this.mapIdToFile.get(e);return a.persistentFile.isRequestInProgress?(a.persistentFile.isLockBusy=!0,t):(a.persistentFile.isFileLocked=!0,a.persistentFile.handleLockReleaser?(a.persistentFile.isLockBusy=!1,i):(a.persistentFile.handleRequestChannel.onmessage=()=>{this.log?.(`received notification for ${a.path}`),a.persistentFile.isFileLocked?a.persistentFile.isHandleRequested=!0:this.#a(a),a.persistentFile.handleRequestChannel.onmessage=null},this.#t(a),this.log?.("returning SQLITE_BUSY"),a.persistentFile.isLockBusy=!0,t))}jUnlock(e,s){const t=this.mapIdToFile.get(e);return s===f&&(t.persistentFile.isLockBusy||(t.persistentFile.isFileLocked=!1,t.persistentFile.isHandleRequested&&setTimeout(()=>{!t.persistentFile.isFileLocked&&t.persistentFile.isHandleRequested&&(this.#a(t),t.persistentFile.isHandleRequested=!1)}))),i}jFileControl(e,s,t){try{const a=this.mapIdToFile.get(e);if(s===w){const e=q(t,4),s=q(t,8);if(this.log?.("xFileControl",a.path,"PRAGMA",e,s),"journal_mode"===e.toLowerCase())if(s&&!["off","memory","delete","wal"].includes(s.toLowerCase()))throw new Error('journal_mode must be "off", "memory", "delete", or "wal"')}}catch(e){return this.lastError=e,H}return m}jGetLastError(e){if(this.lastError){console.error(this.lastError);const s=e.subarray(0,e.byteLength-1),{written:t}=(new TextEncoder).encodeInto(this.lastError.message,s);e[t]=0}return i}async#s(e){const s=new L(e),t=await this.options.getRoot(),a=`/${(await t.resolve(e)).join("/")}`;s.handleRequestChannel=new BroadcastChannel(`ahp:${this.options.prefix}${a}`),this.persistentFiles.set(a,s);return(await e.getFile()).size&&this.accessiblePaths.add(a),s}#t(e){return console.assert(!e.persistentFile.handleLockReleaser),e.persistentFile.isRequestInProgress?Promise.resolve():(e.persistentFile.isRequestInProgress=!0,this._module.retryOps.push((async()=>{e.persistentFile.handleLockReleaser=await this.#r(e.persistentFile);try{this.log?.(`creating access handles for ${e.path}`);const s=performance.now()+5e3;for(;;){const t=[],a=(await Promise.allSettled(R.map(async s=>{const a=this.persistentFiles.get(e.path+s);a&&(a.accessHandle=await a.fileHandle.createSyncAccessHandle(),t.push(()=>{a.accessHandle.close(),a.accessHandle=null}))}))).find(e=>"rejected"===e.status);if(!a)break;if(!y.has(a.reason?.name)||performance.now()>=s)throw a.reason;this.log?.(`access handles held for ${e.path}, retrying`);for(const e of t)e();await new Promise(e=>setTimeout(e,10))}}catch(s){throw this.log?.(`failed to create access handles for ${e.path}`,s),this.#a(e),s}finally{e.persistentFile.isRequestInProgress=!1}})()),this._module.retryOps.at(-1))}#a(e){R.forEach(s=>{const t=this.persistentFiles.get(e.path+s);t&&(t.accessHandle?.close(),t.accessHandle=null)}),this.log?.(`access handles closed for ${e.path}`),e.persistentFile.handleLockReleaser?.(),e.persistentFile.handleLockReleaser=null,this.log?.(`lock released for ${e.path}`)}#r(e){return new Promise(s=>{const t=e.handleRequestChannel.name,a=()=>{this.log?.(`notifying for ${t}`),e.handleRequestChannel.postMessage(null)},r=setInterval(a,1e3);setTimeout(a),this.log?.(`lock requested: ${t}`),navigator.locks.request(t,e=>(this.log?.(`lock acquired: ${t}`,e),clearInterval(r),new Promise(s)))})}}function q(e,s){const t=e.getUint32(s,!0);if(t){const s=new Uint8Array(e.buffer,t);return(new TextDecoder).decode(s.subarray(0,s.indexOf(0)))}return null}export{A as OPFSCoopSyncVFS};
2
+ //# sourceMappingURL=OPFSCoopSyncVFS-Dujy2ZwX.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"OPFSCoopSyncVFS-CDNBPKfy.js","sources":["../../../../node_modules/.pnpm/@journeyapps+wa-sqlite@2.0.10/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"],"sourcesContent":["// Copyright 2024 Roy T. Hashimoto. All Rights Reserved.\nimport { FacadeVFS } from '../FacadeVFS.js';\nimport * as VFS from '../VFS.js';\n\nconst DEFAULT_TEMPORARY_FILES = 10;\nconst LOCK_NOTIFY_INTERVAL = 1000;\n\n// A connection terminated mid-call releases its Web Lock at once and its\n// access handles only later: from a few ms to about a second, depending on\n// the engine, the platform and what the worker was doing. The next lock\n// holder sees the file as held meanwhile, so creating its handles is\n// retried, within this bound.\nconst HELD_RETRY_TIMEOUT = 5000;\nconst HELD_RETRY_INTERVAL = 10;\n\n// What createSyncAccessHandle() throws on a file another handle holds:\n// NoModificationAllowedError in Chromium and Firefox, InvalidStateError in\n// WebKit.\nconst HELD_ERRORS = new Set(['NoModificationAllowedError', 'InvalidStateError']);\n\nconst DB_RELATED_FILE_SUFFIXES = ['', '-journal', '-wal'];\n\nconst finalizationRegistry = new FinalizationRegistry(releaser => releaser());\n\nclass File {\n /** @type {string} */ path\n /** @type {number} */ flags;\n /** @type {FileSystemSyncAccessHandle} */ accessHandle;\n\n /** @type {PersistentFile?} */ persistentFile;\n\n constructor(path, flags) {\n this.path = path;\n this.flags = flags;\n }\n}\n\nclass PersistentFile {\n /** @type {FileSystemFileHandle} */ fileHandle\n /** @type {FileSystemSyncAccessHandle} */ accessHandle = null\n\n // The following properties are for main database files.\n\n /** @type {boolean} */ isLockBusy = false;\n /** @type {boolean} */ isFileLocked = false;\n /** @type {boolean} */ isRequestInProgress = false;\n /** @type {function} */ handleLockReleaser = null;\n\n /** @type {BroadcastChannel} */ handleRequestChannel;\n /** @type {boolean} */ isHandleRequested = false;\n\n constructor(fileHandle) {\n this.fileHandle = fileHandle;\n }\n}\n\n/**\n * @typedef OPFSCoopSyncOptions\n * @property {() => Promise<FileSystemDirectoryHandle>} [getRoot] Returns the\n * directory the VFS keeps its files in. It is called each time the VFS needs\n * the directory. By default the root of the origin private file system,\n * navigator.storage.getDirectory().\n * @property {string} [prefix] Put in front of the names of the Web Locks\n * and BroadcastChannels the VFS derives from its file names. Set it when a\n * file of the same name can exist under another root of this origin, so the\n * two do not share them, and use the same prefix for every VFS instance on\n * one root. A file under the default root whose name starts with the prefix\n * still shares names with the other root. By default empty, which keeps the\n * names as they were.\n */\n\nexport class OPFSCoopSyncVFS extends FacadeVFS {\n /** @type {Map<number, File>} */ mapIdToFile = new Map();\n\n lastError = null;\n log = null; //function(...args) { console.log(`[${contextName}]`, ...args) };\n \n /** @type {Map<string, PersistentFile>} */ persistentFiles = new Map();\n /** @type {Map<string, FileSystemSyncAccessHandle>} */ boundAccessHandles = new Map();\n /** @type {Set<FileSystemSyncAccessHandle>} */ unboundAccessHandles = new Set();\n /** @type {Set<string>} */ accessiblePaths = new Set();\n releaser = null;\n\n /** @type {OPFSCoopSyncOptions} */ options = {\n getRoot: () => navigator.storage.getDirectory(),\n prefix: '',\n };\n\n /**\n * @param {string} name\n * @param {*} module\n * @param {OPFSCoopSyncOptions} [options]\n */\n static async create(name, module, options = {}) {\n const vfs = new OPFSCoopSyncVFS(name, module, options);\n await Promise.all([\n vfs.isReady(),\n vfs.#initialize(DEFAULT_TEMPORARY_FILES),\n ]);\n return vfs;\n }\n\n /**\n * @param {string} name\n * @param {*} module\n * @param {OPFSCoopSyncOptions} [options]\n */\n constructor(name, module, options = {}) {\n super(name, module);\n Object.assign(this.options, options);\n }\n\n async #initialize(nTemporaryFiles) {\n // Delete temporary directories no longer in use.\n const root = await this.options.getRoot();\n // @ts-ignore\n for await (const entry of root.values()) {\n if (entry.kind === 'directory' && entry.name.startsWith('.ahp-')) {\n // A lock with the same name as the directory protects it from\n // being deleted.\n await navigator.locks.request(entry.name, { ifAvailable: true }, async lock => {\n if (lock) {\n this.log?.(`Deleting temporary directory ${entry.name}`);\n // Another instance initializing at the same time may have\n // deleted it between our listing and our lock.\n await root.removeEntry(entry.name, { recursive: true }).catch(e => {\n if (e?.name !== 'NotFoundError') throw e;\n });\n } else {\n this.log?.(`Temporary directory ${entry.name} is in use`);\n }\n });\n }\n }\n\n // Create our temporary directory.\n const tmpDirName = `.ahp-${Math.random().toString(36).slice(2)}`;\n this.releaser = await new Promise(resolve => {\n navigator.locks.request(tmpDirName, () => {\n return new Promise(release => {\n resolve(release);\n });\n });\n });\n finalizationRegistry.register(this, this.releaser);\n const tmpDir = await root.getDirectoryHandle(tmpDirName, { create: true });\n\n // Populate temporary directory.\n for (let i = 0; i < nTemporaryFiles; i++) {\n const tmpFile = await tmpDir.getFileHandle(`${i}.tmp`, { create: true });\n const tmpAccessHandle = await tmpFile.createSyncAccessHandle();\n this.unboundAccessHandles.add(tmpAccessHandle);\n }\n }\n\n /**\n * @param {string?} zName \n * @param {number} fileId \n * @param {number} flags \n * @param {DataView} pOutFlags \n * @returns {number}\n */\n jOpen(zName, fileId, flags, pOutFlags) {\n try {\n const url = new URL(zName || Math.random().toString(36).slice(2), 'file://');\n const path = url.pathname;\n\n if (flags & VFS.SQLITE_OPEN_MAIN_DB) {\n const persistentFile = this.persistentFiles.get(path);\n if (persistentFile?.isRequestInProgress) {\n // Should not reach here unless SQLite itself retries an open.\n // Otherwise, asynchronous operations started on a previous\n // open try should have completed.\n return VFS.SQLITE_BUSY;\n } else if (!persistentFile) {\n // This is the usual starting point for opening a database.\n // Register a Promise that resolves when the database and related\n // files are ready to be used.\n this.log?.(`creating persistent file for ${path}`);\n const create = !!(flags & VFS.SQLITE_OPEN_CREATE);\n this._module.retryOps.push((async () => {\n try {\n // Get the path directory handle.\n let dirHandle = await this.options.getRoot();\n const directories = path.split('/').filter(d => d);\n const filename = directories.pop();\n for (const directory of directories) {\n dirHandle = await dirHandle.getDirectoryHandle(directory, { create });\n }\n\n // Get file handles for the database and related files,\n // and create persistent file instances.\n for (const suffix of DB_RELATED_FILE_SUFFIXES) {\n const fileHandle = await dirHandle.getFileHandle(filename + suffix, { create });\n await this.#createPersistentFile(fileHandle);\n }\n\n // Get access handles for the files.\n const file = new File(path, flags);\n file.persistentFile = this.persistentFiles.get(path);\n await this.#requestAccessHandle(file);\n } catch (e) {\n // Use an invalid persistent file to signal this error\n // for the retried open.\n const persistentFile = new PersistentFile(null);\n this.persistentFiles.set(path, persistentFile);\n\n // Carry the cause to the retried open, which reports\n // SQLITE_CANTOPEN from a branch that has no error of its own.\n // Every other error return of this VFS records its cause here\n // first, so without this one a caller cannot tell a file held\n // by another context from a file that is not there - and\n // xGetLastError may still be holding an older error.\n this.lastError = e;\n console.error(e);\n }\n })());\n return VFS.SQLITE_BUSY;\n } else if (!persistentFile.fileHandle) {\n // The asynchronous open operation failed.\n this.persistentFiles.delete(path);\n return VFS.SQLITE_CANTOPEN;\n } else if (!persistentFile.accessHandle) {\n // This branch is reached if the database was previously opened\n // and closed.\n this._module.retryOps.push((async () => {\n const file = new File(path, flags);\n file.persistentFile = this.persistentFiles.get(path);\n await this.#requestAccessHandle(file);\n })());\n return VFS.SQLITE_BUSY;\n }\n }\n\n if (!this.accessiblePaths.has(path) &&\n !(flags & VFS.SQLITE_OPEN_CREATE)) {\n throw new Error(`File ${path} not found`);\n }\n\n const file = new File(path, flags);\n this.mapIdToFile.set(fileId, file);\n\n if (this.persistentFiles.has(path)) {\n file.persistentFile = this.persistentFiles.get(path);\n } else if (this.boundAccessHandles.has(path)) {\n // This temporary file was previously created and closed. Reopen\n // the same access handle.\n file.accessHandle = this.boundAccessHandles.get(path);\n } else if (this.unboundAccessHandles.size) {\n // Associate an unbound access handle to this file.\n file.accessHandle = this.unboundAccessHandles.values().next().value;\n file.accessHandle.truncate(0);\n this.unboundAccessHandles.delete(file.accessHandle);\n this.boundAccessHandles.set(path, file.accessHandle);\n }\n this.accessiblePaths.add(path);\n \n pOutFlags.setInt32(0, flags, true);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_CANTOPEN;\n }\n }\n\n /**\n * @param {string} zName \n * @param {number} syncDir \n * @returns {number}\n */\n jDelete(zName, syncDir) {\n try {\n const url = new URL(zName, 'file://');\n const path = url.pathname;\n if (this.persistentFiles.has(path)) {\n const persistentFile = this.persistentFiles.get(path);\n persistentFile.accessHandle.truncate(0);\n } else {\n this.boundAccessHandles.get(path)?.truncate(0);\n }\n this.accessiblePaths.delete(path);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_DELETE;\n }\n }\n\n /**\n * @param {string} zName \n * @param {number} flags \n * @param {DataView} pResOut \n * @returns {number}\n */\n jAccess(zName, flags, pResOut) {\n try {\n const url = new URL(zName, 'file://');\n const path = url.pathname;\n pResOut.setInt32(0, this.accessiblePaths.has(path) ? 1 : 0, true);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_ACCESS;\n } \n }\n\n /**\n * @param {number} fileId \n * @returns {number}\n */\n jClose(fileId) {\n try {\n const file = this.mapIdToFile.get(fileId);\n this.mapIdToFile.delete(fileId);\n\n if (file?.flags & VFS.SQLITE_OPEN_MAIN_DB) {\n if (file.persistentFile?.handleLockReleaser) {\n this.#releaseAccessHandle(file);\n }\n } else if (file?.flags & VFS.SQLITE_OPEN_DELETEONCLOSE) {\n file.accessHandle.truncate(0);\n this.accessiblePaths.delete(file.path);\n if (!this.persistentFiles.has(file.path)) {\n this.boundAccessHandles.delete(file.path);\n this.unboundAccessHandles.add(file.accessHandle);\n }\n }\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_CLOSE;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {Uint8Array} pData \n * @param {number} iOffset\n * @returns {number}\n */\n jRead(fileId, pData, iOffset) {\n try {\n const file = this.mapIdToFile.get(fileId);\n\n // On Chrome (at least), passing pData to accessHandle.read() is\n // an error because pData is a Proxy of a Uint8Array. Calling\n // subarray() produces a real Uint8Array and that works.\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n const bytesRead = accessHandle.read(pData.subarray(), { at: iOffset });\n\n // Opening a database file performs one read without a xLock call.\n if ((file.flags & VFS.SQLITE_OPEN_MAIN_DB) && !file.persistentFile.isFileLocked) {\n this.#releaseAccessHandle(file);\n }\n\n if (bytesRead < pData.byteLength) {\n pData.fill(0, bytesRead);\n return VFS.SQLITE_IOERR_SHORT_READ;\n }\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_READ;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {Uint8Array} pData \n * @param {number} iOffset\n * @returns {number}\n */\n jWrite(fileId, pData, iOffset) {\n try {\n const file = this.mapIdToFile.get(fileId);\n\n // On Chrome (at least), passing pData to accessHandle.write() is\n // an error because pData is a Proxy of a Uint8Array. Calling\n // subarray() produces a real Uint8Array and that works.\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n const nBytes = accessHandle.write(pData.subarray(), { at: iOffset });\n if (nBytes !== pData.byteLength) throw new Error('short write');\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_WRITE;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {number} iSize \n * @returns {number}\n */\n jTruncate(fileId, iSize) {\n try {\n const file = this.mapIdToFile.get(fileId);\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n accessHandle.truncate(iSize);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_TRUNCATE;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {number} flags \n * @returns {number}\n */\n jSync(fileId, flags) {\n try {\n const file = this.mapIdToFile.get(fileId);\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n accessHandle.flush();\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_FSYNC;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {DataView} pSize64 \n * @returns {number}\n */\n jFileSize(fileId, pSize64) {\n try {\n const file = this.mapIdToFile.get(fileId);\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n const size = accessHandle.getSize();\n pSize64.setBigInt64(0, BigInt(size), true);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_FSTAT;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {number} lockType \n * @returns {number}\n */\n jLock(fileId, lockType) {\n const file = this.mapIdToFile.get(fileId);\n if (file.persistentFile.isRequestInProgress) {\n file.persistentFile.isLockBusy = true;\n return VFS.SQLITE_BUSY;\n }\n\n file.persistentFile.isFileLocked = true;\n if (!file.persistentFile.handleLockReleaser) {\n // Start listening for notifications from other connections.\n // This is before we actually get access handles, but waiting to\n // listen until then allows a race condition where notifications\n // are missed. \n file.persistentFile.handleRequestChannel.onmessage = () => {\n this.log?.(`received notification for ${file.path}`);\n if (file.persistentFile.isFileLocked) {\n // We're still using the access handle, so mark it to be\n // released when we're done.\n file.persistentFile.isHandleRequested = true;\n } else {\n // Release the access handles immediately.\n this.#releaseAccessHandle(file);\n }\n file.persistentFile.handleRequestChannel.onmessage = null;\n };\n\n this.#requestAccessHandle(file);\n this.log?.('returning SQLITE_BUSY');\n file.persistentFile.isLockBusy = true;\n return VFS.SQLITE_BUSY;\n }\n file.persistentFile.isLockBusy = false;\n return VFS.SQLITE_OK;\n }\n\n /**\n * @param {number} fileId \n * @param {number} lockType \n * @returns {number}\n */\n jUnlock(fileId, lockType) {\n const file = this.mapIdToFile.get(fileId);\n if (lockType === VFS.SQLITE_LOCK_NONE) {\n // Don't change any state if this unlock is because xLock returned\n // SQLITE_BUSY.\n if (!file.persistentFile.isLockBusy) {\n file.persistentFile.isFileLocked = false;\n if (file.persistentFile.isHandleRequested) {\n // Another connection wants the access handle. Hand it over only\n // once the current call has returned: SQLite can lock again within\n // the same call (re-preparing a statement whose schema changed, or\n // a function running statements of its own), and that lock would\n // find the handle gone and return SQLITE_BUSY to a call that\n // retry() has already tried twice. A task rather than a microtask:\n // the JSPI build suspends at every VFS call, which runs microtasks\n // in the middle of the call.\n setTimeout(() => {\n if (!file.persistentFile.isFileLocked &&\n file.persistentFile.isHandleRequested) {\n this.#releaseAccessHandle(file);\n file.persistentFile.isHandleRequested = false;\n }\n });\n }\n }\n }\n return VFS.SQLITE_OK;\n }\n \n /**\n * @param {number} fileId\n * @param {number} op\n * @param {DataView} pArg\n * @returns {number|Promise<number>}\n */\n jFileControl(fileId, op, pArg) {\n try {\n const file = this.mapIdToFile.get(fileId);\n switch (op) {\n case VFS.SQLITE_FCNTL_PRAGMA:\n const key = extractString(pArg, 4);\n const value = extractString(pArg, 8);\n this.log?.('xFileControl', file.path, 'PRAGMA', key, value);\n switch (key.toLowerCase()) {\n case 'journal_mode':\n if (value &&\n !['off', 'memory', 'delete', 'wal'].includes(value.toLowerCase())) {\n throw new Error('journal_mode must be \"off\", \"memory\", \"delete\", or \"wal\"');\n }\n break;\n }\n break;\n }\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR;\n }\n return VFS.SQLITE_NOTFOUND;\n }\n\n /**\n * @param {Uint8Array} zBuf \n * @returns \n */\n jGetLastError(zBuf) {\n if (this.lastError) {\n console.error(this.lastError);\n const outputArray = zBuf.subarray(0, zBuf.byteLength - 1);\n const { written } = new TextEncoder().encodeInto(this.lastError.message, outputArray);\n zBuf[written] = 0;\n }\n return VFS.SQLITE_OK\n }\n\n /**\n * @param {FileSystemFileHandle} fileHandle \n * @returns {Promise<PersistentFile>}\n */\n async #createPersistentFile(fileHandle) {\n const persistentFile = new PersistentFile(fileHandle);\n const root = await this.options.getRoot();\n const relativePath = await root.resolve(fileHandle);\n const path = `/${relativePath.join('/')}`;\n // Also the name of the lock that grants the access handle.\n persistentFile.handleRequestChannel =\n new BroadcastChannel(`ahp:${this.options.prefix}${path}`);\n this.persistentFiles.set(path, persistentFile);\n\n const f = await fileHandle.getFile();\n if (f.size) {\n this.accessiblePaths.add(path);\n }\n return persistentFile;\n }\n\n /**\n * @param {File} file \n */\n #requestAccessHandle(file) {\n console.assert(!file.persistentFile.handleLockReleaser);\n if (!file.persistentFile.isRequestInProgress) {\n file.persistentFile.isRequestInProgress = true;\n this._module.retryOps.push((async () => {\n // Acquire the Web Lock.\n file.persistentFile.handleLockReleaser = await this.#acquireLock(file.persistentFile);\n try {\n // Get access handles for the database and releated files in parallel.\n this.log?.(`creating access handles for ${file.path}`)\n // Settle them all before reporting a failure: Promise.all rejects as\n // soon as one does, while the others are still in flight, so the\n // cleanup in the catch below runs too early to see them. Those\n // acquisitions then complete and assign to persistent files nothing\n // will close, leaking one access handle per attempt - which makes\n // every later open of the same database fail on a sidecar file it\n // holds itself.\n const deadline = performance.now() + HELD_RETRY_TIMEOUT;\n while (true) {\n const onError = [];\n const results = await Promise.allSettled(\n DB_RELATED_FILE_SUFFIXES.map(async suffix => {\n const persistentFile = this.persistentFiles.get(file.path + suffix);\n if (persistentFile) {\n persistentFile.accessHandle =\n await persistentFile.fileHandle.createSyncAccessHandle();\n onError.push(() => {\n persistentFile.accessHandle.close();\n persistentFile.accessHandle = null;\n });\n }\n }));\n const failure = results.find(\n /** @type {(result: PromiseSettledResult<void>) => result is PromiseRejectedResult} */\n (result => result.status === 'rejected'));\n if (!failure) break;\n if (!HELD_ERRORS.has(failure.reason?.name) || performance.now() >= deadline) {\n throw failure.reason;\n }\n\n // Still held by a connection that let go of the lock. Close what\n // this attempt did get, keep the lock, and try again.\n this.log?.(`access handles held for ${file.path}, retrying`);\n for (const f of onError) f();\n await new Promise(resolve => setTimeout(resolve, HELD_RETRY_INTERVAL));\n }\n } catch (e) {\n this.log?.(`failed to create access handles for ${file.path}`, e);\n // Close any of the potentially opened access handles\n this.#releaseAccessHandle(file);\n throw e;\n } finally {\n file.persistentFile.isRequestInProgress = false;\n }\n })());\n return this._module.retryOps.at(-1);\n }\n return Promise.resolve();\n }\n\n /**\n * @param {File} file \n */\n #releaseAccessHandle(file) {\n DB_RELATED_FILE_SUFFIXES.forEach(suffix => {\n const persistentFile = this.persistentFiles.get(file.path + suffix);\n if (persistentFile) {\n persistentFile.accessHandle?.close();\n persistentFile.accessHandle = null;\n }\n });\n this.log?.(`access handles closed for ${file.path}`)\n\n file.persistentFile.handleLockReleaser?.();\n file.persistentFile.handleLockReleaser = null;\n this.log?.(`lock released for ${file.path}`)\n }\n\n /**\n * @param {PersistentFile} persistentFile \n * @returns {Promise<function>} lock releaser\n */\n #acquireLock(persistentFile) {\n return new Promise(resolve => {\n // Tell other connections we want the access handle.\n const lockName = persistentFile.handleRequestChannel.name;\n const notify = () => {\n this.log?.(`notifying for ${lockName}`);\n persistentFile.handleRequestChannel.postMessage(null);\n }\n const notifyId = setInterval(notify, LOCK_NOTIFY_INTERVAL);\n setTimeout(notify);\n\n this.log?.(`lock requested: ${lockName}`)\n navigator.locks.request(lockName, lock => {\n // We have the lock. Stop asking other connections for it.\n this.log?.(`lock acquired: ${lockName}`, lock);\n clearInterval(notifyId);\n return new Promise(resolve);\n });\n });\n }\n}\n\nfunction extractString(dataView, offset) {\n const p = dataView.getUint32(offset, true);\n if (p) {\n const chars = new Uint8Array(dataView.buffer, p);\n return new TextDecoder().decode(chars.subarray(0, chars.indexOf(0)));\n }\n return null;\n}"],"names":["HELD_ERRORS","Set","DB_RELATED_FILE_SUFFIXES","finalizationRegistry","FinalizationRegistry","releaser","File","path","flags","accessHandle","persistentFile","constructor","this","PersistentFile","fileHandle","isLockBusy","isFileLocked","isRequestInProgress","handleLockReleaser","handleRequestChannel","isHandleRequested","OPFSCoopSyncVFS","FacadeVFS","mapIdToFile","Map","lastError","log","persistentFiles","boundAccessHandles","unboundAccessHandles","accessiblePaths","options","getRoot","navigator","storage","getDirectory","prefix","create","name","module","vfs","Promise","all","isReady","initialize","super","Object","assign","nTemporaryFiles","root","entry","values","kind","startsWith","locks","request","ifAvailable","async","lock","removeEntry","recursive","catch","e","tmpDirName","Math","random","toString","slice","resolve","release","register","tmpDir","getDirectoryHandle","i","tmpFile","getFileHandle","tmpAccessHandle","createSyncAccessHandle","add","jOpen","zName","fileId","pOutFlags","URL","pathname","VFS.SQLITE_OPEN_MAIN_DB","get","VFS.SQLITE_BUSY","VFS.SQLITE_OPEN_CREATE","_module","retryOps","push","dirHandle","directories","split","filter","d","filename","pop","directory","suffix","createPersistentFile","file","requestAccessHandle","set","console","error","delete","VFS.SQLITE_CANTOPEN","has","Error","size","next","value","truncate","setInt32","VFS.SQLITE_OK","jDelete","syncDir","VFS.SQLITE_IOERR_DELETE","jAccess","pResOut","VFS.SQLITE_IOERR_ACCESS","jClose","releaseAccessHandle","VFS.SQLITE_OPEN_DELETEONCLOSE","VFS.SQLITE_IOERR_CLOSE","jRead","pData","iOffset","bytesRead","read","subarray","at","byteLength","fill","VFS.SQLITE_IOERR_SHORT_READ","VFS.SQLITE_IOERR_READ","jWrite","write","VFS.SQLITE_IOERR_WRITE","jTruncate","iSize","VFS.SQLITE_IOERR_TRUNCATE","jSync","flush","VFS.SQLITE_IOERR_FSYNC","jFileSize","pSize64","getSize","setBigInt64","BigInt","VFS.SQLITE_IOERR_FSTAT","jLock","lockType","onmessage","jUnlock","VFS.SQLITE_LOCK_NONE","setTimeout","jFileControl","op","pArg","VFS.SQLITE_FCNTL_PRAGMA","key","extractString","toLowerCase","includes","VFS.SQLITE_IOERR","VFS.SQLITE_NOTFOUND","jGetLastError","zBuf","outputArray","written","TextEncoder","encodeInto","message","join","BroadcastChannel","getFile","assert","acquireLock","deadline","performance","now","onError","failure","allSettled","map","close","find","result","status","reason","f","forEach","lockName","notify","postMessage","notifyId","setInterval","clearInterval","dataView","offset","p","getUint32","chars","Uint8Array","buffer","TextDecoder","decode","indexOf"],"mappings":"qMAIA,MAcMA,EAAc,IAAIC,IAAI,CAAC,6BAA8B,sBAErDC,EAA2B,CAAC,GAAI,WAAY,QAE5CC,EAAuB,IAAIC,qBAAqBC,GAAYA,KAElE,MAAMC,EACkBC,KACAC,MACoBC,aAEXC,eAE/B,WAAAC,CAAYJ,EAAMC,GAChBI,KAAKL,KAAOA,EACZK,KAAKJ,MAAQA,CACf,EAGF,MAAMK,EACgCC,WACML,aAAe,KAIlCM,YAAa,EACbC,cAAe,EACfC,qBAAsB,EACrBC,mBAAqB,KAEbC,qBACTC,mBAAoB,EAE3C,WAAAT,CAAYG,GACVF,KAAKE,WAAaA,CACpB,EAkBK,MAA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AMK,QAAQ,IAClE,CACA,OAAO,IACT","x_google_ignoreList":[0]}
1
+ {"version":3,"file":"OPFSCoopSyncVFS-Dujy2ZwX.js","sources":["../../../../node_modules/.pnpm/@journeyapps+wa-sqlite@2.0.10/node_modules/@journeyapps/wa-sqlite/src/examples/OPFSCoopSyncVFS.js"],"sourcesContent":["// Copyright 2024 Roy T. Hashimoto. All Rights Reserved.\nimport { FacadeVFS } from '../FacadeVFS.js';\nimport * as VFS from '../VFS.js';\n\nconst DEFAULT_TEMPORARY_FILES = 10;\nconst LOCK_NOTIFY_INTERVAL = 1000;\n\n// A connection terminated mid-call releases its Web Lock at once and its\n// access handles only later: from a few ms to about a second, depending on\n// the engine, the platform and what the worker was doing. The next lock\n// holder sees the file as held meanwhile, so creating its handles is\n// retried, within this bound.\nconst HELD_RETRY_TIMEOUT = 5000;\nconst HELD_RETRY_INTERVAL = 10;\n\n// What createSyncAccessHandle() throws on a file another handle holds:\n// NoModificationAllowedError in Chromium and Firefox, InvalidStateError in\n// WebKit.\nconst HELD_ERRORS = new Set(['NoModificationAllowedError', 'InvalidStateError']);\n\nconst DB_RELATED_FILE_SUFFIXES = ['', '-journal', '-wal'];\n\nconst finalizationRegistry = new FinalizationRegistry(releaser => releaser());\n\nclass File {\n /** @type {string} */ path\n /** @type {number} */ flags;\n /** @type {FileSystemSyncAccessHandle} */ accessHandle;\n\n /** @type {PersistentFile?} */ persistentFile;\n\n constructor(path, flags) {\n this.path = path;\n this.flags = flags;\n }\n}\n\nclass PersistentFile {\n /** @type {FileSystemFileHandle} */ fileHandle\n /** @type {FileSystemSyncAccessHandle} */ accessHandle = null\n\n // The following properties are for main database files.\n\n /** @type {boolean} */ isLockBusy = false;\n /** @type {boolean} */ isFileLocked = false;\n /** @type {boolean} */ isRequestInProgress = false;\n /** @type {function} */ handleLockReleaser = null;\n\n /** @type {BroadcastChannel} */ handleRequestChannel;\n /** @type {boolean} */ isHandleRequested = false;\n\n constructor(fileHandle) {\n this.fileHandle = fileHandle;\n }\n}\n\n/**\n * @typedef OPFSCoopSyncOptions\n * @property {() => Promise<FileSystemDirectoryHandle>} [getRoot] Returns the\n * directory the VFS keeps its files in. It is called each time the VFS needs\n * the directory. By default the root of the origin private file system,\n * navigator.storage.getDirectory().\n * @property {string} [prefix] Put in front of the names of the Web Locks\n * and BroadcastChannels the VFS derives from its file names. Set it when a\n * file of the same name can exist under another root of this origin, so the\n * two do not share them, and use the same prefix for every VFS instance on\n * one root. A file under the default root whose name starts with the prefix\n * still shares names with the other root. By default empty, which keeps the\n * names as they were.\n */\n\nexport class OPFSCoopSyncVFS extends FacadeVFS {\n /** @type {Map<number, File>} */ mapIdToFile = new Map();\n\n lastError = null;\n log = null; //function(...args) { console.log(`[${contextName}]`, ...args) };\n \n /** @type {Map<string, PersistentFile>} */ persistentFiles = new Map();\n /** @type {Map<string, FileSystemSyncAccessHandle>} */ boundAccessHandles = new Map();\n /** @type {Set<FileSystemSyncAccessHandle>} */ unboundAccessHandles = new Set();\n /** @type {Set<string>} */ accessiblePaths = new Set();\n releaser = null;\n\n /** @type {OPFSCoopSyncOptions} */ options = {\n getRoot: () => navigator.storage.getDirectory(),\n prefix: '',\n };\n\n /**\n * @param {string} name\n * @param {*} module\n * @param {OPFSCoopSyncOptions} [options]\n */\n static async create(name, module, options = {}) {\n const vfs = new OPFSCoopSyncVFS(name, module, options);\n await Promise.all([\n vfs.isReady(),\n vfs.#initialize(DEFAULT_TEMPORARY_FILES),\n ]);\n return vfs;\n }\n\n /**\n * @param {string} name\n * @param {*} module\n * @param {OPFSCoopSyncOptions} [options]\n */\n constructor(name, module, options = {}) {\n super(name, module);\n Object.assign(this.options, options);\n }\n\n async #initialize(nTemporaryFiles) {\n // Delete temporary directories no longer in use.\n const root = await this.options.getRoot();\n // @ts-ignore\n for await (const entry of root.values()) {\n if (entry.kind === 'directory' && entry.name.startsWith('.ahp-')) {\n // A lock with the same name as the directory protects it from\n // being deleted.\n await navigator.locks.request(entry.name, { ifAvailable: true }, async lock => {\n if (lock) {\n this.log?.(`Deleting temporary directory ${entry.name}`);\n // Another instance initializing at the same time may have\n // deleted it between our listing and our lock.\n await root.removeEntry(entry.name, { recursive: true }).catch(e => {\n if (e?.name !== 'NotFoundError') throw e;\n });\n } else {\n this.log?.(`Temporary directory ${entry.name} is in use`);\n }\n });\n }\n }\n\n // Create our temporary directory.\n const tmpDirName = `.ahp-${Math.random().toString(36).slice(2)}`;\n this.releaser = await new Promise(resolve => {\n navigator.locks.request(tmpDirName, () => {\n return new Promise(release => {\n resolve(release);\n });\n });\n });\n finalizationRegistry.register(this, this.releaser);\n const tmpDir = await root.getDirectoryHandle(tmpDirName, { create: true });\n\n // Populate temporary directory.\n for (let i = 0; i < nTemporaryFiles; i++) {\n const tmpFile = await tmpDir.getFileHandle(`${i}.tmp`, { create: true });\n const tmpAccessHandle = await tmpFile.createSyncAccessHandle();\n this.unboundAccessHandles.add(tmpAccessHandle);\n }\n }\n\n /**\n * @param {string?} zName \n * @param {number} fileId \n * @param {number} flags \n * @param {DataView} pOutFlags \n * @returns {number}\n */\n jOpen(zName, fileId, flags, pOutFlags) {\n try {\n const url = new URL(zName || Math.random().toString(36).slice(2), 'file://');\n const path = url.pathname;\n\n if (flags & VFS.SQLITE_OPEN_MAIN_DB) {\n const persistentFile = this.persistentFiles.get(path);\n if (persistentFile?.isRequestInProgress) {\n // Should not reach here unless SQLite itself retries an open.\n // Otherwise, asynchronous operations started on a previous\n // open try should have completed.\n return VFS.SQLITE_BUSY;\n } else if (!persistentFile) {\n // This is the usual starting point for opening a database.\n // Register a Promise that resolves when the database and related\n // files are ready to be used.\n this.log?.(`creating persistent file for ${path}`);\n const create = !!(flags & VFS.SQLITE_OPEN_CREATE);\n this._module.retryOps.push((async () => {\n try {\n // Get the path directory handle.\n let dirHandle = await this.options.getRoot();\n const directories = path.split('/').filter(d => d);\n const filename = directories.pop();\n for (const directory of directories) {\n dirHandle = await dirHandle.getDirectoryHandle(directory, { create });\n }\n\n // Get file handles for the database and related files,\n // and create persistent file instances.\n for (const suffix of DB_RELATED_FILE_SUFFIXES) {\n const fileHandle = await dirHandle.getFileHandle(filename + suffix, { create });\n await this.#createPersistentFile(fileHandle);\n }\n\n // Get access handles for the files.\n const file = new File(path, flags);\n file.persistentFile = this.persistentFiles.get(path);\n await this.#requestAccessHandle(file);\n } catch (e) {\n // Use an invalid persistent file to signal this error\n // for the retried open.\n const persistentFile = new PersistentFile(null);\n this.persistentFiles.set(path, persistentFile);\n\n // Carry the cause to the retried open, which reports\n // SQLITE_CANTOPEN from a branch that has no error of its own.\n // Every other error return of this VFS records its cause here\n // first, so without this one a caller cannot tell a file held\n // by another context from a file that is not there - and\n // xGetLastError may still be holding an older error.\n this.lastError = e;\n console.error(e);\n }\n })());\n return VFS.SQLITE_BUSY;\n } else if (!persistentFile.fileHandle) {\n // The asynchronous open operation failed.\n this.persistentFiles.delete(path);\n return VFS.SQLITE_CANTOPEN;\n } else if (!persistentFile.accessHandle) {\n // This branch is reached if the database was previously opened\n // and closed.\n this._module.retryOps.push((async () => {\n const file = new File(path, flags);\n file.persistentFile = this.persistentFiles.get(path);\n await this.#requestAccessHandle(file);\n })());\n return VFS.SQLITE_BUSY;\n }\n }\n\n if (!this.accessiblePaths.has(path) &&\n !(flags & VFS.SQLITE_OPEN_CREATE)) {\n throw new Error(`File ${path} not found`);\n }\n\n const file = new File(path, flags);\n this.mapIdToFile.set(fileId, file);\n\n if (this.persistentFiles.has(path)) {\n file.persistentFile = this.persistentFiles.get(path);\n } else if (this.boundAccessHandles.has(path)) {\n // This temporary file was previously created and closed. Reopen\n // the same access handle.\n file.accessHandle = this.boundAccessHandles.get(path);\n } else if (this.unboundAccessHandles.size) {\n // Associate an unbound access handle to this file.\n file.accessHandle = this.unboundAccessHandles.values().next().value;\n file.accessHandle.truncate(0);\n this.unboundAccessHandles.delete(file.accessHandle);\n this.boundAccessHandles.set(path, file.accessHandle);\n }\n this.accessiblePaths.add(path);\n \n pOutFlags.setInt32(0, flags, true);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_CANTOPEN;\n }\n }\n\n /**\n * @param {string} zName \n * @param {number} syncDir \n * @returns {number}\n */\n jDelete(zName, syncDir) {\n try {\n const url = new URL(zName, 'file://');\n const path = url.pathname;\n if (this.persistentFiles.has(path)) {\n const persistentFile = this.persistentFiles.get(path);\n persistentFile.accessHandle.truncate(0);\n } else {\n this.boundAccessHandles.get(path)?.truncate(0);\n }\n this.accessiblePaths.delete(path);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_DELETE;\n }\n }\n\n /**\n * @param {string} zName \n * @param {number} flags \n * @param {DataView} pResOut \n * @returns {number}\n */\n jAccess(zName, flags, pResOut) {\n try {\n const url = new URL(zName, 'file://');\n const path = url.pathname;\n pResOut.setInt32(0, this.accessiblePaths.has(path) ? 1 : 0, true);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_ACCESS;\n } \n }\n\n /**\n * @param {number} fileId \n * @returns {number}\n */\n jClose(fileId) {\n try {\n const file = this.mapIdToFile.get(fileId);\n this.mapIdToFile.delete(fileId);\n\n if (file?.flags & VFS.SQLITE_OPEN_MAIN_DB) {\n if (file.persistentFile?.handleLockReleaser) {\n this.#releaseAccessHandle(file);\n }\n } else if (file?.flags & VFS.SQLITE_OPEN_DELETEONCLOSE) {\n file.accessHandle.truncate(0);\n this.accessiblePaths.delete(file.path);\n if (!this.persistentFiles.has(file.path)) {\n this.boundAccessHandles.delete(file.path);\n this.unboundAccessHandles.add(file.accessHandle);\n }\n }\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_CLOSE;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {Uint8Array} pData \n * @param {number} iOffset\n * @returns {number}\n */\n jRead(fileId, pData, iOffset) {\n try {\n const file = this.mapIdToFile.get(fileId);\n\n // On Chrome (at least), passing pData to accessHandle.read() is\n // an error because pData is a Proxy of a Uint8Array. Calling\n // subarray() produces a real Uint8Array and that works.\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n const bytesRead = accessHandle.read(pData.subarray(), { at: iOffset });\n\n // Opening a database file performs one read without a xLock call.\n if ((file.flags & VFS.SQLITE_OPEN_MAIN_DB) && !file.persistentFile.isFileLocked) {\n this.#releaseAccessHandle(file);\n }\n\n if (bytesRead < pData.byteLength) {\n pData.fill(0, bytesRead);\n return VFS.SQLITE_IOERR_SHORT_READ;\n }\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_READ;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {Uint8Array} pData \n * @param {number} iOffset\n * @returns {number}\n */\n jWrite(fileId, pData, iOffset) {\n try {\n const file = this.mapIdToFile.get(fileId);\n\n // On Chrome (at least), passing pData to accessHandle.write() is\n // an error because pData is a Proxy of a Uint8Array. Calling\n // subarray() produces a real Uint8Array and that works.\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n const nBytes = accessHandle.write(pData.subarray(), { at: iOffset });\n if (nBytes !== pData.byteLength) throw new Error('short write');\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_WRITE;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {number} iSize \n * @returns {number}\n */\n jTruncate(fileId, iSize) {\n try {\n const file = this.mapIdToFile.get(fileId);\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n accessHandle.truncate(iSize);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_TRUNCATE;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {number} flags \n * @returns {number}\n */\n jSync(fileId, flags) {\n try {\n const file = this.mapIdToFile.get(fileId);\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n accessHandle.flush();\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_FSYNC;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {DataView} pSize64 \n * @returns {number}\n */\n jFileSize(fileId, pSize64) {\n try {\n const file = this.mapIdToFile.get(fileId);\n const accessHandle = file.accessHandle || file.persistentFile.accessHandle;\n const size = accessHandle.getSize();\n pSize64.setBigInt64(0, BigInt(size), true);\n return VFS.SQLITE_OK;\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR_FSTAT;\n }\n }\n\n /**\n * @param {number} fileId \n * @param {number} lockType \n * @returns {number}\n */\n jLock(fileId, lockType) {\n const file = this.mapIdToFile.get(fileId);\n if (file.persistentFile.isRequestInProgress) {\n file.persistentFile.isLockBusy = true;\n return VFS.SQLITE_BUSY;\n }\n\n file.persistentFile.isFileLocked = true;\n if (!file.persistentFile.handleLockReleaser) {\n // Start listening for notifications from other connections.\n // This is before we actually get access handles, but waiting to\n // listen until then allows a race condition where notifications\n // are missed. \n file.persistentFile.handleRequestChannel.onmessage = () => {\n this.log?.(`received notification for ${file.path}`);\n if (file.persistentFile.isFileLocked) {\n // We're still using the access handle, so mark it to be\n // released when we're done.\n file.persistentFile.isHandleRequested = true;\n } else {\n // Release the access handles immediately.\n this.#releaseAccessHandle(file);\n }\n file.persistentFile.handleRequestChannel.onmessage = null;\n };\n\n this.#requestAccessHandle(file);\n this.log?.('returning SQLITE_BUSY');\n file.persistentFile.isLockBusy = true;\n return VFS.SQLITE_BUSY;\n }\n file.persistentFile.isLockBusy = false;\n return VFS.SQLITE_OK;\n }\n\n /**\n * @param {number} fileId \n * @param {number} lockType \n * @returns {number}\n */\n jUnlock(fileId, lockType) {\n const file = this.mapIdToFile.get(fileId);\n if (lockType === VFS.SQLITE_LOCK_NONE) {\n // Don't change any state if this unlock is because xLock returned\n // SQLITE_BUSY.\n if (!file.persistentFile.isLockBusy) {\n file.persistentFile.isFileLocked = false;\n if (file.persistentFile.isHandleRequested) {\n // Another connection wants the access handle. Hand it over only\n // once the current call has returned: SQLite can lock again within\n // the same call (re-preparing a statement whose schema changed, or\n // a function running statements of its own), and that lock would\n // find the handle gone and return SQLITE_BUSY to a call that\n // retry() has already tried twice. A task rather than a microtask:\n // the JSPI build suspends at every VFS call, which runs microtasks\n // in the middle of the call.\n setTimeout(() => {\n if (!file.persistentFile.isFileLocked &&\n file.persistentFile.isHandleRequested) {\n this.#releaseAccessHandle(file);\n file.persistentFile.isHandleRequested = false;\n }\n });\n }\n }\n }\n return VFS.SQLITE_OK;\n }\n \n /**\n * @param {number} fileId\n * @param {number} op\n * @param {DataView} pArg\n * @returns {number|Promise<number>}\n */\n jFileControl(fileId, op, pArg) {\n try {\n const file = this.mapIdToFile.get(fileId);\n switch (op) {\n case VFS.SQLITE_FCNTL_PRAGMA:\n const key = extractString(pArg, 4);\n const value = extractString(pArg, 8);\n this.log?.('xFileControl', file.path, 'PRAGMA', key, value);\n switch (key.toLowerCase()) {\n case 'journal_mode':\n if (value &&\n !['off', 'memory', 'delete', 'wal'].includes(value.toLowerCase())) {\n throw new Error('journal_mode must be \"off\", \"memory\", \"delete\", or \"wal\"');\n }\n break;\n }\n break;\n }\n } catch (e) {\n this.lastError = e;\n return VFS.SQLITE_IOERR;\n }\n return VFS.SQLITE_NOTFOUND;\n }\n\n /**\n * @param {Uint8Array} zBuf \n * @returns \n */\n jGetLastError(zBuf) {\n if (this.lastError) {\n console.error(this.lastError);\n const outputArray = zBuf.subarray(0, zBuf.byteLength - 1);\n const { written } = new TextEncoder().encodeInto(this.lastError.message, outputArray);\n zBuf[written] = 0;\n }\n return VFS.SQLITE_OK\n }\n\n /**\n * @param {FileSystemFileHandle} fileHandle \n * @returns {Promise<PersistentFile>}\n */\n async #createPersistentFile(fileHandle) {\n const persistentFile = new PersistentFile(fileHandle);\n const root = await this.options.getRoot();\n const relativePath = await root.resolve(fileHandle);\n const path = `/${relativePath.join('/')}`;\n // Also the name of the lock that grants the access handle.\n persistentFile.handleRequestChannel =\n new BroadcastChannel(`ahp:${this.options.prefix}${path}`);\n this.persistentFiles.set(path, persistentFile);\n\n const f = await fileHandle.getFile();\n if (f.size) {\n this.accessiblePaths.add(path);\n }\n return persistentFile;\n }\n\n /**\n * @param {File} file \n */\n #requestAccessHandle(file) {\n console.assert(!file.persistentFile.handleLockReleaser);\n if (!file.persistentFile.isRequestInProgress) {\n file.persistentFile.isRequestInProgress = true;\n this._module.retryOps.push((async () => {\n // Acquire the Web Lock.\n file.persistentFile.handleLockReleaser = await this.#acquireLock(file.persistentFile);\n try {\n // Get access handles for the database and releated files in parallel.\n this.log?.(`creating access handles for ${file.path}`)\n // Settle them all before reporting a failure: Promise.all rejects as\n // soon as one does, while the others are still in flight, so the\n // cleanup in the catch below runs too early to see them. Those\n // acquisitions then complete and assign to persistent files nothing\n // will close, leaking one access handle per attempt - which makes\n // every later open of the same database fail on a sidecar file it\n // holds itself.\n const deadline = performance.now() + HELD_RETRY_TIMEOUT;\n while (true) {\n const onError = [];\n const results = await Promise.allSettled(\n DB_RELATED_FILE_SUFFIXES.map(async suffix => {\n const persistentFile = this.persistentFiles.get(file.path + suffix);\n if (persistentFile) {\n persistentFile.accessHandle =\n await persistentFile.fileHandle.createSyncAccessHandle();\n onError.push(() => {\n persistentFile.accessHandle.close();\n persistentFile.accessHandle = null;\n });\n }\n }));\n const failure = results.find(\n /** @type {(result: PromiseSettledResult<void>) => result is PromiseRejectedResult} */\n (result => result.status === 'rejected'));\n if (!failure) break;\n if (!HELD_ERRORS.has(failure.reason?.name) || performance.now() >= deadline) {\n throw failure.reason;\n }\n\n // Still held by a connection that let go of the lock. Close what\n // this attempt did get, keep the lock, and try again.\n this.log?.(`access handles held for ${file.path}, retrying`);\n for (const f of onError) f();\n await new Promise(resolve => setTimeout(resolve, HELD_RETRY_INTERVAL));\n }\n } catch (e) {\n this.log?.(`failed to create access handles for ${file.path}`, e);\n // Close any of the potentially opened access handles\n this.#releaseAccessHandle(file);\n throw e;\n } finally {\n file.persistentFile.isRequestInProgress = false;\n }\n })());\n return this._module.retryOps.at(-1);\n }\n return Promise.resolve();\n }\n\n /**\n * @param {File} file \n */\n #releaseAccessHandle(file) {\n DB_RELATED_FILE_SUFFIXES.forEach(suffix => {\n const persistentFile = this.persistentFiles.get(file.path + suffix);\n if (persistentFile) {\n persistentFile.accessHandle?.close();\n persistentFile.accessHandle = null;\n }\n });\n this.log?.(`access handles closed for ${file.path}`)\n\n file.persistentFile.handleLockReleaser?.();\n file.persistentFile.handleLockReleaser = null;\n this.log?.(`lock released for ${file.path}`)\n }\n\n /**\n * @param {PersistentFile} persistentFile \n * @returns {Promise<function>} lock releaser\n */\n #acquireLock(persistentFile) {\n return new Promise(resolve => {\n // Tell other connections we want the access handle.\n const lockName = persistentFile.handleRequestChannel.name;\n const notify = () => {\n this.log?.(`notifying for ${lockName}`);\n persistentFile.handleRequestChannel.postMessage(null);\n }\n const notifyId = setInterval(notify, LOCK_NOTIFY_INTERVAL);\n setTimeout(notify);\n\n this.log?.(`lock requested: ${lockName}`)\n navigator.locks.request(lockName, lock => {\n // We have the lock. Stop asking other connections for it.\n this.log?.(`lock acquired: ${lockName}`, lock);\n clearInterval(notifyId);\n return new Promise(resolve);\n });\n });\n }\n}\n\nfunction extractString(dataView, offset) {\n const p = dataView.getUint32(offset, true);\n if (p) {\n const chars = new Uint8Array(dataView.buffer, p);\n return new TextDecoder().decode(chars.subarray(0, chars.indexOf(0)));\n }\n return null;\n}"],"names":["HELD_ERRORS","Set","DB_RELATED_FILE_SUFFIXES","finalizationRegistry","FinalizationRegistry","releaser","File","path","flags","accessHandle","persistentFile","constructor","this","PersistentFile","fileHandle","isLockBusy","isFileLocked","isRequestInProgress","handleLockReleaser","handleRequestChannel","isHandleRequested","OPFSCoopSyncVFS","FacadeVFS","mapIdToFile","Map","lastError","log","persistentFiles","boundAccessHandles","unboundAccessHandles","accessiblePaths","options","getRoot","navigator","storage","getDirectory","prefix","create","name","module","vfs","Promise","all","isReady","initialize","super","Object","assign","nTemporaryFiles","root","entry","values","kind","startsWith","locks","request","ifAvailable","async","lock","removeEntry","recursive","catch","e","tmpDirName","Math","random","toString","slice","resolve","release","register","tmpDir","getDirectoryHandle","i","tmpFile","getFileHandle","tmpAccessHandle","createSyncAccessHandle","add","jOpen","zName","fileId","pOutFlags","URL","pathname","VFS.SQLITE_OPEN_MAIN_DB","get","VFS.SQLITE_BUSY","VFS.SQLITE_OPEN_CREATE","_module","retryOps","push","dirHandle","directories","split","filter","d","filename","pop","directory","suffix","createPersistentFile","file","requestAccessHandle","set","console","error","delete","VFS.SQLITE_CANTOPEN","has","Error","size","next","value","truncate","setInt32","VFS.SQLITE_OK","jDelete","syncDir","VFS.SQLITE_IOERR_DELETE","jAccess","pResOut","VFS.SQLITE_IOERR_ACCESS","jClose","releaseAccessHandle","VFS.SQLITE_OPEN_DELETEONCLOSE","VFS.SQLITE_IOERR_CLOSE","jRead","pData","iOffset","bytesRead","read","subarray","at","byteLength","fill","VFS.SQLITE_IOERR_SHORT_READ","VFS.SQLITE_IOERR_READ","jWrite","write","VFS.SQLITE_IOERR_WRITE","jTruncate","iSize","VFS.SQLITE_IOERR_TRUNCATE","jSync","flush","VFS.SQLITE_IOERR_FSYNC","jFileSize","pSize64","getSize","setBigInt64","BigInt","VFS.SQLITE_IOERR_FSTAT","jLock","lockType","onmessage","jUnlock","VFS.SQLITE_LOCK_NONE","setTimeout","jFileControl","op","pArg","VFS.SQLITE_FCNTL_PRAGMA","key","extractString","toLowerCase","includes","VFS.SQLITE_IOERR","VFS.SQLITE_NOTFOUND","jGetLastError","zBuf","outputArray","written","TextEncoder","encodeInto","message","join","BroadcastChannel","getFile","assert","acquireLock","deadline","performance","now","onError","failure","allSettled","map","close","find","result","status","reason","f","forEach","lockName","notify","postMessage","notifyId","setInterval","clearInterval","dataView","offset","p","getUint32","chars","Uint8Array","buffer","TextDecoder","decode","indexOf"],"mappings":"qMAIA,MAcMA,EAAc,IAAIC,IAAI,CAAC,6BAA8B,sBAErDC,EAA2B,CAAC,GAAI,WAAY,QAE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9BlK,UAAUqB,MAAMC,QAAQ4I,EAAUzI,IAEhC9C,KAAKc,MAAM,kBAAkByK,IAAYzI,GACzC8I,cAAcF,GACP,IAAI7J,QAAQ2B,MAGzB,EAGF,SAASgG,EAAcqC,EAAUC,GAC/B,MAAMC,EAAIF,EAASG,UAAUF,GAAQ,GACrC,GAAIC,EAAG,CACL,MAAME,EAAQ,IAAIC,WAAWL,EAASM,OAAQJ,GAC9C,OAAO,IAAIK,aAAcC,OAAOJ,EAAMzE,SAAS,EAAGyE,EAAMK,QAAQ,IAClE,CACA,OAAO,IACT","x_google_ignoreList":[0]}
@@ -0,0 +1,2 @@
1
+ import{F as e}from"./FacadeVFS-d1ZDvud7.js";import{MemoryVFS as t}from"./MemoryVFS-DVJL5F8j.js";import{D as s,r,k as a,S as i,G as l,l as o,p as n}from"./worker.js";class u extends e{#e=null;#t;#s=new Map;#r;constructor(e,s,r){super(e,s),this.#t=new t(`${e}-memory`,s),this.#r=r}#a(){if(null==this.#e)throw new Error("Called OPFS method while closed.");return this.#e}#i(e){return this.#a().files[e.index]}#l(e){const t=this.#s.get(e.fileId);if(null==t)return e.memory(this.#t);try{return e.opfs(this.#i(t))}catch(e){return console.error("OPFS VFS error",e),s}}jOpen(e,t,s,o){return s&r?"/database"!=e?a:(this.#s.set(t,f),i):s&l?"/database-journal"!=e?a:(this.#s.set(t,d),i):this.#t.jOpen(e,t,s,o)}jDelete(e,t){switch(e){case"/database":case"/database-journal":return o;default:return this.#t.jDelete(e,t)}}jAccess(e,t,s){switch(e){case"/database":case"/database-journal":return s.setInt32(0,1,!0),i;default:return this.#t.jAccess(e,t,s)}}jClose(e){return this.#l({fileId:e,opfs:()=>(this.#s.delete(e),i),memory:t=>t.jClose(e)})}jRead(e,t,s){return this.#l({fileId:e,opfs:e=>{const r=e.read(t.subarray(),{at:s});return r<t.byteLength?(t.fill(0,r),n):i},memory:r=>r.jRead(e,t,s)})}jWrite(e,t,s){return this.#l({fileId:e,opfs:e=>{if(e.write(t.subarray(),{at:s})!==t.byteLength)throw new Error("short write");return i},memory:r=>r.jWrite(e,t,s)})}jTruncate(e,t){return this.#l({fileId:e,opfs:e=>(e.truncate(t),i),memory:s=>s.jTruncate(e,t)})}jSync(e,t){return this.#l({fileId:e,opfs:e=>(e.flush(),i),memory:s=>s.jSync(e,t)})}jFileSize(e,t){return this.#l({fileId:e,opfs:e=>(t.setBigInt64(0,BigInt(e.getSize()),!0),i),memory:s=>s.jFileSize(e,t)})}async open(){console.assert(null==this.#e);const{dir:e,readWriteUnsafe:t}=await this.#r();this.#e=await c.open(e,t)}close(){this.#e?.close(),this.#e=null}static directoryResolver(e,t,s){const r=new URL(e,"file://");return async()=>{let e=await(s?s():navigator.storage.getDirectory());for(const t of["powersync",...r.pathname.split("/")])t.length&&(e=await e.getDirectoryHandle(t,{create:!0}));return{dir:e,readWriteUnsafe:t}}}}class c{files;constructor(e,t){this.files=[e,t]}close(){for(const e of this.files)e.close()}static async open(e,t){async function s(s){const r=await e.getFileHandle(s,{create:!0});return await(t?r.createSyncAccessHandle({mode:"readwrite-unsafe"}):r.createSyncAccessHandle())}const[r,a]=await Promise.allSettled([s("database"),s("journal")]);if("fulfilled"===r.status&&"fulfilled"===a.status)return new c(r.value,a.value);if("fulfilled"===r.status)throw r.value.close(),a.reason;throw"fulfilled"===a.status&&a.value.close(),r.reason}}const f=Object.freeze({index:0,name:"/database"}),d=Object.freeze({index:1,name:"/database-journal"});export{u as SimpleOpfsFileSystem};
2
+ //# sourceMappingURL=SimpleOpfsFileSystem-6GYD1Xui.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"SimpleOpfsFileSystem-6GYD1Xui.js","sources":["../../lib/db/adapters/wa-sqlite/SimpleOpfsFileSystem.js"],"sourcesContent":["// @ts-expect-error\nimport { FacadeVFS } from '@journeyapps/wa-sqlite/src/FacadeVFS.js';\nimport { MemoryVFS } from '@journeyapps/wa-sqlite/src/examples/MemoryVFS.js';\nimport * as VFS from '@journeyapps/wa-sqlite/src/VFS.js';\nexport class SimpleOpfsFileSystem extends FacadeVFS {\n #files = null;\n #memory;\n #openedFiles = new Map();\n #openRoot;\n constructor(name, module, openRoot) {\n super(name, module);\n this.#memory = new MemoryVFS(`${name}-memory`, module);\n this.#openRoot = openRoot;\n }\n #requireFiles() {\n if (this.#files == null) {\n throw new Error(`Called OPFS method while closed.`);\n }\n return this.#files;\n }\n #requireFile(file) {\n return this.#requireFiles().files[file.index];\n }\n #useFile(options) {\n const opened = this.#openedFiles.get(options.fileId);\n if (opened != null) {\n try {\n return options.opfs(this.#requireFile(opened));\n }\n catch (e) {\n console.error('OPFS VFS error', e);\n return VFS.SQLITE_IOERR;\n }\n }\n else {\n return options.memory(this.#memory);\n }\n }\n jOpen(zName, fileId, flags, pOutFlags) {\n if (flags & VFS.SQLITE_OPEN_MAIN_DB) {\n if (zName != '/database') {\n return VFS.SQLITE_CANTOPEN;\n }\n this.#openedFiles.set(fileId, database);\n return VFS.SQLITE_OK;\n }\n else if (flags & VFS.SQLITE_OPEN_MAIN_JOURNAL) {\n if (zName != '/database-journal') {\n return VFS.SQLITE_CANTOPEN;\n }\n this.#openedFiles.set(fileId, databaseJournal);\n return VFS.SQLITE_OK;\n }\n else {\n // We don't care about other files (like those for materialized views). Back them by the in-memory VFS.\n return this.#memory.jOpen(zName, fileId, flags, pOutFlags);\n }\n }\n jDelete(name, syncDir) {\n switch (name) {\n case '/database':\n case '/database-journal':\n // We don't support deleting files in this VFS, and use a journal mode where that is not necessary.\n return VFS.SQLITE_IOERR_DELETE;\n default:\n return this.#memory.jDelete(name, syncDir);\n }\n }\n jAccess(zName, flags, pResOut) {\n switch (zName) {\n case '/database':\n case '/database-journal':\n // These always exist\n pResOut.setInt32(0, 1, true);\n return VFS.SQLITE_OK;\n default:\n return this.#memory.jAccess(zName, flags, pResOut);\n }\n }\n jClose(fileId) {\n return this.#useFile({\n fileId,\n opfs: () => {\n this.#openedFiles.delete(fileId);\n return VFS.SQLITE_OK;\n },\n memory: (m) => m.jClose(fileId)\n });\n }\n jRead(fileId, data, iOffset) {\n return this.#useFile({\n fileId,\n opfs: (file) => {\n const bytesRead = file.read(data.subarray(), { at: iOffset });\n if (bytesRead < data.byteLength) {\n data.fill(0, bytesRead);\n return VFS.SQLITE_IOERR_SHORT_READ;\n }\n return VFS.SQLITE_OK;\n },\n memory: (m) => m.jRead(fileId, data, iOffset)\n });\n }\n jWrite(fileId, data, iOffset) {\n return this.#useFile({\n fileId,\n opfs: (file) => {\n const nBytes = file.write(data.subarray(), { at: iOffset });\n if (nBytes !== data.byteLength)\n throw new Error('short write');\n return VFS.SQLITE_OK;\n },\n memory: (m) => m.jWrite(fileId, data, iOffset)\n });\n }\n jTruncate(fileId, iSize) {\n return this.#useFile({\n fileId,\n opfs: (file) => {\n file.truncate(iSize);\n return VFS.SQLITE_OK;\n },\n memory: (m) => m.jTruncate(fileId, iSize)\n });\n }\n jSync(fileId, flags) {\n return this.#useFile({\n fileId,\n opfs: (file) => {\n file.flush();\n return VFS.SQLITE_OK;\n },\n memory: (m) => m.jSync(fileId, flags)\n });\n }\n jFileSize(fileId, pSize64) {\n return this.#useFile({\n fileId,\n opfs: (file) => {\n pSize64.setBigInt64(0, BigInt(file.getSize()), true);\n return VFS.SQLITE_OK;\n },\n memory: (m) => m.jFileSize(fileId, pSize64)\n });\n }\n /**\n * Re-opens a file system previously closed with {@link SimpleOpfsFileSystem.close}.\n */\n async open() {\n console.assert(this.#files == null);\n const { dir, readWriteUnsafe } = await this.#openRoot();\n this.#files = await OpfsFiles.open(dir, readWriteUnsafe);\n }\n /**\n * Closes the synchronous access handles kept open while this file system is active.\n *\n * This file system can be re-opened afterwards with {@link SimpleOpfsFileSystem.open}.\n */\n close() {\n this.#files?.close();\n this.#files = null;\n }\n static directoryResolver(name, readWriteUnsafe, getRoot) {\n const url = new URL(name, 'file://');\n return async () => {\n let dir = await (getRoot ? getRoot() : navigator.storage.getDirectory());\n for (const segment of ['powersync', ...url.pathname.split('/')]) {\n if (!segment.length)\n continue; // Skip initial / and empty directory names\n dir = await dir.getDirectoryHandle(segment, { create: true });\n }\n return { dir, readWriteUnsafe };\n };\n }\n}\nclass OpfsFiles {\n files;\n constructor(database, journal) {\n this.files = [database, journal];\n }\n close() {\n for (const file of this.files) {\n file.close();\n }\n }\n static async open(root, readWriteUnsafe) {\n async function open(name) {\n const handle = await root.getFileHandle(name, { create: true });\n return await (readWriteUnsafe\n ? // @ts-expect-error\n handle.createSyncAccessHandle({ mode: 'readwrite-unsafe' })\n : handle.createSyncAccessHandle());\n }\n const [database, journal] = await Promise.allSettled([open('database'), open('journal')]);\n if (database.status === 'fulfilled' && journal.status === 'fulfilled') {\n return new OpfsFiles(database.value, journal.value);\n }\n if (database.status === 'fulfilled') {\n database.value.close();\n throw journal.reason;\n }\n else if (journal.status === 'fulfilled') {\n journal.value.close();\n }\n throw database.reason;\n }\n}\nconst database = Object.freeze({ index: 0, name: '/database' });\nconst databaseJournal = Object.freeze({ index: 1, name: '/database-journal' });\n//# sourceMappingURL=SimpleOpfsFileSystem.js.map"],"names":["SimpleOpfsFileSystem","FacadeVFS","files","memory","openedFiles","Map","openRoot","constructor","name","module","super","this","MemoryVFS","requireFiles","Error","requireFile","file","index","useFile","options","opened","get","fileId","opfs","e","console","error","VFS.SQLITE_IOERR","jOpen","zName","flags","pOutFlags","VFS.SQLITE_OPEN_MAIN_DB","VFS.SQLITE_CANTOPEN","set","database","VFS.SQLITE_OK","VFS.SQLITE_OPEN_MAIN_JOURNAL","databaseJournal","jDelete","syncDir","VFS.SQLITE_IOERR_DELETE","jAccess","pResOut","setInt32","jClose","delete","m","jRead","data","iOffset","bytesRead","read","subarray","at","byteLength","fill","VFS.SQLITE_IOERR_SHORT_READ","jWrite","write","jTruncate","iSize","truncate","jSync","flush","jFileSize","pSize64","setBigInt64","BigInt","getSize","open","assert","dir","readWriteUnsafe","OpfsFiles","close","directoryResolver","getRoot","url","URL","async","navigator","storage","getDirectory","segment","pathname","split","length","getDirectoryHandle","create","journal","root","handle","getFileHandle","createSyncAccessHandle","mode","Promise","allSettled","status","value","reason","Object","freeze"],"mappings":"qKAIO,MAAMA,UAA6BC,EACtCC,GAAS,KACTC,GACAC,GAAe,IAAIC,IACnBC,GACA,WAAAC,CAAYC,EAAMC,EAAQH,GACtBI,MAAMF,EAAMC,GACZE,MAAKR,EAAU,IAAIS,EAAU,GAAGJ,WAAeC,GAC/CE,MAAKL,EAAYA,CACrB,CACA,EAAAO,GACI,GAAmB,MAAfF,MAAKT,EACL,MAAM,IAAIY,MAAM,oCAEpB,OAAOH,MAAKT,CAChB,CACA,EAAAa,CAAaC,GACT,OAAOL,MAAKE,IAAgBX,MAAMc,EAAKC,MAC3C,CACA,EAAAC,CAASC,GACL,MAAMC,EAAST,MAAKP,EAAaiB,IAAIF,EAAQG,QAC7C,GAAc,MAAVF,EAUA,OAAOD,EAAQhB,OAAOQ,MAAKR,GAT3B,IACI,OAAOgB,EAAQI,KAAKZ,MAAKI,EAAaK,GAC1C,CACA,MAAOI,GAEH,OADAC,QAAQC,MAAM,iBAAkBF,GACzBG,CACX,CAKR,CACA,KAAAC,CAAMC,EAAOP,EAAQQ,EAAOC,GACxB,OAAID,EAAQE,EACK,aAATH,EACOI,GAEXtB,MAAKP,EAAa8B,IAAIZ,EAAQa,GACvBC,GAEFN,EAAQO,EACA,qBAATR,EACOI,GAEXtB,MAAKP,EAAa8B,IAAIZ,EAAQgB,GACvBF,GAIAzB,MAAKR,EAAQyB,MAAMC,EAAOP,EAAQQ,EAAOC,EAExD,CACA,OAAAQ,CAAQ/B,EAAMgC,GACV,OAAQhC,GACJ,IAAK,YACL,IAAK,oBAED,OAAOiC,EACX,QACI,OAAO9B,MAAKR,EAAQoC,QAAQ/B,EAAMgC,GAE9C,CACA,OAAAE,CAAQb,EAAOC,EAAOa,GAClB,OAAQd,GACJ,IAAK,YACL,IAAK,oBAGD,OADAc,EAAQC,SAAS,EAAG,GAAG,GAChBR,EACX,QACI,OAAOzB,MAAKR,EAAQ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