@firebase/data-connect 0.5.0 → 0.6.0-20260408221811

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 (42) hide show
  1. package/dist/index.cjs.js +1165 -143
  2. package/dist/index.cjs.js.map +1 -1
  3. package/dist/index.esm.js +1164 -144
  4. package/dist/index.esm.js.map +1 -1
  5. package/dist/index.node.cjs.js +1231 -190
  6. package/dist/index.node.cjs.js.map +1 -1
  7. package/dist/internal.d.ts +133 -12
  8. package/dist/node-esm/index.node.esm.js +1230 -191
  9. package/dist/node-esm/index.node.esm.js.map +1 -1
  10. package/dist/node-esm/src/api/Mutation.d.ts +2 -2
  11. package/dist/node-esm/src/api/query.d.ts +1 -1
  12. package/dist/node-esm/src/core/query/QueryManager.d.ts +22 -3
  13. package/dist/node-esm/src/network/index.d.ts +1 -1
  14. package/dist/node-esm/src/network/manager.d.ts +61 -0
  15. package/dist/node-esm/src/network/{fetch.d.ts → rest/fetch.d.ts} +9 -4
  16. package/dist/node-esm/src/network/rest/index.d.ts +18 -0
  17. package/dist/node-esm/src/network/rest/restTransport.d.ts +33 -0
  18. package/dist/node-esm/src/network/stream/streamTransport.d.ts +241 -0
  19. package/dist/node-esm/src/network/stream/websocket.d.ts +90 -0
  20. package/dist/node-esm/src/network/stream/wire.d.ts +138 -0
  21. package/dist/node-esm/src/network/transport.d.ts +179 -0
  22. package/dist/node-esm/src/util/url.d.ts +3 -1
  23. package/dist/private.d.ts +29 -7
  24. package/dist/public.d.ts +3 -1
  25. package/dist/src/api/Mutation.d.ts +2 -2
  26. package/dist/src/api/query.d.ts +1 -1
  27. package/dist/src/core/query/QueryManager.d.ts +22 -3
  28. package/dist/src/network/index.d.ts +1 -1
  29. package/dist/src/network/manager.d.ts +61 -0
  30. package/dist/src/network/{fetch.d.ts → rest/fetch.d.ts} +9 -4
  31. package/dist/src/network/rest/index.d.ts +18 -0
  32. package/dist/src/network/rest/restTransport.d.ts +33 -0
  33. package/dist/src/network/stream/streamTransport.d.ts +241 -0
  34. package/dist/src/network/stream/websocket.d.ts +90 -0
  35. package/dist/src/network/stream/wire.d.ts +138 -0
  36. package/dist/src/network/transport.d.ts +179 -0
  37. package/dist/src/util/url.d.ts +3 -1
  38. package/package.json +1 -1
  39. package/dist/node-esm/src/network/transport/index.d.ts +0 -81
  40. package/dist/node-esm/src/network/transport/rest.d.ts +0 -49
  41. package/dist/src/network/transport/index.d.ts +0 -81
  42. package/dist/src/network/transport/rest.d.ts +0 -49
@@ -136,6 +136,138 @@ const CallerSdkTypeEnum = {
136
136
  TanstackAngularCore: 'TanstackAngularCore', // Tanstack non-generated Angular SDK
137
137
  GeneratedAngular: 'GeneratedAngular' // Generated Angular SDK
138
138
  };
139
+ /**
140
+ * Constructs the value for the X-Goog-Api-Client header
141
+ * @internal
142
+ */
143
+ function getGoogApiClientValue$1(isUsingGen, callerSdkType) {
144
+ let str = 'gl-js/ fire/' + SDK_VERSION;
145
+ if (callerSdkType !== CallerSdkTypeEnum.Base &&
146
+ callerSdkType !== CallerSdkTypeEnum.Generated) {
147
+ str += ' js/' + callerSdkType.toLowerCase();
148
+ }
149
+ else if (isUsingGen || callerSdkType === CallerSdkTypeEnum.Generated) {
150
+ str += ' js/gen';
151
+ }
152
+ return str;
153
+ }
154
+ /**
155
+ * The base class for all DataConnectTransportInterface implementations. Handles common logic such as
156
+ * URL construction, auth token management, and emulator usage. Concrete transport implementations
157
+ * should extend this class and implement the abstract {@link DataConnectTransportInterface} methods.
158
+ * @internal
159
+ */
160
+ class AbstractDataConnectTransport {
161
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
162
+ this.apiKey = apiKey;
163
+ this.appId = appId;
164
+ this.authProvider = authProvider;
165
+ this.appCheckProvider = appCheckProvider;
166
+ this._isUsingGen = _isUsingGen;
167
+ this._callerSdkType = _callerSdkType;
168
+ this._host = '';
169
+ this._location = 'l';
170
+ this._connectorName = '';
171
+ this._secure = true;
172
+ this._project = 'p';
173
+ this._authToken = null;
174
+ this._appCheckToken = null;
175
+ this._lastToken = null;
176
+ this._isUsingEmulator = false;
177
+ if (transportOptions) {
178
+ if (typeof transportOptions.port === 'number') {
179
+ this._port = transportOptions.port;
180
+ }
181
+ if (typeof transportOptions.sslEnabled !== 'undefined') {
182
+ this._secure = transportOptions.sslEnabled;
183
+ }
184
+ this._host = transportOptions.host;
185
+ }
186
+ const { location, projectId: project, connector, service } = options;
187
+ if (location) {
188
+ this._location = location;
189
+ }
190
+ if (project) {
191
+ this._project = project;
192
+ }
193
+ this._serviceName = service;
194
+ if (!connector) {
195
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
196
+ }
197
+ this._connectorName = connector;
198
+ this._connectorResourcePath = `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`;
199
+ this.authProvider?.addTokenChangeListener(token => {
200
+ logDebug(`New Token Available: ${token}`);
201
+ this.onAuthTokenChanged(token);
202
+ });
203
+ this.appCheckProvider?.addTokenChangeListener(result => {
204
+ const { token } = result;
205
+ logDebug(`New App Check Token Available: ${token}`);
206
+ this._appCheckToken = token;
207
+ });
208
+ }
209
+ useEmulator(host, port, isSecure) {
210
+ this._host = host;
211
+ this._isUsingEmulator = true;
212
+ if (typeof port === 'number') {
213
+ this._port = port;
214
+ }
215
+ if (typeof isSecure !== 'undefined') {
216
+ this._secure = isSecure;
217
+ }
218
+ }
219
+ async getWithAuth(forceToken = false) {
220
+ let starterPromise = new Promise(resolve => resolve(this._authToken));
221
+ if (this.appCheckProvider) {
222
+ const appCheckToken = await this.appCheckProvider.getToken();
223
+ if (appCheckToken) {
224
+ this._appCheckToken = appCheckToken.token;
225
+ }
226
+ }
227
+ if (this.authProvider) {
228
+ starterPromise = this.authProvider
229
+ .getToken(/*forceToken=*/ forceToken)
230
+ .then(data => {
231
+ if (!data) {
232
+ return null;
233
+ }
234
+ this._authToken = data.accessToken;
235
+ return this._authToken;
236
+ });
237
+ }
238
+ else {
239
+ starterPromise = new Promise(resolve => resolve(''));
240
+ }
241
+ return starterPromise;
242
+ }
243
+ async withRetry(promiseFactory, retry = false) {
244
+ let isNewToken = false;
245
+ return this.getWithAuth(retry)
246
+ .then(res => {
247
+ isNewToken = this._lastToken !== res;
248
+ this._lastToken = res;
249
+ return res;
250
+ })
251
+ .then(promiseFactory)
252
+ .catch(err => {
253
+ // Only retry if the result is unauthorized and the last token isn't the same as the new one.
254
+ if ('code' in err &&
255
+ err.code === Code.UNAUTHORIZED &&
256
+ !retry &&
257
+ isNewToken) {
258
+ logDebug('Retrying due to unauthorized');
259
+ return this.withRetry(promiseFactory, true);
260
+ }
261
+ throw err;
262
+ });
263
+ }
264
+ _setLastToken(lastToken) {
265
+ this._lastToken = lastToken;
266
+ }
267
+ _setCallerSdkType(callerSdkType) {
268
+ this._callerSdkType = callerSdkType;
269
+ }
270
+ }
139
271
 
140
272
  /**
141
273
  * @license
@@ -153,7 +285,13 @@ const CallerSdkTypeEnum = {
153
285
  * See the License for the specific language governing permissions and
154
286
  * limitations under the License.
155
287
  */
288
+ /** The fetch implementation to be used by the {@link RESTTransport}. */
156
289
  let connectFetch = globalThis.fetch;
290
+ /**
291
+ * This function is ONLY used for testing and for ensuring compatability in environments which may
292
+ * be using a poyfill and/or bundlers. It should not be called by users of the Firebase JS SDK.
293
+ * @internal
294
+ */
157
295
  function initializeFetch(fetchImpl) {
158
296
  connectFetch = fetchImpl;
159
297
  }
@@ -200,14 +338,20 @@ async function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken,
200
338
  response = await connectFetch(url, fetchOptions);
201
339
  }
202
340
  catch (err) {
203
- throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err));
341
+ const message = err && typeof err === 'object' && 'message' in err
342
+ ? err['message']
343
+ : String(err);
344
+ throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + message);
204
345
  }
205
346
  let jsonResponse;
206
347
  try {
207
348
  jsonResponse = await response.json();
208
349
  }
209
350
  catch (e) {
210
- throw new DataConnectError(Code.OTHER, JSON.stringify(e));
351
+ const message = e && typeof e === 'object' && 'message' in e
352
+ ? e['message']
353
+ : String(e);
354
+ throw new DataConnectError(Code.OTHER, 'Failed to parse JSON response: ' + message);
211
355
  }
212
356
  const message = getErrorMessage(jsonResponse);
213
357
  if (response.status >= 400) {
@@ -215,32 +359,910 @@ async function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken,
215
359
  if (response.status === 401) {
216
360
  throw new DataConnectError(Code.UNAUTHORIZED, message);
217
361
  }
218
- throw new DataConnectError(Code.OTHER, message);
362
+ throw new DataConnectError(Code.OTHER, message);
363
+ }
364
+ if (jsonResponse.errors && jsonResponse.errors.length) {
365
+ const stringified = JSON.stringify(jsonResponse.errors);
366
+ const failureResponse = {
367
+ errors: jsonResponse.errors,
368
+ data: jsonResponse.data
369
+ };
370
+ throw new DataConnectOperationError('DataConnect error while performing request: ' + stringified, failureResponse);
371
+ }
372
+ if (!jsonResponse.extensions) {
373
+ jsonResponse.extensions = {
374
+ dataConnect: []
375
+ };
376
+ }
377
+ return jsonResponse;
378
+ }
379
+ function getErrorMessage(obj) {
380
+ if ('message' in obj && obj.message) {
381
+ return obj.message;
382
+ }
383
+ return JSON.stringify(obj);
384
+ }
385
+
386
+ /**
387
+ * @license
388
+ * Copyright 2024 Google LLC
389
+ *
390
+ * Licensed under the Apache License, Version 2.0 (the "License");
391
+ * you may not use this file except in compliance with the License.
392
+ * You may obtain a copy of the License at
393
+ *
394
+ * http://www.apache.org/licenses/LICENSE-2.0
395
+ *
396
+ * Unless required by applicable law or agreed to in writing, software
397
+ * distributed under the License is distributed on an "AS IS" BASIS,
398
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
399
+ * See the License for the specific language governing permissions and
400
+ * limitations under the License.
401
+ */
402
+ const PROD_HOST = 'firebasedataconnect.googleapis.com';
403
+ const WEBSOCKET_PATH = 'ws/google.firebase.dataconnect.v1.ConnectorStreamService';
404
+ function restUrlBuilder(projectConfig, transportOptions) {
405
+ const { connector, location, projectId: project, service } = projectConfig;
406
+ const { host, sslEnabled, port } = transportOptions;
407
+ const protocol = sslEnabled ? 'https' : 'http';
408
+ const realHost = host || PROD_HOST;
409
+ let baseUrl = `${protocol}://${realHost}`;
410
+ if (typeof port === 'number') {
411
+ baseUrl += `:${port}`;
412
+ }
413
+ else if (typeof port !== 'undefined') {
414
+ logError('Port type is of an invalid type');
415
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
416
+ }
417
+ return `${baseUrl}/v1/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
418
+ }
419
+ function websocketUrlBuilder(projectConfig, transportOptions) {
420
+ const { location } = projectConfig;
421
+ const { host, sslEnabled, port } = transportOptions;
422
+ const protocol = sslEnabled ? 'wss' : 'ws';
423
+ const realHost = host || PROD_HOST;
424
+ let baseUrl = `${protocol}://${realHost}`;
425
+ if (typeof port === 'number') {
426
+ baseUrl += `:${port}`;
427
+ }
428
+ else if (typeof port !== 'undefined') {
429
+ logError('Port type is of an invalid type');
430
+ throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
431
+ }
432
+ return `${baseUrl}/${WEBSOCKET_PATH}/Connect/locations/${location}`;
433
+ }
434
+ function addToken(url, apiKey) {
435
+ if (!apiKey) {
436
+ return url;
437
+ }
438
+ const newUrl = new URL(url);
439
+ newUrl.searchParams.append('key', apiKey);
440
+ return newUrl.toString();
441
+ }
442
+
443
+ /**
444
+ * @license
445
+ * Copyright 2024 Google LLC
446
+ *
447
+ * Licensed under the Apache License, Version 2.0 (the "License");
448
+ * you may not use this file except in compliance with the License.
449
+ * You may obtain a copy of the License at
450
+ *
451
+ * http://www.apache.org/licenses/LICENSE-2.0
452
+ *
453
+ * Unless required by applicable law or agreed to in writing, software
454
+ * distributed under the License is distributed on an "AS IS" BASIS,
455
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
456
+ * See the License for the specific language governing permissions and
457
+ * limitations under the License.
458
+ */
459
+ /**
460
+ * Fetch-based REST implementation of {@link AbstractDataConnectTransport}.
461
+ * @internal
462
+ */
463
+ class RESTTransport extends AbstractDataConnectTransport {
464
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
465
+ super(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen, _callerSdkType);
466
+ this.invokeQuery = (queryName, body) => {
467
+ const abortController = new AbortController();
468
+ // TODO(mtewani): Update to proper value
469
+ const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
470
+ name: this._connectorResourcePath,
471
+ operationName: queryName,
472
+ variables: body
473
+ }, abortController, this.appId, this._authToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator));
474
+ return withAuth;
475
+ };
476
+ this.invokeMutation = (mutationName, body) => {
477
+ const abortController = new AbortController();
478
+ const taskResult = this.withRetry(() => {
479
+ return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
480
+ name: this._connectorResourcePath,
481
+ operationName: mutationName,
482
+ variables: body
483
+ }, abortController, this.appId, this._authToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator);
484
+ });
485
+ return taskResult;
486
+ };
487
+ }
488
+ get endpointUrl() {
489
+ return restUrlBuilder({
490
+ connector: this._connectorName,
491
+ location: this._location,
492
+ projectId: this._project,
493
+ service: this._serviceName
494
+ }, {
495
+ host: this._host,
496
+ sslEnabled: this._secure,
497
+ port: this._port
498
+ });
499
+ }
500
+ invokeSubscribe(observer, queryName, body) {
501
+ throw new DataConnectError(Code.NOT_SUPPORTED, 'Subscriptions are not supported using REST!');
502
+ }
503
+ invokeUnsubscribe(queryName, body) {
504
+ throw new DataConnectError(Code.NOT_SUPPORTED, 'Unsubscriptions are not supported using REST!');
505
+ }
506
+ onAuthTokenChanged(newToken) {
507
+ this._authToken = newToken;
508
+ }
509
+ }
510
+
511
+ /**
512
+ * @license
513
+ * Copyright 2026 Google LLC
514
+ *
515
+ * Licensed under the Apache License, Version 2.0 (the "License");
516
+ * you may not use this file except in compliance with the License.
517
+ * You may obtain a copy of the License at
518
+ *
519
+ * http://www.apache.org/licenses/LICENSE-2.0
520
+ *
521
+ * Unless required by applicable law or agreed to in writing, software
522
+ * distributed under the License is distributed on an "AS IS" BASIS,
523
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
524
+ * See the License for the specific language governing permissions and
525
+ * limitations under the License.
526
+ */
527
+ /** The request id of the first request over the stream */
528
+ const FIRST_REQUEST_ID = 1;
529
+ /** Time to wait before closing an idle connection (no active subscriptions) */
530
+ const IDLE_CONNECTION_TIMEOUT_MS = 60 * 1000; // 1 minute
531
+ /**
532
+ * The base class for all {@link DataConnectStreamTransport | Stream Transport} implementations.
533
+ * Handles management of logical streams (requests), authentication, data routing to query layer, etc.
534
+ * @internal
535
+ */
536
+ class AbstractDataConnectStreamTransport extends AbstractDataConnectTransport {
537
+ constructor() {
538
+ super(...arguments);
539
+ this.pendingClose = false;
540
+ /** True if the transport is unable to connect to the server */
541
+ this.isUnableToConnect = false;
542
+ /** The request ID of the next message to be sent. Monotonically increasing sequence number. */
543
+ this.requestNumber = FIRST_REQUEST_ID;
544
+ /**
545
+ * Map of query/variables to their active execute/resume request bodies.
546
+ */
547
+ this.activeQueryExecuteRequests = new Map();
548
+ /**
549
+ * Map of mutation/variables to their active execute request bodies.
550
+ */
551
+ this.activeMutationExecuteRequests = new Map();
552
+ /**
553
+ * Map of query/variables to their active subscribe request bodies.
554
+ */
555
+ this.activeSubscribeRequests = new Map();
556
+ /**
557
+ * Map of active execution RequestIds and their corresponding Promises and resolvers.
558
+ */
559
+ this.executeRequestPromises = new Map();
560
+ /**
561
+ * Map of active subscription RequestIds and their corresponding observers.
562
+ */
563
+ this.subscribeObservers = new Map();
564
+ /** current close timeout from setTimeout(), if any */
565
+ this.closeTimeout = null;
566
+ /** has the close timeout finished? */
567
+ this.closeTimeoutFinished = false;
568
+ /**
569
+ * Tracks if the next message to be sent is the first message of the stream.
570
+ */
571
+ this.isFirstStreamMessage = true;
572
+ /**
573
+ * Tracks the last auth token sent to the server.
574
+ * Used to detect if the token has changed and needs to be resent.
575
+ */
576
+ this.lastSentAuthToken = null;
577
+ }
578
+ /** Is the stream currently waiting to close connection? */
579
+ get isPendingClose() {
580
+ return this.pendingClose;
581
+ }
582
+ /** True if there are active subscriptions on the stream */
583
+ get hasActiveSubscriptions() {
584
+ return this.activeSubscribeRequests.size > 0;
585
+ }
586
+ /** True if there are active execute or mutation requests on the stream */
587
+ get hasActiveExecuteRequests() {
588
+ return (this.activeQueryExecuteRequests.size > 0 ||
589
+ this.activeMutationExecuteRequests.size > 0);
590
+ }
591
+ /**
592
+ * Generates and returns the next request ID.
593
+ */
594
+ nextRequestId() {
595
+ return (this.requestNumber++).toString();
596
+ }
597
+ /**
598
+ * Tracks a query execution request, storing the request body and creating and storing a promise that
599
+ * will be resolved when the response is received.
600
+ * @returns The reject function and the response promise.
601
+ *
602
+ * @remarks
603
+ * This method returns a promise, but is synchronous.
604
+ */
605
+ trackQueryExecuteRequest(requestId, mapKey, executeBody) {
606
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
607
+ let resolveFn;
608
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
609
+ let rejectFn;
610
+ const responsePromise = new Promise((resolve, reject) => {
611
+ resolveFn = resolve;
612
+ rejectFn = reject;
613
+ });
614
+ const executeRequestPromise = {
615
+ responsePromise,
616
+ resolveFn: resolveFn,
617
+ rejectFn: rejectFn
618
+ };
619
+ this.activeQueryExecuteRequests.set(mapKey, executeBody);
620
+ this.executeRequestPromises.set(requestId, executeRequestPromise);
621
+ return executeRequestPromise;
622
+ }
623
+ /**
624
+ * Tracks a mutation execution request, storing the request body and creating and storing a promise
625
+ * that will be resolved when the response is received.
626
+ * @returns The reject function and the response promise.
627
+ *
628
+ * @remarks
629
+ * This method returns a promise, but is synchronous.
630
+ */
631
+ trackMutationExecuteRequest(requestId, mapKey, executeBody) {
632
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
633
+ let resolveFn;
634
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
635
+ let rejectFn;
636
+ const responsePromise = new Promise((resolve, reject) => {
637
+ resolveFn = resolve;
638
+ rejectFn = reject;
639
+ });
640
+ const executeRequestPromise = {
641
+ responsePromise,
642
+ resolveFn: resolveFn,
643
+ rejectFn: rejectFn
644
+ };
645
+ const activeRequests = this.activeMutationExecuteRequests.get(mapKey) || [];
646
+ activeRequests.push(executeBody);
647
+ this.activeMutationExecuteRequests.set(mapKey, activeRequests);
648
+ this.executeRequestPromises.set(requestId, executeRequestPromise);
649
+ return executeRequestPromise;
650
+ }
651
+ /**
652
+ * Tracks a subscribe request, storing the request body and the notification observer.
653
+ * @remarks
654
+ * This method is synchronous.
655
+ */
656
+ trackSubscribeRequest(requestId, mapKey, subscribeBody, observer) {
657
+ this.activeSubscribeRequests.set(mapKey, subscribeBody);
658
+ this.subscribeObservers.set(requestId, observer);
659
+ }
660
+ /**
661
+ * Cleans up the query execute request tracking data structures, deleting the tracked request and
662
+ * it's associated promise.
663
+ */
664
+ cleanupQueryExecuteRequest(requestId, mapKey) {
665
+ this.activeQueryExecuteRequests.delete(mapKey);
666
+ this.executeRequestPromises.delete(requestId);
667
+ }
668
+ /**
669
+ * Cleans up the mutation execute request tracking data structures, deleting the tracked request and
670
+ * it's associated promise.
671
+ */
672
+ cleanupMutationExecuteRequest(requestId, mapKey) {
673
+ const executeRequests = this.activeMutationExecuteRequests.get(mapKey);
674
+ if (executeRequests) {
675
+ const updatedRequests = executeRequests.filter(req => req.requestId !== requestId);
676
+ if (updatedRequests.length > 0) {
677
+ this.activeMutationExecuteRequests.set(mapKey, updatedRequests);
678
+ }
679
+ else {
680
+ this.activeMutationExecuteRequests.delete(mapKey);
681
+ }
682
+ }
683
+ this.executeRequestPromises.delete(requestId);
684
+ }
685
+ /**
686
+ * Cleans up the subscribe request tracking data structures, deleting the tracked request and
687
+ * it's associated promise.
688
+ */
689
+ cleanupSubscribeRequest(requestId, mapKey) {
690
+ this.activeSubscribeRequests.delete(mapKey);
691
+ this.subscribeObservers.delete(requestId);
692
+ }
693
+ /**
694
+ * Indicates whether we should include the auth token in the next message.
695
+ * Only true if there is an auth token and it is different from the last sent auth token, or this
696
+ * is the first message.
697
+ */
698
+ get shouldIncludeAuth() {
699
+ return (this.isFirstStreamMessage ||
700
+ (!!this._authToken && this._authToken !== this.lastSentAuthToken));
701
+ }
702
+ /**
703
+ * Called by the concrete transport implementation when the physical connection is ready.
704
+ */
705
+ onConnectionReady() {
706
+ this.isFirstStreamMessage = true;
707
+ this.lastSentAuthToken = null;
708
+ }
709
+ /**
710
+ * Attempt to close the connection. Will only close if there are no active requests preventing it
711
+ * from doing so.
712
+ */
713
+ async attemptClose() {
714
+ if (this.hasActiveSubscriptions || this.hasActiveExecuteRequests) {
715
+ return;
716
+ }
717
+ this.cancelClose();
718
+ await this.closeConnection();
719
+ this.onGracefulStreamClose?.();
720
+ }
721
+ /**
722
+ * Begin closing the connection. Waits for and cleans up all active requests, and waits for
723
+ * {@link IDLE_CONNECTION_TIMEOUT_MS}. This is a graceful close - it will be called when there are
724
+ * no more active subscriptions, so there's no need to cleanup.
725
+ */
726
+ prepareToCloseGracefully() {
727
+ if (this.pendingClose) {
728
+ return;
729
+ }
730
+ this.pendingClose = true;
731
+ this.closeTimeoutFinished = false;
732
+ this.closeTimeout = setTimeout(() => {
733
+ this.closeTimeoutFinished = true;
734
+ void this.attemptClose();
735
+ }, IDLE_CONNECTION_TIMEOUT_MS);
736
+ }
737
+ /**
738
+ * Cancel closing the connection.
739
+ */
740
+ cancelClose() {
741
+ if (this.closeTimeout) {
742
+ clearTimeout(this.closeTimeout);
743
+ }
744
+ this.pendingClose = false;
745
+ this.closeTimeoutFinished = false;
746
+ }
747
+ /**
748
+ * Reject all active execute promises and notify all subscribe observers with the given error.
749
+ * Clear active request tracking maps without cancelling or re-invoking any requests.
750
+ */
751
+ rejectAllActiveRequests(code, reason) {
752
+ this.activeQueryExecuteRequests.clear();
753
+ this.activeMutationExecuteRequests.clear();
754
+ this.activeSubscribeRequests.clear();
755
+ const error = new DataConnectError(code, reason);
756
+ for (const [requestId, { rejectFn }] of this.executeRequestPromises) {
757
+ this.executeRequestPromises.delete(requestId);
758
+ rejectFn(error);
759
+ }
760
+ for (const [requestId, observer] of this.subscribeObservers) {
761
+ this.subscribeObservers.delete(requestId);
762
+ observer.onDisconnect(code, reason);
763
+ }
764
+ }
765
+ /**
766
+ * Called by concrete implementations when the stream is successfully closed, gracefully or otherwise.
767
+ */
768
+ onStreamClose(code, reason) {
769
+ this.rejectAllActiveRequests(Code.OTHER, `Stream disconnected with code ${code}: ${reason}`);
770
+ }
771
+ /**
772
+ * Prepares a stream request message by adding necessary headers and metadata.
773
+ * If this is the first message on the stream, it includes the resource name, auth token, and App Check token.
774
+ * If the auth token has refreshed since the last message, it includes the new auth token.
775
+ *
776
+ * This method is called by the concrete transport implementation before sending a message.
777
+ *
778
+ * @returns the requestBody, with attached headers and initial request fields
779
+ */
780
+ prepareMessage(requestBody) {
781
+ const preparedRequestBody = { ...requestBody };
782
+ const headers = {};
783
+ if (this.appId) {
784
+ headers['x-firebase-gmpid'] = this.appId;
785
+ }
786
+ headers['X-Goog-Api-Client'] = getGoogApiClientValue$1(this._isUsingGen, this._callerSdkType);
787
+ if (this.shouldIncludeAuth && this._authToken) {
788
+ headers.authToken = this._authToken;
789
+ this.lastSentAuthToken = this._authToken;
790
+ }
791
+ if (this.isFirstStreamMessage) {
792
+ if (this._appCheckToken) {
793
+ headers.appCheckToken = this._appCheckToken;
794
+ }
795
+ preparedRequestBody.name = this._connectorResourcePath;
796
+ }
797
+ preparedRequestBody.headers = headers;
798
+ this.isFirstStreamMessage = false;
799
+ return preparedRequestBody;
800
+ }
801
+ /**
802
+ * Sends a request message to the server via the concrete implementation.
803
+ * Ensures the connection is ready and prepares the message before sending.
804
+ * @returns A promise that resolves when the request message has been sent.
805
+ */
806
+ sendRequestMessage(requestBody) {
807
+ if (this.streamIsReady) {
808
+ const prepared = this.prepareMessage(requestBody);
809
+ return this.sendMessage(prepared);
810
+ }
811
+ return this.ensureConnection().then(() => {
812
+ const prepared = this.prepareMessage(requestBody);
813
+ return this.sendMessage(prepared);
814
+ });
815
+ }
816
+ /**
817
+ * Helper to generate a consistent string key for the tracking maps.
818
+ */
819
+ getMapKey(operationName, variables) {
820
+ const sortedVariables = this.sortObjectKeys(variables);
821
+ return JSON.stringify({ operationName, variables: sortedVariables });
822
+ }
823
+ /**
824
+ * Recursively sorts the keys of an object.
825
+ */
826
+ sortObjectKeys(obj) {
827
+ if (obj === null || typeof obj !== 'object' || Array.isArray(obj)) {
828
+ return obj;
829
+ }
830
+ const sortedObj = {};
831
+ Object.keys(obj)
832
+ .sort()
833
+ .forEach(key => {
834
+ sortedObj[key] = this.sortObjectKeys(obj[key]);
835
+ });
836
+ return sortedObj;
837
+ }
838
+ /**
839
+ * @inheritdoc
840
+ * @remarks
841
+ * This method synchronously updates the request tracking data structures before sending any message.
842
+ * If any asynchronous functionality is added to this function, it MUST be done in a way that
843
+ * preserves the synchronous update of the tracking data structures before the method returns.
844
+ */
845
+ invokeQuery(queryName, variables) {
846
+ const requestId = this.nextRequestId();
847
+ const activeRequestKey = { operationName: queryName, variables };
848
+ const mapKey = this.getMapKey(queryName, variables);
849
+ const executeBody = {
850
+ requestId,
851
+ execute: activeRequestKey
852
+ };
853
+ let { responsePromise, rejectFn } = this.trackQueryExecuteRequest(requestId, mapKey, executeBody);
854
+ responsePromise = responsePromise.finally(() => {
855
+ this.cleanupQueryExecuteRequest(requestId, mapKey);
856
+ if (!this.hasActiveSubscriptions &&
857
+ !this.hasActiveExecuteRequests &&
858
+ this.closeTimeoutFinished) {
859
+ void this.attemptClose();
860
+ }
861
+ });
862
+ // asynchronous, fire and forget
863
+ this.sendRequestMessage(executeBody).catch(err => {
864
+ rejectFn(err);
865
+ });
866
+ return responsePromise;
867
+ }
868
+ /**
869
+ * @inheritdoc
870
+ * @remarks
871
+ * This method synchronously updates the request tracking data structures before sending any message.
872
+ * If any asynchronous functionality is added to this function, it MUST be done in a way that
873
+ * preserves the synchronous update of the tracking data structures before the method returns.
874
+ */
875
+ invokeMutation(mutationName, variables) {
876
+ const requestId = this.nextRequestId();
877
+ const activeRequestKey = { operationName: mutationName, variables };
878
+ const mapKey = this.getMapKey(mutationName, variables);
879
+ const executeBody = {
880
+ requestId,
881
+ execute: activeRequestKey
882
+ };
883
+ let { responsePromise, rejectFn } = this.trackMutationExecuteRequest(requestId, mapKey, executeBody);
884
+ responsePromise = responsePromise.finally(() => {
885
+ this.cleanupMutationExecuteRequest(requestId, mapKey);
886
+ if (!this.hasActiveSubscriptions &&
887
+ !this.hasActiveExecuteRequests &&
888
+ this.closeTimeoutFinished) {
889
+ void this.attemptClose();
890
+ }
891
+ });
892
+ // asynchronous, fire and forget
893
+ this.sendRequestMessage(executeBody).catch(err => {
894
+ rejectFn(err);
895
+ });
896
+ return responsePromise;
897
+ }
898
+ /**
899
+ * @inheritdoc
900
+ * @remarks
901
+ * This method synchronously updates the request tracking data structures before sending any message
902
+ * or cancelling the closing of the stream. If any asynchronous functionality is added to this function,
903
+ * it MUST be done in a way that preserves the synchronous update of the tracking data structures
904
+ * before the method returns.
905
+ */
906
+ invokeSubscribe(observer, queryName, variables) {
907
+ // if we are waiting to close the stream, cancel closing!
908
+ this.cancelClose();
909
+ const requestId = this.nextRequestId();
910
+ const activeRequestKey = { operationName: queryName, variables };
911
+ const mapKey = this.getMapKey(queryName, variables);
912
+ const subscribeBody = {
913
+ requestId,
914
+ subscribe: activeRequestKey
915
+ };
916
+ this.trackSubscribeRequest(requestId, mapKey, subscribeBody, observer);
917
+ // asynchronous, fire and forget
918
+ this.sendRequestMessage(subscribeBody).catch(err => {
919
+ observer.onError(err instanceof Error ? err : new Error(String(err)));
920
+ this.cleanupSubscribeRequest(requestId, mapKey);
921
+ if (!this.hasActiveSubscriptions) {
922
+ this.prepareToCloseGracefully();
923
+ }
924
+ });
925
+ }
926
+ /**
927
+ * @inheritdoc
928
+ * @remarks
929
+ * This method synchronously updates the request tracking data structures before sending any message.
930
+ * If any asynchronous functionality is added to this function, it MUST be done in a way that
931
+ * preserves the synchronous update of the tracking data structures before the method returns.
932
+ */
933
+ invokeUnsubscribe(queryName, variables) {
934
+ const mapKey = this.getMapKey(queryName, variables);
935
+ const subscribeRequest = this.activeSubscribeRequests.get(mapKey);
936
+ if (!subscribeRequest) {
937
+ return;
938
+ }
939
+ const requestId = subscribeRequest.requestId;
940
+ const cancelBody = {
941
+ requestId,
942
+ cancel: {}
943
+ };
944
+ this.cleanupSubscribeRequest(requestId, mapKey);
945
+ // asynchronous, fire and forget
946
+ this.sendRequestMessage(cancelBody).catch(err => {
947
+ logError(`Stream Transport failed to send unsubscribe message: ${err}`);
948
+ });
949
+ if (!this.hasActiveSubscriptions) {
950
+ this.prepareToCloseGracefully();
951
+ }
952
+ }
953
+ onAuthTokenChanged(newToken) {
954
+ const oldAuthToken = this._authToken;
955
+ this._authToken = newToken;
956
+ const oldAuthUid = this.authUid;
957
+ const newAuthUid = this.authProvider?.getAuth()?.getUid();
958
+ this.authUid = newAuthUid;
959
+ // onAuthTokenChanged gets called by the auth provider once it initializes, so we must make sure
960
+ // we don't prematurely disconnect the stream if this is the initial call.
961
+ const isInitialAuth = oldAuthUid === undefined;
962
+ if (isInitialAuth) {
963
+ return;
964
+ }
965
+ if ((oldAuthToken && newToken === null) || // user logged out
966
+ (!oldAuthUid && newAuthUid) || // user logged in
967
+ (oldAuthUid && newAuthUid !== oldAuthUid) // logged in user changed
968
+ ) {
969
+ this.rejectAllActiveRequests(Code.UNAUTHORIZED, 'Stream disconnected due to auth change.');
970
+ void this.attemptClose();
971
+ }
972
+ }
973
+ /**
974
+ * Handle a response message from the server. Called by the connection-specific implementation after
975
+ * it's transformed a message from the server into a {@link DataConnectResponse}.
976
+ * @param requestId the requestId associated with this response.
977
+ * @param response the response from the server.
978
+ */
979
+ async handleResponse(requestId, response) {
980
+ if (this.executeRequestPromises.has(requestId)) {
981
+ // don't clean up the tracking maps here, they're handled automatically when the execute promise settles
982
+ const { resolveFn, rejectFn } = this.executeRequestPromises.get(requestId);
983
+ if (response.errors && response.errors.length) {
984
+ const failureResponse = {
985
+ errors: response.errors,
986
+ data: response.data
987
+ };
988
+ const stringified = JSON.stringify(response.errors);
989
+ rejectFn(new DataConnectOperationError('DataConnect error while performing request: ' + stringified, failureResponse));
990
+ }
991
+ else {
992
+ resolveFn(response);
993
+ }
994
+ }
995
+ else if (this.subscribeObservers.has(requestId)) {
996
+ const observer = this.subscribeObservers.get(requestId);
997
+ await observer.onData(response);
998
+ }
999
+ else {
1000
+ throw new DataConnectError(Code.OTHER, `Stream response contained unrecognized requestId '${requestId}'`);
1001
+ }
1002
+ }
1003
+ }
1004
+
1005
+ /**
1006
+ * @license
1007
+ * Copyright 2026 Google LLC
1008
+ *
1009
+ * Licensed under the Apache License, Version 2.0 (the "License");
1010
+ * you may not use this file except in compliance with the License.
1011
+ * You may obtain a copy of the License at
1012
+ *
1013
+ * http://www.apache.org/licenses/LICENSE-2.0
1014
+ *
1015
+ * Unless required by applicable law or agreed to in writing, software
1016
+ * distributed under the License is distributed on an "AS IS" BASIS,
1017
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1018
+ * See the License for the specific language governing permissions and
1019
+ * limitations under the License.
1020
+ */
1021
+ /** The WebSocket implementation to be used by the {@link WebSocketTransport}. */
1022
+ let connectWebSocket = globalThis.WebSocket;
1023
+ /**
1024
+ * This function is ONLY used for testing and for ensuring compatability in environments which may
1025
+ * be using a poyfill and/or bundlers. It should not be called by users of the Firebase JS SDK.
1026
+ * @internal
1027
+ */
1028
+ function initializeWebSocket(webSocketImpl) {
1029
+ connectWebSocket = webSocketImpl;
1030
+ }
1031
+ /**
1032
+ * The code used to close the WebSocket connection.
1033
+ * This is a protocol-level code, and is not the same as the {@link Code | DataConnect error code}.
1034
+ * @internal
1035
+ */
1036
+ const WEBSOCKET_CLOSE_CODE = 1000;
1037
+ /**
1038
+ * An {@link AbstractDataConnectStreamTransport | Stream Transport} implementation that uses {@link WebSocket | WebSockets} to stream requests and responses.
1039
+ * This class handles the lifecycle of the WebSocket connection, including automatic
1040
+ * reconnection and request correlation.
1041
+ * @internal
1042
+ */
1043
+ class WebSocketTransport extends AbstractDataConnectStreamTransport {
1044
+ get endpointUrl() {
1045
+ return websocketUrlBuilder({
1046
+ connector: this._connectorName,
1047
+ location: this._location,
1048
+ projectId: this._project,
1049
+ service: this._serviceName
1050
+ }, {
1051
+ host: this._host,
1052
+ sslEnabled: this._secure,
1053
+ port: this._port
1054
+ });
1055
+ }
1056
+ /**
1057
+ * Decodes a WebSocket response from a Uint8Array to a JSON object.
1058
+ * Emulator does not send messages as Uint8Arrays, but prod does.
1059
+ */
1060
+ decodeBinaryResponse(data) {
1061
+ if (!this.decoder) {
1062
+ this.decoder = new TextDecoder('utf-8');
1063
+ }
1064
+ return this.decoder.decode(data);
1065
+ }
1066
+ get streamIsReady() {
1067
+ return this.connection?.readyState === WebSocket.OPEN;
1068
+ }
1069
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
1070
+ super(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen, _callerSdkType);
1071
+ this.apiKey = apiKey;
1072
+ this.appId = appId;
1073
+ this.authProvider = authProvider;
1074
+ this.appCheckProvider = appCheckProvider;
1075
+ this._isUsingGen = _isUsingGen;
1076
+ this._callerSdkType = _callerSdkType;
1077
+ /** Decodes binary WebSocket responses to strings */
1078
+ this.decoder = undefined;
1079
+ /** The current connection to the server. Undefined if disconnected. */
1080
+ this.connection = undefined;
1081
+ /**
1082
+ * Current connection attempt. If null, we are not currently attemping to connect (not connected,
1083
+ * or already connected). Will be resolved or rejected when the connection is opened or fails to open.
1084
+ */
1085
+ this.connectionAttempt = null;
1086
+ }
1087
+ ensureConnection() {
1088
+ try {
1089
+ if (this.streamIsReady) {
1090
+ return Promise.resolve();
1091
+ }
1092
+ if (this.connectionAttempt) {
1093
+ return this.connectionAttempt;
1094
+ }
1095
+ this.connectionAttempt = new Promise((resolve, reject) => {
1096
+ if (!connectWebSocket) {
1097
+ throw new DataConnectError(Code.OTHER, 'No WebSocket Implementation detected!');
1098
+ }
1099
+ const ws = new connectWebSocket(this.endpointUrl);
1100
+ this.connection = ws;
1101
+ this.connection.binaryType = 'arraybuffer';
1102
+ ws.onopen = () => {
1103
+ this.isUnableToConnect = false;
1104
+ this.onConnectionReady();
1105
+ resolve();
1106
+ };
1107
+ ws.onerror = event => {
1108
+ this.connectionAttempt = null;
1109
+ this.isUnableToConnect = true;
1110
+ const error = new DataConnectError(Code.OTHER, `Error using WebSocket connection, closing WebSocket`);
1111
+ this.handleError(error);
1112
+ reject(error);
1113
+ };
1114
+ ws.onmessage = ev => this.handleWebSocketMessage(ev).catch(async (reason) => {
1115
+ this.handleError(reason);
1116
+ });
1117
+ ws.onclose = ev => this.handleWebsocketDisconnect(ev);
1118
+ });
1119
+ return this.connectionAttempt;
1120
+ }
1121
+ catch (error) {
1122
+ this.handleError(error);
1123
+ throw error;
1124
+ }
1125
+ }
1126
+ openConnection() {
1127
+ return this.ensureConnection().catch(err => {
1128
+ throw new DataConnectError(Code.OTHER, `Failed to open connection: ${err}`);
1129
+ });
1130
+ }
1131
+ closeConnection(code, reason) {
1132
+ if (!this.connection) {
1133
+ this.connectionAttempt = null;
1134
+ return Promise.resolve();
1135
+ }
1136
+ let error;
1137
+ try {
1138
+ if (reason) {
1139
+ // reason string can be max 123 bytes (not characters, bytes)
1140
+ // https://developer.mozilla.org/en-US/docs/Web/API/WebSocketStream/close#parameters
1141
+ const MAX_BYTES = 123;
1142
+ const encoder = new TextEncoder();
1143
+ const bytes = encoder.encode(reason);
1144
+ if (bytes.length <= MAX_BYTES) {
1145
+ this.connection.close(code, reason);
1146
+ }
1147
+ else {
1148
+ const buf = new Uint8Array(MAX_BYTES);
1149
+ const { read } = encoder.encodeInto(reason, buf);
1150
+ const truncatedReason = reason.substring(0, read);
1151
+ this.connection.close(code, truncatedReason);
1152
+ }
1153
+ }
1154
+ else {
1155
+ this.connection.close(code);
1156
+ }
1157
+ }
1158
+ catch (e) {
1159
+ error = e;
1160
+ }
1161
+ finally {
1162
+ this.connection = undefined;
1163
+ this.connectionAttempt = null;
1164
+ }
1165
+ if (error) {
1166
+ return Promise.reject(error);
1167
+ }
1168
+ return Promise.resolve();
219
1169
  }
220
- if (jsonResponse.errors && jsonResponse.errors.length) {
221
- const stringified = JSON.stringify(jsonResponse.errors);
222
- const failureResponse = {
223
- errors: jsonResponse.errors,
224
- data: jsonResponse.data
225
- };
226
- throw new DataConnectOperationError('DataConnect error while performing request: ' + stringified, failureResponse);
1170
+ /**
1171
+ * Handle a disconnection from the server. Initiates graceful clean up and reconnection attempts.
1172
+ * @param ev the {@link CloseEvent} that closed the WebSocket.
1173
+ */
1174
+ handleWebsocketDisconnect(ev) {
1175
+ this.connection = undefined;
1176
+ this.connectionAttempt = null;
1177
+ this.onStreamClose(ev.code, ev.reason);
227
1178
  }
228
- if (!jsonResponse.extensions) {
229
- jsonResponse.extensions = {
230
- dataConnect: []
1179
+ /**
1180
+ * Handle an error that occurred on the WebSocket. Close the connection and reject all active requests.
1181
+ */
1182
+ handleError(error) {
1183
+ logError(`DataConnect WebSocket error, closing stream: ${error}`);
1184
+ let reason = error ? String(error) : 'Unknown Error';
1185
+ if (error instanceof DataConnectError) {
1186
+ reason = error.message;
1187
+ }
1188
+ void this.closeConnection(WEBSOCKET_CLOSE_CODE, reason);
1189
+ }
1190
+ sendMessage(requestBody) {
1191
+ return this.ensureConnection().then(() => {
1192
+ try {
1193
+ this.connection.send(JSON.stringify(requestBody));
1194
+ return Promise.resolve();
1195
+ }
1196
+ catch (err) {
1197
+ this.handleError(err);
1198
+ throw new DataConnectError(Code.OTHER, `Failed to send message: ${String(err)}`);
1199
+ }
1200
+ });
1201
+ }
1202
+ /**
1203
+ * Handles incoming WebSocket messages.
1204
+ * @param ev The {@link MessageEvent} from the WebSocket.
1205
+ */
1206
+ async handleWebSocketMessage(ev) {
1207
+ const result = this.parseWebSocketData(ev.data);
1208
+ const requestId = result.requestId;
1209
+ const response = {
1210
+ data: result.data,
1211
+ errors: result.errors,
1212
+ extensions: result.extensions || { dataConnect: [] }
231
1213
  };
1214
+ await this.handleResponse(requestId, response);
232
1215
  }
233
- return jsonResponse;
234
- }
235
- function getErrorMessage(obj) {
236
- if ('message' in obj && obj.message) {
237
- return obj.message;
1216
+ /**
1217
+ * Parse a response from the server. Assert that it has a {@link DataConnectStreamResponse.requestId | requestId}.
1218
+ * @param data the message from the server to be parsed
1219
+ * @returns the parsed message as a {@link DataConnectStreamResponse}
1220
+ * @throws {DataConnectError} if parsing fails or message is malformed.
1221
+ */
1222
+ parseWebSocketData(
1223
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
1224
+ data) {
1225
+ const dataIsString = typeof data === 'string';
1226
+ /** raw websocket message */
1227
+ let webSocketMessage;
1228
+ /** object containing data, errors, and extensions */
1229
+ let result;
1230
+ try {
1231
+ if (dataIsString) {
1232
+ webSocketMessage = JSON.parse(data);
1233
+ }
1234
+ else {
1235
+ webSocketMessage = JSON.parse(this.decodeBinaryResponse(data));
1236
+ }
1237
+ }
1238
+ catch (err) {
1239
+ throw new DataConnectError(Code.OTHER, `Could not parse WebSocket message: ${err instanceof Error ? err.message : String(err)}`);
1240
+ }
1241
+ if (typeof webSocketMessage !== 'object' || webSocketMessage === null) {
1242
+ throw new DataConnectError(Code.OTHER, 'WebSocket message is not an object');
1243
+ }
1244
+ if (dataIsString) {
1245
+ if (!('result' in webSocketMessage)) {
1246
+ throw new DataConnectError(Code.OTHER, 'WebSocket message from emulator did not include result');
1247
+ }
1248
+ if (typeof webSocketMessage.result !== 'object' ||
1249
+ webSocketMessage.result === null) {
1250
+ throw new DataConnectError(Code.OTHER, 'WebSocket message result is not an object');
1251
+ }
1252
+ result = webSocketMessage.result;
1253
+ }
1254
+ else {
1255
+ result = webSocketMessage;
1256
+ }
1257
+ if (!('requestId' in result)) {
1258
+ throw new DataConnectError(Code.OTHER, 'WebSocket message did not include requestId');
1259
+ }
1260
+ return result;
238
1261
  }
239
- return JSON.stringify(obj);
240
1262
  }
241
1263
 
242
1264
  const name = "@firebase/data-connect";
243
- const version = "0.5.0";
1265
+ const version = "0.6.0-20260408221811";
244
1266
 
245
1267
  /**
246
1268
  * @license
@@ -1047,6 +2069,10 @@ class QueryManager {
1047
2069
  this.dc = dc;
1048
2070
  this.cache = cache;
1049
2071
  this.callbacks = new Map();
2072
+ /**
2073
+ * Map of serialized query keys to most recent Query Result. Used as a simple fallback cache
2074
+ * for subsciptions if caching is not enabled.
2075
+ */
1050
2076
  this.subscriptionCache = new Map();
1051
2077
  this.queue = [];
1052
2078
  }
@@ -1092,7 +2118,12 @@ class QueryManager {
1092
2118
  const unsubscribe = () => {
1093
2119
  if (this.callbacks.has(key)) {
1094
2120
  const callbackList = this.callbacks.get(key);
1095
- this.callbacks.set(key, callbackList.filter(callback => callback !== subscription));
2121
+ const newList = callbackList.filter(callback => callback !== subscription);
2122
+ this.callbacks.set(key, newList);
2123
+ if (newList.length === 0) {
2124
+ this.callbacks.delete(key);
2125
+ this.transport.invokeUnsubscribe(queryRef.name, queryRef.variables);
2126
+ }
1096
2127
  onCompleteCallback?.();
1097
2128
  }
1098
2129
  };
@@ -1107,12 +2138,18 @@ class QueryManager {
1107
2138
  const promise = this.preferCacheResults(queryRef, /*allowStale=*/ true);
1108
2139
  // We want to ignore the error and let subscriptions handle it
1109
2140
  promise.then(undefined, err => { });
1110
- if (!this.callbacks.has(key)) {
1111
- this.callbacks.set(key, []);
2141
+ if (this.callbacks.has(key)) {
2142
+ this.callbacks
2143
+ .get(key)
2144
+ .push(subscription);
2145
+ }
2146
+ else {
2147
+ this.callbacks.set(key, [
2148
+ subscription
2149
+ ]);
2150
+ // only invoke subscription if we don't already have an active subscription
2151
+ this.transport.invokeSubscribe(this.makeSubscribeObserver(queryRef), queryRef.name, queryRef.variables);
1112
2152
  }
1113
- this.callbacks
1114
- .get(key)
1115
- .push(subscription);
1116
2153
  return unsubscribe;
1117
2154
  }
1118
2155
  async fetchServerResults(queryRef) {
@@ -1135,8 +2172,7 @@ class QueryManager {
1135
2172
  extensions: getDataConnectExtensionsWithoutMaxAge(originalExtensions),
1136
2173
  toJSON: getRefSerializer(queryRef, result.data, SOURCE_SERVER, fetchTime)
1137
2174
  };
1138
- let updatedKeys = [];
1139
- updatedKeys = await this.updateCache(queryResult, originalExtensions?.dataConnect);
2175
+ const updatedKeys = await this.updateCache(queryResult, originalExtensions?.dataConnect);
1140
2176
  this.publishDataToSubscribers(key, queryResult);
1141
2177
  if (this.cache) {
1142
2178
  await this.publishCacheResultsToSubscribers(updatedKeys, fetchTime);
@@ -1237,6 +2273,7 @@ class QueryManager {
1237
2273
  result.toJSON = getRefSerializer(result.ref, result.data, SOURCE_CACHE, result.fetchTime);
1238
2274
  return result;
1239
2275
  }
2276
+ /** Call the registered onNext callbacks for the given key */
1240
2277
  publishDataToSubscribers(key, queryResult) {
1241
2278
  if (!this.callbacks.has(key)) {
1242
2279
  return;
@@ -1277,6 +2314,80 @@ class QueryManager {
1277
2314
  enableEmulator(host, port) {
1278
2315
  this.transport.useEmulator(host, port);
1279
2316
  }
2317
+ /**
2318
+ * Create a new {@link SubscribeObserver} for the given QueryRef. This will be passed to
2319
+ * {@link DataConnectTransportInterface.invokeSubscribe | invokeSubscribe()} to notify the query
2320
+ * layer of data update notifications or if the stream disconnected.
2321
+ */
2322
+ makeSubscribeObserver(queryRef) {
2323
+ const key = encoderImpl({
2324
+ name: queryRef.name,
2325
+ variables: queryRef.variables,
2326
+ refType: QUERY_STR
2327
+ });
2328
+ return {
2329
+ onData: async (response) => {
2330
+ await this.handleStreamNotification(key, response, queryRef);
2331
+ },
2332
+ onDisconnect: (code, reason) => {
2333
+ this.handleStreamDisconnect(key, code, reason);
2334
+ },
2335
+ onError: error => {
2336
+ this.publishErrorToSubscribers(key, error);
2337
+ }
2338
+ };
2339
+ }
2340
+ /**
2341
+ * Handle a data update notification from the stream. Notify subscribers of results/errors, and
2342
+ * update the cache.
2343
+ */
2344
+ async handleStreamNotification(key, response, queryRef) {
2345
+ if (response.errors && response.errors.length > 0) {
2346
+ const stringified = JSON.stringify(response.errors.map(e => {
2347
+ if (e && typeof e === 'object') {
2348
+ return {
2349
+ message: e.message,
2350
+ code: e.code
2351
+ };
2352
+ }
2353
+ return e;
2354
+ }));
2355
+ const failureResponse = {
2356
+ errors: response.errors,
2357
+ data: response.data
2358
+ };
2359
+ const error = new DataConnectOperationError('DataConnect error received from subscribe notification: ' +
2360
+ stringified, failureResponse);
2361
+ this.publishErrorToSubscribers(key, error);
2362
+ return;
2363
+ }
2364
+ const fetchTime = Date.now().toString();
2365
+ const queryResult = {
2366
+ ref: queryRef,
2367
+ source: SOURCE_SERVER,
2368
+ fetchTime,
2369
+ data: response.data,
2370
+ extensions: getDataConnectExtensionsWithoutMaxAge(response.extensions),
2371
+ toJSON: getRefSerializer(queryRef, response.data, SOURCE_SERVER, fetchTime)
2372
+ };
2373
+ const updatedKeys = await this.updateCache(queryResult, response.extensions?.dataConnect);
2374
+ this.publishDataToSubscribers(key, queryResult);
2375
+ if (this.cache) {
2376
+ await this.publishCacheResultsToSubscribers(updatedKeys, fetchTime);
2377
+ }
2378
+ }
2379
+ /**
2380
+ * Handle a disconnect from the stream. Unsubscribe all callbacks for the given key.
2381
+ */
2382
+ handleStreamDisconnect(key, code, reason) {
2383
+ const error = new DataConnectError(code, reason);
2384
+ this.publishErrorToSubscribers(key, error);
2385
+ const callbacks = this.callbacks.get(key);
2386
+ if (callbacks) {
2387
+ [...callbacks].forEach(cb => cb.unsubscribe());
2388
+ }
2389
+ return;
2390
+ }
1280
2391
  }
1281
2392
  function getMaxAgeFromExtensions(extensions) {
1282
2393
  if (!extensions) {
@@ -1300,7 +2411,7 @@ function getDataConnectExtensionsWithoutMaxAge(extensions) {
1300
2411
 
1301
2412
  /**
1302
2413
  * @license
1303
- * Copyright 2024 Google LLC
2414
+ * Copyright 2026 Google LLC
1304
2415
  *
1305
2416
  * Licensed under the Apache License, Version 2.0 (the "License");
1306
2417
  * you may not use this file except in compliance with the License.
@@ -1314,188 +2425,110 @@ function getDataConnectExtensionsWithoutMaxAge(extensions) {
1314
2425
  * See the License for the specific language governing permissions and
1315
2426
  * limitations under the License.
1316
2427
  */
1317
- const PROD_HOST = 'firebasedataconnect.googleapis.com';
1318
- function urlBuilder(projectConfig, transportOptions) {
1319
- const { connector, location, projectId: project, service } = projectConfig;
1320
- const { host, sslEnabled, port } = transportOptions;
1321
- const protocol = sslEnabled ? 'https' : 'http';
1322
- const realHost = host || PROD_HOST;
1323
- let baseUrl = `${protocol}://${realHost}`;
1324
- if (typeof port === 'number') {
1325
- baseUrl += `:${port}`;
1326
- }
1327
- else if (typeof port !== 'undefined') {
1328
- logError('Port type is of an invalid type');
1329
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
1330
- }
1331
- return `${baseUrl}/v1/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
1332
- }
1333
- function addToken(url, apiKey) {
1334
- if (!apiKey) {
1335
- return url;
1336
- }
1337
- const newUrl = new URL(url);
1338
- newUrl.searchParams.append('key', apiKey);
1339
- return newUrl.toString();
1340
- }
1341
-
1342
2428
  /**
1343
- * @license
1344
- * Copyright 2024 Google LLC
1345
- *
1346
- * Licensed under the Apache License, Version 2.0 (the "License");
1347
- * you may not use this file except in compliance with the License.
1348
- * You may obtain a copy of the License at
1349
- *
1350
- * http://www.apache.org/licenses/LICENSE-2.0
1351
- *
1352
- * Unless required by applicable law or agreed to in writing, software
1353
- * distributed under the License is distributed on an "AS IS" BASIS,
1354
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
1355
- * See the License for the specific language governing permissions and
1356
- * limitations under the License.
2429
+ * Entry point for the transport layer. Manages routing between transport implementations.
2430
+ * @internal
1357
2431
  */
1358
- class RESTTransport {
1359
- constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType = CallerSdkTypeEnum.Base) {
2432
+ class DataConnectTransportManager {
2433
+ constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false, _callerSdkType) {
2434
+ this.options = options;
1360
2435
  this.apiKey = apiKey;
1361
2436
  this.appId = appId;
1362
2437
  this.authProvider = authProvider;
1363
2438
  this.appCheckProvider = appCheckProvider;
2439
+ this.transportOptions = transportOptions;
1364
2440
  this._isUsingGen = _isUsingGen;
1365
2441
  this._callerSdkType = _callerSdkType;
1366
- this._host = '';
1367
- this._location = 'l';
1368
- this._connectorName = '';
1369
- this._secure = true;
1370
- this._project = 'p';
1371
- this._accessToken = null;
1372
- this._appCheckToken = null;
1373
- this._lastToken = null;
1374
- this._isUsingEmulator = false;
1375
- // TODO(mtewani): Update U to include shape of body defined in line 13.
1376
- this.invokeQuery = (queryName, body) => {
1377
- const abortController = new AbortController();
1378
- // TODO(mtewani): Update to proper value
1379
- const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
1380
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
1381
- operationName: queryName,
1382
- variables: body
1383
- }, abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator));
1384
- return withAuth;
1385
- };
1386
- this.invokeMutation = (mutationName, body) => {
1387
- const abortController = new AbortController();
1388
- const taskResult = this.withRetry(() => {
1389
- return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
1390
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
1391
- operationName: mutationName,
1392
- variables: body
1393
- }, abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen, this._callerSdkType, this._isUsingEmulator);
1394
- });
1395
- return taskResult;
1396
- };
1397
- if (transportOptions) {
1398
- if (typeof transportOptions.port === 'number') {
1399
- this._port = transportOptions.port;
1400
- }
1401
- if (typeof transportOptions.sslEnabled !== 'undefined') {
1402
- this._secure = transportOptions.sslEnabled;
2442
+ this.isUsingEmulator = false;
2443
+ this.restTransport = new RESTTransport(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen, _callerSdkType);
2444
+ }
2445
+ /**
2446
+ * Initializes the stream transport if it hasn't been already.
2447
+ */
2448
+ initStreamTransport() {
2449
+ if (!this.streamTransport) {
2450
+ this.streamTransport = new WebSocketTransport(this.options, this.apiKey, this.appId, this.authProvider, this.appCheckProvider, this.transportOptions, this._isUsingGen, this._callerSdkType);
2451
+ if (this.isUsingEmulator && this.transportOptions) {
2452
+ this.streamTransport.useEmulator(this.transportOptions.host, this.transportOptions.port, this.transportOptions.sslEnabled);
1403
2453
  }
1404
- this._host = transportOptions.host;
1405
- }
1406
- const { location, projectId: project, connector, service } = options;
1407
- if (location) {
1408
- this._location = location;
1409
- }
1410
- if (project) {
1411
- this._project = project;
1412
- }
1413
- this._serviceName = service;
1414
- if (!connector) {
1415
- throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
2454
+ this.streamTransport.onGracefulStreamClose = () => {
2455
+ this.streamTransport = undefined;
2456
+ };
1416
2457
  }
1417
- this._connectorName = connector;
1418
- this.authProvider?.addTokenChangeListener(token => {
1419
- logDebug(`New Token Available: ${token}`);
1420
- this._accessToken = token;
1421
- });
1422
- this.appCheckProvider?.addTokenChangeListener(result => {
1423
- const { token } = result;
1424
- logDebug(`New App Check Token Available: ${token}`);
1425
- this._appCheckToken = token;
1426
- });
2458
+ return this.streamTransport;
1427
2459
  }
1428
- get endpointUrl() {
1429
- return urlBuilder({
1430
- connector: this._connectorName,
1431
- location: this._location,
1432
- projectId: this._project,
1433
- service: this._serviceName
1434
- }, { host: this._host, sslEnabled: this._secure, port: this._port });
2460
+ /**
2461
+ * Returns true if the stream is in a healthy, ready connection state and has active subscriptions.
2462
+ */
2463
+ executeShouldUseStream() {
2464
+ return (!!this.streamTransport &&
2465
+ !this.streamTransport.isPendingClose &&
2466
+ this.streamTransport.streamIsReady &&
2467
+ this.streamTransport.hasActiveSubscriptions &&
2468
+ !this.streamTransport.isUnableToConnect);
1435
2469
  }
1436
- useEmulator(host, port, isSecure) {
1437
- this._host = host;
1438
- this._isUsingEmulator = true;
1439
- if (typeof port === 'number') {
1440
- this._port = port;
1441
- }
1442
- if (typeof isSecure !== 'undefined') {
1443
- this._secure = isSecure;
2470
+ /**
2471
+ * Prefer to use Streaming Transport connection when one is available.
2472
+ * @inheritdoc
2473
+ */
2474
+ invokeQuery(queryName, body) {
2475
+ if (this.executeShouldUseStream()) {
2476
+ return this.streamTransport.invokeQuery(queryName, body).catch(err => {
2477
+ if (this.executeShouldUseStream()) {
2478
+ throw err;
2479
+ }
2480
+ return this.restTransport.invokeQuery(queryName, body);
2481
+ });
1444
2482
  }
2483
+ return this.restTransport.invokeQuery(queryName, body);
1445
2484
  }
1446
- onTokenChanged(newToken) {
1447
- this._accessToken = newToken;
1448
- }
1449
- async getWithAuth(forceToken = false) {
1450
- let starterPromise = new Promise(resolve => resolve(this._accessToken));
1451
- if (this.appCheckProvider) {
1452
- const appCheckToken = await this.appCheckProvider.getToken();
1453
- if (appCheckToken) {
1454
- this._appCheckToken = appCheckToken.token;
1455
- }
1456
- }
1457
- if (this.authProvider) {
1458
- starterPromise = this.authProvider
1459
- .getToken(/*forceToken=*/ forceToken)
1460
- .then(data => {
1461
- if (!data) {
1462
- return null;
2485
+ /**
2486
+ * Prefer to use Streaming Transport connection when one is available.
2487
+ * @inheritdoc
2488
+ */
2489
+ invokeMutation(queryName, body) {
2490
+ if (this.executeShouldUseStream()) {
2491
+ return this.streamTransport.invokeMutation(queryName, body).catch(err => {
2492
+ if (this.executeShouldUseStream()) {
2493
+ throw err;
1463
2494
  }
1464
- this._accessToken = data.accessToken;
1465
- return this._accessToken;
2495
+ return this.restTransport.invokeMutation(queryName, body);
1466
2496
  });
1467
2497
  }
1468
- else {
1469
- starterPromise = new Promise(resolve => resolve(''));
2498
+ return this.restTransport.invokeMutation(queryName, body);
2499
+ }
2500
+ invokeSubscribe(observer, queryName, body) {
2501
+ const streamTransport = this.initStreamTransport();
2502
+ if (streamTransport.isUnableToConnect) {
2503
+ throw new DataConnectError(Code.OTHER, 'Unable to connect streaming connection to server. Subscriptions are unavailable.');
1470
2504
  }
1471
- return starterPromise;
2505
+ streamTransport.invokeSubscribe(observer, queryName, body);
1472
2506
  }
1473
- _setLastToken(lastToken) {
1474
- this._lastToken = lastToken;
2507
+ invokeUnsubscribe(queryName, body) {
2508
+ if (this.streamTransport) {
2509
+ this.streamTransport.invokeUnsubscribe(queryName, body);
2510
+ }
1475
2511
  }
1476
- withRetry(promiseFactory, retry = false) {
1477
- let isNewToken = false;
1478
- return this.getWithAuth(retry)
1479
- .then(res => {
1480
- isNewToken = this._lastToken !== res;
1481
- this._lastToken = res;
1482
- return res;
1483
- })
1484
- .then(promiseFactory)
1485
- .catch(err => {
1486
- // Only retry if the result is unauthorized and the last token isn't the same as the new one.
1487
- if ('code' in err &&
1488
- err.code === Code.UNAUTHORIZED &&
1489
- !retry &&
1490
- isNewToken) {
1491
- logDebug('Retrying due to unauthorized');
1492
- return this.withRetry(promiseFactory, true);
1493
- }
1494
- throw err;
1495
- });
2512
+ useEmulator(host, port, sslEnabled) {
2513
+ this.isUsingEmulator = true;
2514
+ this.transportOptions = { host, port, sslEnabled };
2515
+ this.restTransport.useEmulator(host, port, sslEnabled);
2516
+ if (this.streamTransport) {
2517
+ this.streamTransport.useEmulator(host, port, sslEnabled);
2518
+ }
2519
+ }
2520
+ onAuthTokenChanged(token) {
2521
+ this.restTransport.onAuthTokenChanged(token);
2522
+ if (this.streamTransport) {
2523
+ this.streamTransport.onAuthTokenChanged(token);
2524
+ }
1496
2525
  }
1497
2526
  _setCallerSdkType(callerSdkType) {
1498
2527
  this._callerSdkType = callerSdkType;
2528
+ this.restTransport._setCallerSdkType(callerSdkType);
2529
+ if (this.streamTransport) {
2530
+ this.streamTransport._setCallerSdkType(callerSdkType);
2531
+ }
1499
2532
  }
1500
2533
  }
1501
2534
 
@@ -1661,8 +2694,8 @@ class DataConnect {
1661
2694
  return;
1662
2695
  }
1663
2696
  if (this._transportClass === undefined) {
1664
- logDebug('transportClass not provided. Defaulting to RESTTransport.');
1665
- this._transportClass = RESTTransport;
2697
+ logDebug('transportClass not provided. Defaulting to DataConnectTransportManager.');
2698
+ this._transportClass = DataConnectTransportManager;
1666
2699
  }
1667
2700
  this._authTokenProvider = new FirebaseAuthProvider(this.app.name, this.app.options, this._authProvider);
1668
2701
  const connectorConfig = {
@@ -2105,8 +3138,15 @@ function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComp
2105
3138
  * limitations under the License.
2106
3139
  */
2107
3140
  initializeFetch(fetch);
3141
+ if (typeof WebSocket !== 'undefined') {
3142
+ initializeWebSocket(WebSocket);
3143
+ }
3144
+ else {
3145
+ console.warn('WebSocket is not available in this environment. Use a polyfill or upgrade your Node version to one that supports WebSockets.');
3146
+ }
2108
3147
  registerDataConnect('node');
2109
3148
 
3149
+ exports.AbstractDataConnectTransport = AbstractDataConnectTransport;
2110
3150
  exports.CallerSdkTypeEnum = CallerSdkTypeEnum;
2111
3151
  exports.Code = Code;
2112
3152
  exports.DataConnect = DataConnect;
@@ -2124,6 +3164,7 @@ exports.connectDataConnectEmulator = connectDataConnectEmulator;
2124
3164
  exports.executeMutation = executeMutation;
2125
3165
  exports.executeQuery = executeQuery;
2126
3166
  exports.getDataConnect = getDataConnect;
3167
+ exports.getGoogApiClientValue = getGoogApiClientValue$1;
2127
3168
  exports.makeMemoryCacheProvider = makeMemoryCacheProvider;
2128
3169
  exports.mutationRef = mutationRef;
2129
3170
  exports.parseOptions = parseOptions;