@@ -7,18 +7,15 @@ import {
77} from '@powersync/common' ;
88import * as Comlink from 'comlink' ;
99import { AbstractSharedSyncClientProvider } from '../../worker/sync/AbstractSharedSyncClientProvider' ;
10- import {
11- ManualSharedSyncPayload ,
12- SharedSyncClientEvent ,
13- SharedSyncImplementation
14- } from '../../worker/sync/SharedSyncImplementation' ;
10+ import { ManualSharedSyncPayload , SharedSyncClientEvent } from '../../worker/sync/SharedSyncImplementation' ;
1511import { DEFAULT_CACHE_SIZE_KB , resolveWebSQLFlags , TemporaryStorageOption } from '../adapters/web-sql-flags' ;
1612import { WebDBAdapter } from '../adapters/WebDBAdapter' ;
1713import {
1814 WebStreamingSyncImplementation ,
1915 WebStreamingSyncImplementationOptions
2016} from './WebStreamingSyncImplementation' ;
2117import { WorkerClient } from '../../worker/sync/WorkerClient' ;
18+ import { getNavigatorLocks } from '../../shared/navigator' ;
2219
2320/**
2421 * The shared worker will trigger methods on this side of the message port
@@ -111,6 +108,7 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
111108
112109 protected isInitialized : Promise < void > ;
113110 protected dbAdapter : WebDBAdapter ;
111+ private abortOnClose = new AbortController ( ) ;
114112
115113 constructor ( options : SharedWebStreamingSyncImplementationOptions ) {
116114 super ( options ) ;
@@ -192,6 +190,19 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
192190 * This performs bi-directional method calling.
193191 */
194192 Comlink . expose ( this . clientProvider , this . messagePort ) ;
193+
194+ // Request a random lock until this client is disposed. The name of the lock is sent to the shared worker, which
195+ // will also attempt to acquire it. Since the lock is returned when the tab is closed, this allows the share worker
196+ // to free resources associated with this tab.
197+ getNavigatorLocks ( ) . request ( `tab-close-signal-${ crypto . randomUUID ( ) } ` , async ( lock ) => {
198+ if ( ! this . abortOnClose . signal . aborted ) {
199+ this . syncManager . addLockBasedCloseSignal ( lock ! . name ) ;
200+
201+ await new Promise < void > ( ( r ) => {
202+ this . abortOnClose . signal . onabort = ( ) => r ( ) ;
203+ } ) ;
204+ }
205+ } ) ;
195206 }
196207
197208 /**
@@ -238,6 +249,7 @@ export class SharedWebStreamingSyncImplementation extends WebStreamingSyncImplem
238249 } ;
239250 this . messagePort . postMessage ( closeMessagePayload ) ;
240251 } ) ;
252+ this . abortOnClose . abort ( ) ;
241253
242254 // Release the proxy
243255 this . syncManager [ Comlink . releaseProxy ] ( ) ;
0 commit comments