@@ -180,6 +180,9 @@ export class SharedSyncImplementation
180180 await this . waitForReady ( ) ;
181181 // This effectively queues connect and disconnect calls. Ensuring multiple tabs' requests are synchronized
182182 return getNavigatorLocks ( ) . request ( 'shared-sync-connect' , async ( ) => {
183+ if ( ! this . dbAdapter ) {
184+ await this . openInternalDB ( ) ;
185+ }
183186 this . syncStreamClient = this . generateStreamingImplementation ( ) ;
184187 this . lastConnectOptions = options ;
185188 this . syncStreamClient . registerListener ( {
@@ -231,12 +234,7 @@ export class SharedSyncImplementation
231234 }
232235
233236 const trackedPort = this . ports [ index ] ;
234- if ( trackedPort . db ) {
235- trackedPort . db . close ( ) ;
236- }
237-
238- // Release proxy
239- trackedPort . clientProvider [ Comlink . releaseProxy ] ( ) ;
237+ // Remove from the list of active ports
240238 this . ports . splice ( index , 1 ) ;
241239
242240 /**
@@ -249,12 +247,25 @@ export class SharedSyncImplementation
249247 }
250248 } ) ;
251249
252- if ( this . dbAdapter == trackedPort . db && this . syncStreamClient ) {
253- await this . disconnect ( ) ;
254- // Ask for a new DB worker port handler
255- await this . openInternalDB ( ) ;
256- await this . connect ( this . lastConnectOptions ) ;
250+ const shouldReconnect = ! ! this . syncStreamClient ;
251+ if ( this . dbAdapter && this . dbAdapter == trackedPort . db ) {
252+ if ( shouldReconnect ) {
253+ await this . disconnect ( ) ;
254+ }
255+
256+ // Clearing the adapter will result in a new one being opened in connect
257+ this . dbAdapter = null ;
258+
259+ if ( shouldReconnect ) {
260+ await this . connect ( this . lastConnectOptions ) ;
261+ }
257262 }
263+
264+ if ( trackedPort . db ) {
265+ trackedPort . db . close ( ) ;
266+ }
267+ // Release proxy
268+ trackedPort . clientProvider [ Comlink . releaseProxy ] ( ) ;
258269 }
259270
260271 triggerCrudUpload ( ) {
@@ -334,6 +345,10 @@ export class SharedSyncImplementation
334345
335346 protected async openInternalDB ( ) {
336347 const lastClient = this . ports [ this . ports . length - 1 ] ;
348+ if ( ! lastClient ) {
349+ // Should not really happen in practice
350+ throw new Error ( `Could not open DB connection since no client is connected.` ) ;
351+ }
337352 const workerPort = await lastClient . clientProvider . getDBWorkerPort ( ) ;
338353 const remote = Comlink . wrap < OpenAsyncDatabaseConnection > ( workerPort ) ;
339354 const identifier = this . syncParams ! . dbParams . dbFilename ;
0 commit comments