@firebase/data-connect 0.1.0-canary.aa6db78eb → 0.1.0-canary.b942e9e6e

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.
@@ -1,10 +1,11 @@
1
+ import { __extends, __assign, __awaiter, __generator } from 'tslib';
1
2
  import { _removeServiceInstance, getApp, _getProvider, _registerComponent, registerVersion, SDK_VERSION as SDK_VERSION$1 } from '@firebase/app';
2
3
  import { Component } from '@firebase/component';
3
4
  import { FirebaseError } from '@firebase/util';
4
5
  import { Logger } from '@firebase/logger';
5
6
 
6
7
  const name = "@firebase/data-connect";
7
- const version = "0.1.0-canary.aa6db78eb";
8
+ const version = "0.1.0-canary.b942e9e6e";
8
9
 
9
10
  /**
10
11
  * @license
@@ -23,7 +24,7 @@ const version = "0.1.0-canary.aa6db78eb";
23
24
  * limitations under the License.
24
25
  */
25
26
  /** The semver (www.semver.org) version of the SDK. */
26
- let SDK_VERSION = '';
27
+ var SDK_VERSION = '';
27
28
  /**
28
29
  * SDK_VERSION should be set before any database instance is created
29
30
  * @internal
@@ -52,25 +53,27 @@ function setSDKVersion(version) {
52
53
  * @internal
53
54
  * Abstraction around AppCheck's token fetching capabilities.
54
55
  */
55
- class AppCheckTokenProvider {
56
- constructor(appName_, appCheckProvider) {
56
+ var AppCheckTokenProvider = /** @class */ (function () {
57
+ function AppCheckTokenProvider(appName_, appCheckProvider) {
58
+ var _this = this;
57
59
  this.appName_ = appName_;
58
60
  this.appCheckProvider = appCheckProvider;
59
61
  this.appCheck = appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.getImmediate({ optional: true });
60
62
  if (!this.appCheck) {
61
- void (appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(appCheck => (this.appCheck = appCheck)).catch());
63
+ void (appCheckProvider === null || appCheckProvider === void 0 ? void 0 : appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); }).catch());
62
64
  }
63
65
  }
64
- getToken(forceRefresh) {
66
+ AppCheckTokenProvider.prototype.getToken = function (forceRefresh) {
67
+ var _this = this;
65
68
  if (!this.appCheck) {
66
- return new Promise((resolve, reject) => {
69
+ return new Promise(function (resolve, reject) {
67
70
  // Support delayed initialization of FirebaseAppCheck. This allows our
68
71
  // customers to initialize the RTDB SDK before initializing Firebase
69
72
  // AppCheck and ensures that all requests are authenticated if a token
70
73
  // becomes available before the timoeout below expires.
71
- setTimeout(() => {
72
- if (this.appCheck) {
73
- this.getToken(forceRefresh).then(resolve, reject);
74
+ setTimeout(function () {
75
+ if (_this.appCheck) {
76
+ _this.getToken(forceRefresh).then(resolve, reject);
74
77
  }
75
78
  else {
76
79
  resolve(null);
@@ -79,12 +82,13 @@ class AppCheckTokenProvider {
79
82
  });
80
83
  }
81
84
  return this.appCheck.getToken(forceRefresh);
82
- }
83
- addTokenChangeListener(listener) {
85
+ };
86
+ AppCheckTokenProvider.prototype.addTokenChangeListener = function (listener) {
84
87
  var _a;
85
- void ((_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(appCheck => appCheck.addTokenListener(listener)));
86
- }
87
- }
88
+ void ((_a = this.appCheckProvider) === null || _a === void 0 ? void 0 : _a.get().then(function (appCheck) { return appCheck.addTokenListener(listener); }));
89
+ };
90
+ return AppCheckTokenProvider;
91
+ }());
88
92
 
89
93
  /**
90
94
  * @license
@@ -102,7 +106,7 @@ class AppCheckTokenProvider {
102
106
  * See the License for the specific language governing permissions and
103
107
  * limitations under the License.
104
108
  */
105
- const Code = {
109
+ var Code = {
106
110
  OTHER: 'other',
107
111
  ALREADY_INITIALIZED: 'already-initialized',
108
112
  NOT_INITIALIZED: 'not-initialized',
@@ -112,9 +116,10 @@ const Code = {
112
116
  UNAUTHORIZED: 'unauthorized'
113
117
  };
114
118
  /** An error returned by a DataConnect operation. */
115
- class DataConnectError extends FirebaseError {
119
+ var DataConnectError = /** @class */ (function (_super) {
120
+ __extends(DataConnectError, _super);
116
121
  /** @hideconstructor */
117
- constructor(
122
+ function DataConnectError(
118
123
  /**
119
124
  * The backend error code associated with this error.
120
125
  */
@@ -123,15 +128,17 @@ class DataConnectError extends FirebaseError {
123
128
  * A custom error description.
124
129
  */
125
130
  message) {
126
- super(code, message);
127
- this.code = code;
128
- this.message = message;
131
+ var _this = _super.call(this, code, message) || this;
132
+ _this.code = code;
133
+ _this.message = message;
129
134
  // HACK: We write a toString property directly because Error is not a real
130
135
  // class and so inheritance does not work correctly. We could alternatively
131
136
  // do the same "back-door inheritance" trick that FirebaseError does.
132
- this.toString = () => `${this.name}: [code=${this.code}]: ${this.message}`;
137
+ _this.toString = function () { return "".concat(_this.name, ": [code=").concat(_this.code, "]: ").concat(_this.message); };
138
+ return _this;
133
139
  }
134
- }
140
+ return DataConnectError;
141
+ }(FirebaseError));
135
142
 
136
143
  /**
137
144
  * @license
@@ -149,15 +156,15 @@ class DataConnectError extends FirebaseError {
149
156
  * See the License for the specific language governing permissions and
150
157
  * limitations under the License.
151
158
  */
152
- const logger = new Logger('@firebase/data-connect');
159
+ var logger = new Logger('@firebase/data-connect');
153
160
  function setLogLevel(logLevel) {
154
161
  logger.setLogLevel(logLevel);
155
162
  }
156
163
  function logDebug(msg) {
157
- logger.debug(`DataConnect (${SDK_VERSION}): ${msg}`);
164
+ logger.debug("DataConnect (".concat(SDK_VERSION, "): ").concat(msg));
158
165
  }
159
166
  function logError(msg) {
160
- logger.error(`DataConnect (${SDK_VERSION}): ${msg}`);
167
+ logger.error("DataConnect (".concat(SDK_VERSION, "): ").concat(msg));
161
168
  }
162
169
 
163
170
  /**
@@ -177,22 +184,24 @@ function logError(msg) {
177
184
  * limitations under the License.
178
185
  */
179
186
  // @internal
180
- class FirebaseAuthProvider {
181
- constructor(_appName, _options, _authProvider) {
187
+ var FirebaseAuthProvider = /** @class */ (function () {
188
+ function FirebaseAuthProvider(_appName, _options, _authProvider) {
189
+ var _this = this;
182
190
  this._appName = _appName;
183
191
  this._options = _options;
184
192
  this._authProvider = _authProvider;
185
193
  this._auth = _authProvider.getImmediate({ optional: true });
186
194
  if (!this._auth) {
187
- _authProvider.onInit(auth => (this._auth = auth));
195
+ _authProvider.onInit(function (auth) { return (_this._auth = auth); });
188
196
  }
189
197
  }
190
- getToken(forceRefresh) {
198
+ FirebaseAuthProvider.prototype.getToken = function (forceRefresh) {
199
+ var _this = this;
191
200
  if (!this._auth) {
192
- return new Promise((resolve, reject) => {
193
- setTimeout(() => {
194
- if (this._auth) {
195
- this.getToken(forceRefresh).then(resolve, reject);
201
+ return new Promise(function (resolve, reject) {
202
+ setTimeout(function () {
203
+ if (_this._auth) {
204
+ _this.getToken(forceRefresh).then(resolve, reject);
196
205
  }
197
206
  else {
198
207
  resolve(null);
@@ -200,7 +209,7 @@ class FirebaseAuthProvider {
200
209
  }, 0);
201
210
  });
202
211
  }
203
- return this._auth.getToken(forceRefresh).catch(error => {
212
+ return this._auth.getToken(forceRefresh).catch(function (error) {
204
213
  if (error && error.code === 'auth/token-not-initialized') {
205
214
  logDebug('Got auth/token-not-initialized error. Treating as null token.');
206
215
  return null;
@@ -211,18 +220,19 @@ class FirebaseAuthProvider {
211
220
  return Promise.reject(error);
212
221
  }
213
222
  });
214
- }
215
- addTokenChangeListener(listener) {
223
+ };
224
+ FirebaseAuthProvider.prototype.addTokenChangeListener = function (listener) {
216
225
  var _a;
217
226
  (_a = this._auth) === null || _a === void 0 ? void 0 : _a.addAuthTokenListener(listener);
218
- }
219
- removeTokenChangeListener(listener) {
227
+ };
228
+ FirebaseAuthProvider.prototype.removeTokenChangeListener = function (listener) {
220
229
  this._authProvider
221
230
  .get()
222
- .then(auth => auth.removeAuthTokenListener(listener))
223
- .catch(err => logError(err));
224
- }
225
- }
231
+ .then(function (auth) { return auth.removeAuthTokenListener(listener); })
232
+ .catch(function (err) { return logError(err); });
233
+ };
234
+ return FirebaseAuthProvider;
235
+ }());
226
236
 
227
237
  /**
228
238
  * @license
@@ -240,10 +250,10 @@ class FirebaseAuthProvider {
240
250
  * See the License for the specific language governing permissions and
241
251
  * limitations under the License.
242
252
  */
243
- const QUERY_STR = 'query';
244
- const MUTATION_STR = 'mutation';
245
- const SOURCE_SERVER = 'SERVER';
246
- const SOURCE_CACHE = 'CACHE';
253
+ var QUERY_STR = 'query';
254
+ var MUTATION_STR = 'mutation';
255
+ var SOURCE_SERVER = 'SERVER';
256
+ var SOURCE_CACHE = 'CACHE';
247
257
 
248
258
  /**
249
259
  * @license
@@ -261,11 +271,11 @@ const SOURCE_CACHE = 'CACHE';
261
271
  * See the License for the specific language governing permissions and
262
272
  * limitations under the License.
263
273
  */
264
- let encoderImpl;
274
+ var encoderImpl;
265
275
  function setEncoder(encoder) {
266
276
  encoderImpl = encoder;
267
277
  }
268
- setEncoder(o => JSON.stringify(o));
278
+ setEncoder(function (o) { return JSON.stringify(o); });
269
279
 
270
280
  /**
271
281
  * @license
@@ -308,31 +318,31 @@ function setIfNotExists(map, key, val) {
308
318
  function getRefSerializer(queryRef, data, source) {
309
319
  return function toJSON() {
310
320
  return {
311
- data,
321
+ data: data,
312
322
  refInfo: {
313
323
  name: queryRef.name,
314
324
  variables: queryRef.variables,
315
- connectorConfig: Object.assign({ projectId: queryRef.dataConnect.app.options.projectId }, queryRef.dataConnect.getSettings())
325
+ connectorConfig: __assign({ projectId: queryRef.dataConnect.app.options.projectId }, queryRef.dataConnect.getSettings())
316
326
  },
317
327
  fetchTime: Date.now().toLocaleString(),
318
- source
328
+ source: source
319
329
  };
320
330
  };
321
331
  }
322
- class QueryManager {
323
- constructor(transport) {
332
+ var QueryManager = /** @class */ (function () {
333
+ function QueryManager(transport) {
324
334
  this.transport = transport;
325
335
  this._queries = new Map();
326
336
  }
327
- track(queryName, variables, initialCache) {
328
- const ref = {
337
+ QueryManager.prototype.track = function (queryName, variables, initialCache) {
338
+ var ref = {
329
339
  name: queryName,
330
- variables,
340
+ variables: variables,
331
341
  refType: QUERY_STR
332
342
  };
333
- const key = encoderImpl(ref);
334
- const newTrackedQuery = {
335
- ref,
343
+ var key = encoderImpl(ref);
344
+ var newTrackedQuery = {
345
+ ref: ref,
336
346
  subscriptions: [],
337
347
  currentCache: initialCache || null,
338
348
  lastError: null
@@ -340,21 +350,22 @@ class QueryManager {
340
350
  // @ts-ignore
341
351
  setIfNotExists(this._queries, key, newTrackedQuery);
342
352
  return this._queries.get(key);
343
- }
344
- addSubscription(queryRef, onResultCallback, onErrorCallback, initialCache) {
345
- const key = encoderImpl({
353
+ };
354
+ QueryManager.prototype.addSubscription = function (queryRef, onResultCallback, onErrorCallback, initialCache) {
355
+ var _this = this;
356
+ var key = encoderImpl({
346
357
  name: queryRef.name,
347
358
  variables: queryRef.variables,
348
359
  refType: QUERY_STR
349
360
  });
350
- const trackedQuery = this._queries.get(key);
351
- const subscription = {
361
+ var trackedQuery = this._queries.get(key);
362
+ var subscription = {
352
363
  userCallback: onResultCallback,
353
364
  errCallback: onErrorCallback
354
365
  };
355
- const unsubscribe = () => {
356
- const trackedQuery = this._queries.get(key);
357
- trackedQuery.subscriptions = trackedQuery.subscriptions.filter(sub => sub !== subscription);
366
+ var unsubscribe = function () {
367
+ var trackedQuery = _this._queries.get(key);
368
+ trackedQuery.subscriptions = trackedQuery.subscriptions.filter(function (sub) { return sub !== subscription; });
358
369
  };
359
370
  if (initialCache && trackedQuery.currentCache !== initialCache) {
360
371
  logDebug('Initial cache found. Comparing dates.');
@@ -365,7 +376,7 @@ class QueryManager {
365
376
  }
366
377
  }
367
378
  if (trackedQuery.currentCache !== null) {
368
- const cachedData = trackedQuery.currentCache.data;
379
+ var cachedData = trackedQuery.currentCache.data;
369
380
  onResultCallback({
370
381
  data: cachedData,
371
382
  source: SOURCE_CACHE,
@@ -380,39 +391,42 @@ class QueryManager {
380
391
  trackedQuery.subscriptions.push({
381
392
  userCallback: onResultCallback,
382
393
  errCallback: onErrorCallback,
383
- unsubscribe
394
+ unsubscribe: unsubscribe
384
395
  });
385
396
  if (!trackedQuery.currentCache) {
386
- logDebug(`No cache available for query ${queryRef.name} with variables ${JSON.stringify(queryRef.variables)}. Calling executeQuery.`);
387
- const promise = this.executeQuery(queryRef);
397
+ logDebug("No cache available for query ".concat(queryRef.name, " with variables ").concat(JSON.stringify(queryRef.variables), ". Calling executeQuery."));
398
+ var promise = this.executeQuery(queryRef);
388
399
  // We want to ignore the error and let subscriptions handle it
389
- promise.then(undefined, err => { });
400
+ promise.then(undefined, function (err) { });
390
401
  }
391
402
  return unsubscribe;
392
- }
393
- executeQuery(queryRef) {
394
- const key = encoderImpl({
403
+ };
404
+ QueryManager.prototype.executeQuery = function (queryRef) {
405
+ if (queryRef.refType !== QUERY_STR) {
406
+ throw new DataConnectError(Code.INVALID_ARGUMENT, "ExecuteQuery can only execute query operation");
407
+ }
408
+ var key = encoderImpl({
395
409
  name: queryRef.name,
396
410
  variables: queryRef.variables,
397
411
  refType: QUERY_STR
398
412
  });
399
- const trackedQuery = this._queries.get(key);
400
- const result = this.transport.invokeQuery(queryRef.name, queryRef.variables);
401
- const newR = result.then(res => {
402
- const fetchTime = new Date().toString();
403
- const result = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: queryRef, toJSON: getRefSerializer(queryRef, res.data, SOURCE_SERVER), fetchTime });
404
- trackedQuery.subscriptions.forEach(subscription => {
413
+ var trackedQuery = this._queries.get(key);
414
+ var result = this.transport.invokeQuery(queryRef.name, queryRef.variables);
415
+ var newR = result.then(function (res) {
416
+ var fetchTime = new Date().toString();
417
+ var result = __assign(__assign({}, res), { source: SOURCE_SERVER, ref: queryRef, toJSON: getRefSerializer(queryRef, res.data, SOURCE_SERVER), fetchTime: fetchTime });
418
+ trackedQuery.subscriptions.forEach(function (subscription) {
405
419
  subscription.userCallback(result);
406
420
  });
407
421
  trackedQuery.currentCache = {
408
422
  data: res.data,
409
423
  source: SOURCE_CACHE,
410
- fetchTime
424
+ fetchTime: fetchTime
411
425
  };
412
426
  return result;
413
- }, err => {
427
+ }, function (err) {
414
428
  trackedQuery.lastError = err;
415
- trackedQuery.subscriptions.forEach(subscription => {
429
+ trackedQuery.subscriptions.forEach(function (subscription) {
416
430
  if (subscription.errCallback) {
417
431
  subscription.errCallback(err);
418
432
  }
@@ -420,14 +434,15 @@ class QueryManager {
420
434
  throw err;
421
435
  });
422
436
  return newR;
423
- }
424
- enableEmulator(host, port) {
437
+ };
438
+ QueryManager.prototype.enableEmulator = function (host, port) {
425
439
  this.transport.useEmulator(host, port);
426
- }
427
- }
440
+ };
441
+ return QueryManager;
442
+ }());
428
443
  function compareDates(str1, str2) {
429
- const date1 = new Date(str1);
430
- const date2 = new Date(str2);
444
+ var date1 = new Date(str1);
445
+ var date2 = new Date(str2);
431
446
  return date1.getTime() < date2.getTime();
432
447
  }
433
448
 
@@ -448,25 +463,25 @@ function compareDates(str1, str2) {
448
463
  * limitations under the License.
449
464
  */
450
465
  function urlBuilder(projectConfig, transportOptions) {
451
- const { connector, location, projectId: project, service } = projectConfig;
452
- const { host, sslEnabled, port } = transportOptions;
453
- const protocol = sslEnabled ? 'https' : 'http';
454
- const realHost = host || `firebasedataconnect.googleapis.com`;
455
- let baseUrl = `${protocol}://${realHost}`;
466
+ var connector = projectConfig.connector, location = projectConfig.location, project = projectConfig.projectId, service = projectConfig.service;
467
+ var host = transportOptions.host, sslEnabled = transportOptions.sslEnabled, port = transportOptions.port;
468
+ var protocol = sslEnabled ? 'https' : 'http';
469
+ var realHost = host || "firebasedataconnect.googleapis.com";
470
+ var baseUrl = "".concat(protocol, "://").concat(realHost);
456
471
  if (typeof port === 'number') {
457
- baseUrl += `:${port}`;
472
+ baseUrl += ":".concat(port);
458
473
  }
459
474
  else if (typeof port !== 'undefined') {
460
475
  logError('Port type is of an invalid type');
461
476
  throw new DataConnectError(Code.INVALID_ARGUMENT, 'Incorrect type for port passed in!');
462
477
  }
463
- return `${baseUrl}/v1beta/projects/${project}/locations/${location}/services/${service}/connectors/${connector}`;
478
+ return "".concat(baseUrl, "/v1beta/projects/").concat(project, "/locations/").concat(location, "/services/").concat(service, "/connectors/").concat(connector);
464
479
  }
465
480
  function addToken(url, apiKey) {
466
481
  if (!apiKey) {
467
482
  return url;
468
483
  }
469
- const newUrl = new URL(url);
484
+ var newUrl = new URL(url);
470
485
  newUrl.searchParams.append('key', apiKey);
471
486
  return newUrl.toString();
472
487
  }
@@ -487,19 +502,21 @@ function addToken(url, apiKey) {
487
502
  * See the License for the specific language governing permissions and
488
503
  * limitations under the License.
489
504
  */
490
- let connectFetch = globalThis.fetch;
505
+ var connectFetch = globalThis.fetch;
491
506
  function getGoogApiClientValue(_isUsingGen) {
492
- let str = 'gl-js/ fire/' + SDK_VERSION;
507
+ var str = 'gl-js/ fire/' + SDK_VERSION;
493
508
  if (_isUsingGen) {
494
- str += ' web/gen';
509
+ str += ' js/gen';
495
510
  }
496
511
  return str;
497
512
  }
498
- function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken, _isUsingGen) {
513
+ function dcFetch(url, body, _a, appId, accessToken, appCheckToken, _isUsingGen) {
514
+ var _this = this;
515
+ var signal = _a.signal;
499
516
  if (!connectFetch) {
500
517
  throw new DataConnectError(Code.OTHER, 'No Fetch Implementation detected!');
501
518
  }
502
- const headers = {
519
+ var headers = {
503
520
  'Content-Type': 'application/json',
504
521
  'X-Goog-Api-Client': getGoogApiClientValue(_isUsingGen)
505
522
  };
@@ -512,38 +529,49 @@ function dcFetch(url, body, { signal }, appId, accessToken, appCheckToken, _isUs
512
529
  if (appCheckToken) {
513
530
  headers['X-Firebase-AppCheck'] = appCheckToken;
514
531
  }
515
- const bodyStr = JSON.stringify(body);
516
- logDebug(`Making request out to ${url} with body: ${bodyStr}`);
532
+ var bodyStr = JSON.stringify(body);
533
+ logDebug("Making request out to ".concat(url, " with body: ").concat(bodyStr));
517
534
  return connectFetch(url, {
518
535
  body: bodyStr,
519
536
  method: 'POST',
520
- headers,
521
- signal
537
+ headers: headers,
538
+ signal: signal
522
539
  })
523
- .catch(err => {
540
+ .catch(function (err) {
524
541
  throw new DataConnectError(Code.OTHER, 'Failed to fetch: ' + JSON.stringify(err));
525
542
  })
526
- .then(async (response) => {
527
- let jsonResponse = null;
528
- try {
529
- jsonResponse = await response.json();
530
- }
531
- catch (e) {
532
- throw new DataConnectError(Code.OTHER, JSON.stringify(e));
533
- }
534
- const message = getMessage(jsonResponse);
535
- if (response.status >= 400) {
536
- logError('Error while performing request: ' + JSON.stringify(jsonResponse));
537
- if (response.status === 401) {
538
- throw new DataConnectError(Code.UNAUTHORIZED, message);
543
+ .then(function (response) { return __awaiter(_this, void 0, void 0, function () {
544
+ var jsonResponse, e_1, message;
545
+ return __generator(this, function (_a) {
546
+ switch (_a.label) {
547
+ case 0:
548
+ jsonResponse = null;
549
+ _a.label = 1;
550
+ case 1:
551
+ _a.trys.push([1, 3, , 4]);
552
+ return [4 /*yield*/, response.json()];
553
+ case 2:
554
+ jsonResponse = _a.sent();
555
+ return [3 /*break*/, 4];
556
+ case 3:
557
+ e_1 = _a.sent();
558
+ throw new DataConnectError(Code.OTHER, JSON.stringify(e_1));
559
+ case 4:
560
+ message = getMessage(jsonResponse);
561
+ if (response.status >= 400) {
562
+ logError('Error while performing request: ' + JSON.stringify(jsonResponse));
563
+ if (response.status === 401) {
564
+ throw new DataConnectError(Code.UNAUTHORIZED, message);
565
+ }
566
+ throw new DataConnectError(Code.OTHER, message);
567
+ }
568
+ return [2 /*return*/, jsonResponse];
539
569
  }
540
- throw new DataConnectError(Code.OTHER, message);
541
- }
542
- return jsonResponse;
543
- })
544
- .then(res => {
570
+ });
571
+ }); })
572
+ .then(function (res) {
545
573
  if (res.errors && res.errors.length) {
546
- const stringified = JSON.stringify(res.errors);
574
+ var stringified = JSON.stringify(res.errors);
547
575
  logError('DataConnect error while performing request: ' + stringified);
548
576
  throw new DataConnectError(Code.OTHER, stringified);
549
577
  }
@@ -573,8 +601,10 @@ function getMessage(obj) {
573
601
  * See the License for the specific language governing permissions and
574
602
  * limitations under the License.
575
603
  */
576
- class RESTTransport {
577
- constructor(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen = false) {
604
+ var RESTTransport = /** @class */ (function () {
605
+ function RESTTransport(options, apiKey, appId, authProvider, appCheckProvider, transportOptions, _isUsingGen) {
606
+ if (_isUsingGen === void 0) { _isUsingGen = false; }
607
+ var _this = this;
578
608
  var _a, _b;
579
609
  this.apiKey = apiKey;
580
610
  this.appId = appId;
@@ -590,34 +620,36 @@ class RESTTransport {
590
620
  this._appCheckToken = null;
591
621
  this._lastToken = null;
592
622
  // TODO(mtewani): Update U to include shape of body defined in line 13.
593
- this.invokeQuery = (queryName, body) => {
594
- const abortController = new AbortController();
623
+ this.invokeQuery = function (queryName, body) {
624
+ var abortController = new AbortController();
595
625
  // TODO(mtewani): Update to proper value
596
- const withAuth = this.withRetry(() => dcFetch(addToken(`${this.endpointUrl}:executeQuery`, this.apiKey), {
597
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
598
- operationName: queryName,
599
- variables: body
600
- }, // TODO(mtewani): This is a patch, fix this.
601
- abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen));
626
+ var withAuth = _this.withRetry(function () {
627
+ return dcFetch(addToken("".concat(_this.endpointUrl, ":executeQuery"), _this.apiKey), {
628
+ name: "projects/".concat(_this._project, "/locations/").concat(_this._location, "/services/").concat(_this._serviceName, "/connectors/").concat(_this._connectorName),
629
+ operationName: queryName,
630
+ variables: body
631
+ }, // TODO(mtewani): This is a patch, fix this.
632
+ abortController, _this.appId, _this._accessToken, _this._appCheckToken, _this._isUsingGen);
633
+ });
602
634
  return {
603
635
  then: withAuth.then.bind(withAuth),
604
636
  catch: withAuth.catch.bind(withAuth)
605
637
  };
606
638
  };
607
- this.invokeMutation = (mutationName, body) => {
608
- const abortController = new AbortController();
609
- const taskResult = this.withRetry(() => {
610
- return dcFetch(addToken(`${this.endpointUrl}:executeMutation`, this.apiKey), {
611
- name: `projects/${this._project}/locations/${this._location}/services/${this._serviceName}/connectors/${this._connectorName}`,
639
+ this.invokeMutation = function (mutationName, body) {
640
+ var abortController = new AbortController();
641
+ var taskResult = _this.withRetry(function () {
642
+ return dcFetch(addToken("".concat(_this.endpointUrl, ":executeMutation"), _this.apiKey), {
643
+ name: "projects/".concat(_this._project, "/locations/").concat(_this._location, "/services/").concat(_this._serviceName, "/connectors/").concat(_this._connectorName),
612
644
  operationName: mutationName,
613
645
  variables: body
614
- }, abortController, this.appId, this._accessToken, this._appCheckToken, this._isUsingGen);
646
+ }, abortController, _this.appId, _this._accessToken, _this._appCheckToken, _this._isUsingGen);
615
647
  });
616
648
  return {
617
649
  then: taskResult.then.bind(taskResult),
618
650
  // catch: taskResult.catch.bind(taskResult),
619
651
  // finally: taskResult.finally.bind(taskResult),
620
- cancel: () => abortController.abort()
652
+ cancel: function () { return abortController.abort(); }
621
653
  };
622
654
  };
623
655
  if (transportOptions) {
@@ -629,7 +661,7 @@ class RESTTransport {
629
661
  }
630
662
  this._host = transportOptions.host;
631
663
  }
632
- const { location, projectId: project, connector, service } = options;
664
+ var location = options.location, project = options.projectId, connector = options.connector, service = options.service;
633
665
  if (location) {
634
666
  this._location = location;
635
667
  }
@@ -641,25 +673,29 @@ class RESTTransport {
641
673
  throw new DataConnectError(Code.INVALID_ARGUMENT, 'Connector Name required!');
642
674
  }
643
675
  this._connectorName = connector;
644
- (_a = this.authProvider) === null || _a === void 0 ? void 0 : _a.addTokenChangeListener(token => {
645
- logDebug(`New Token Available: ${token}`);
646
- this._accessToken = token;
676
+ (_a = this.authProvider) === null || _a === void 0 ? void 0 : _a.addTokenChangeListener(function (token) {
677
+ logDebug("New Token Available: ".concat(token));
678
+ _this._accessToken = token;
647
679
  });
648
- (_b = this.appCheckProvider) === null || _b === void 0 ? void 0 : _b.addTokenChangeListener(result => {
649
- const { token } = result;
650
- logDebug(`New App Check Token Available: ${token}`);
651
- this._appCheckToken = token;
680
+ (_b = this.appCheckProvider) === null || _b === void 0 ? void 0 : _b.addTokenChangeListener(function (result) {
681
+ var token = result.token;
682
+ logDebug("New App Check Token Available: ".concat(token));
683
+ _this._appCheckToken = token;
652
684
  });
653
685
  }
654
- get endpointUrl() {
655
- return urlBuilder({
656
- connector: this._connectorName,
657
- location: this._location,
658
- projectId: this._project,
659
- service: this._serviceName
660
- }, { host: this._host, sslEnabled: this._secure, port: this._port });
661
- }
662
- useEmulator(host, port, isSecure) {
686
+ Object.defineProperty(RESTTransport.prototype, "endpointUrl", {
687
+ get: function () {
688
+ return urlBuilder({
689
+ connector: this._connectorName,
690
+ location: this._location,
691
+ projectId: this._project,
692
+ service: this._serviceName
693
+ }, { host: this._host, sslEnabled: this._secure, port: this._port });
694
+ },
695
+ enumerable: false,
696
+ configurable: true
697
+ });
698
+ RESTTransport.prototype.useEmulator = function (host, port, isSecure) {
663
699
  this._host = host;
664
700
  if (typeof port === 'number') {
665
701
  this._port = port;
@@ -667,57 +703,76 @@ class RESTTransport {
667
703
  if (typeof isSecure !== 'undefined') {
668
704
  this._secure = isSecure;
669
705
  }
670
- }
671
- onTokenChanged(newToken) {
706
+ };
707
+ RESTTransport.prototype.onTokenChanged = function (newToken) {
672
708
  this._accessToken = newToken;
673
- }
674
- async getWithAuth(forceToken = false) {
709
+ };
710
+ RESTTransport.prototype.getWithAuth = function (forceToken) {
675
711
  var _a;
676
- let starterPromise = new Promise(resolve => resolve(this._accessToken));
677
- if (this.appCheckProvider) {
678
- this._appCheckToken = (_a = (await this.appCheckProvider.getToken())) === null || _a === void 0 ? void 0 : _a.token;
679
- }
680
- if (this.authProvider) {
681
- starterPromise = this.authProvider
682
- .getToken(/*forceToken=*/ forceToken)
683
- .then(data => {
684
- if (!data) {
685
- return null;
712
+ if (forceToken === void 0) { forceToken = false; }
713
+ return __awaiter(this, void 0, void 0, function () {
714
+ var starterPromise, _b;
715
+ var _this = this;
716
+ return __generator(this, function (_c) {
717
+ switch (_c.label) {
718
+ case 0:
719
+ starterPromise = new Promise(function (resolve) {
720
+ return resolve(_this._accessToken);
721
+ });
722
+ if (!this.appCheckProvider) return [3 /*break*/, 2];
723
+ _b = this;
724
+ return [4 /*yield*/, this.appCheckProvider.getToken()];
725
+ case 1:
726
+ _b._appCheckToken = (_a = (_c.sent())) === null || _a === void 0 ? void 0 : _a.token;
727
+ _c.label = 2;
728
+ case 2:
729
+ if (this.authProvider) {
730
+ starterPromise = this.authProvider
731
+ .getToken(/*forceToken=*/ forceToken)
732
+ .then(function (data) {
733
+ if (!data) {
734
+ return null;
735
+ }
736
+ _this._accessToken = data.accessToken;
737
+ return _this._accessToken;
738
+ });
739
+ }
740
+ else {
741
+ starterPromise = new Promise(function (resolve) { return resolve(''); });
742
+ }
743
+ return [2 /*return*/, starterPromise];
686
744
  }
687
- this._accessToken = data.accessToken;
688
- return this._accessToken;
689
745
  });
690
- }
691
- else {
692
- starterPromise = new Promise(resolve => resolve(''));
693
- }
694
- return starterPromise;
695
- }
696
- _setLastToken(lastToken) {
746
+ });
747
+ };
748
+ RESTTransport.prototype._setLastToken = function (lastToken) {
697
749
  this._lastToken = lastToken;
698
- }
699
- withRetry(promiseFactory, retry = false) {
700
- let isNewToken = false;
750
+ };
751
+ RESTTransport.prototype.withRetry = function (promiseFactory, retry) {
752
+ var _this = this;
753
+ if (retry === void 0) { retry = false; }
754
+ var isNewToken = false;
701
755
  return this.getWithAuth(retry)
702
- .then(res => {
703
- isNewToken = this._lastToken !== res;
704
- this._lastToken = res;
756
+ .then(function (res) {
757
+ isNewToken = _this._lastToken !== res;
758
+ _this._lastToken = res;
705
759
  return res;
706
760
  })
707
761
  .then(promiseFactory)
708
- .catch(err => {
762
+ .catch(function (err) {
709
763
  // Only retry if the result is unauthorized and the last token isn't the same as the new one.
710
764
  if ('code' in err &&
711
765
  err.code === Code.UNAUTHORIZED &&
712
766
  !retry &&
713
767
  isNewToken) {
714
768
  logDebug('Retrying due to unauthorized');
715
- return this.withRetry(promiseFactory, true);
769
+ return _this.withRetry(promiseFactory, true);
716
770
  }
717
771
  throw err;
718
772
  });
719
- }
720
- }
773
+ };
774
+ return RESTTransport;
775
+ }());
721
776
 
722
777
  /**
723
778
  * @license
@@ -744,7 +799,7 @@ class RESTTransport {
744
799
  */
745
800
  function mutationRef(dcInstance, mutationName, variables) {
746
801
  dcInstance.setInitialized();
747
- const ref = {
802
+ var ref = {
748
803
  dataConnect: dcInstance,
749
804
  name: mutationName,
750
805
  refType: MUTATION_STR,
@@ -755,23 +810,27 @@ function mutationRef(dcInstance, mutationName, variables) {
755
810
  /**
756
811
  * @internal
757
812
  */
758
- class MutationManager {
759
- constructor(_transport) {
813
+ var MutationManager = /** @class */ (function () {
814
+ function MutationManager(_transport) {
760
815
  this._transport = _transport;
761
816
  this._inflight = [];
762
817
  }
763
- executeMutation(mutationRef) {
764
- const result = this._transport.invokeMutation(mutationRef.name, mutationRef.variables);
765
- const withRefPromise = result.then(res => {
766
- const obj = Object.assign(Object.assign({}, res), { source: SOURCE_SERVER, ref: mutationRef, fetchTime: Date.now().toLocaleString() });
818
+ MutationManager.prototype.executeMutation = function (mutationRef) {
819
+ var _this = this;
820
+ var result = this._transport.invokeMutation(mutationRef.name, mutationRef.variables);
821
+ var withRefPromise = result.then(function (res) {
822
+ var obj = __assign(__assign({}, res), { source: SOURCE_SERVER, ref: mutationRef, fetchTime: Date.now().toLocaleString() });
767
823
  return obj;
768
824
  });
769
825
  this._inflight.push(result);
770
- const removePromise = () => (this._inflight = this._inflight.filter(promise => promise !== result));
826
+ var removePromise = function () {
827
+ return (_this._inflight = _this._inflight.filter(function (promise) { return promise !== result; }));
828
+ };
771
829
  result.then(removePromise, removePromise);
772
830
  return withRefPromise;
773
- }
774
- }
831
+ };
832
+ return MutationManager;
833
+ }());
775
834
  /**
776
835
  * Execute Mutation
777
836
  * @param mutationRef mutation to execute
@@ -797,7 +856,7 @@ function executeMutation(mutationRef) {
797
856
  * See the License for the specific language governing permissions and
798
857
  * limitations under the License.
799
858
  */
800
- const FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR = 'FIREBASE_DATA_CONNECT_EMULATOR_HOST';
859
+ var FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR = 'FIREBASE_DATA_CONNECT_EMULATOR_HOST';
801
860
  /**
802
861
  *
803
862
  * @param fullHost
@@ -805,18 +864,18 @@ const FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR = 'FIREBASE_DATA_CONNECT_EMULATOR_
805
864
  * @internal
806
865
  */
807
866
  function parseOptions(fullHost) {
808
- const [protocol, hostName] = fullHost.split('://');
809
- const isSecure = protocol === 'https';
810
- const [host, portAsString] = hostName.split(':');
811
- const port = Number(portAsString);
812
- return { host, port, sslEnabled: isSecure };
867
+ var _a = fullHost.split('://'), protocol = _a[0], hostName = _a[1];
868
+ var isSecure = protocol === 'https';
869
+ var _b = hostName.split(':'), host = _b[0], portAsString = _b[1];
870
+ var port = Number(portAsString);
871
+ return { host: host, port: port, sslEnabled: isSecure };
813
872
  }
814
873
  /**
815
874
  * Class representing Firebase Data Connect
816
875
  */
817
- class DataConnect {
876
+ var DataConnect = /** @class */ (function () {
818
877
  // @internal
819
- constructor(app,
878
+ function DataConnect(app,
820
879
  // TODO(mtewani): Replace with _dataConnectOptions in the future
821
880
  dataConnectOptions, _authProvider, _appCheckProvider) {
822
881
  this.app = app;
@@ -827,7 +886,7 @@ class DataConnect {
827
886
  this._initialized = false;
828
887
  this._isUsingGeneratedSdk = false;
829
888
  if (typeof process !== 'undefined' && process.env) {
830
- const host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR];
889
+ var host = process.env[FIREBASE_DATA_CONNECT_EMULATOR_HOST_VAR];
831
890
  if (host) {
832
891
  logDebug('Found custom host. Using emulator');
833
892
  this.isEmulator = true;
@@ -836,23 +895,23 @@ class DataConnect {
836
895
  }
837
896
  }
838
897
  // @internal
839
- _useGeneratedSdk() {
898
+ DataConnect.prototype._useGeneratedSdk = function () {
840
899
  if (!this._isUsingGeneratedSdk) {
841
900
  this._isUsingGeneratedSdk = true;
842
901
  }
843
- }
844
- _delete() {
902
+ };
903
+ DataConnect.prototype._delete = function () {
845
904
  _removeServiceInstance(this.app, 'data-connect', JSON.stringify(this.getSettings()));
846
905
  return Promise.resolve();
847
- }
906
+ };
848
907
  // @internal
849
- getSettings() {
850
- const copy = JSON.parse(JSON.stringify(this.dataConnectOptions));
908
+ DataConnect.prototype.getSettings = function () {
909
+ var copy = JSON.parse(JSON.stringify(this.dataConnectOptions));
851
910
  delete copy.projectId;
852
911
  return copy;
853
- }
912
+ };
854
913
  // @internal
855
- setInitialized() {
914
+ DataConnect.prototype.setInitialized = function () {
856
915
  if (this._initialized) {
857
916
  return;
858
917
  }
@@ -873,17 +932,18 @@ class DataConnect {
873
932
  }
874
933
  this._queryManager = new QueryManager(this._transport);
875
934
  this._mutationManager = new MutationManager(this._transport);
876
- }
935
+ };
877
936
  // @internal
878
- enableEmulator(transportOptions) {
937
+ DataConnect.prototype.enableEmulator = function (transportOptions) {
879
938
  if (this._initialized) {
880
939
  logError('enableEmulator called after initialization');
881
940
  throw new DataConnectError(Code.ALREADY_INITIALIZED, 'DataConnect instance already initialized!');
882
941
  }
883
942
  this._transportOptions = transportOptions;
884
943
  this.isEmulator = true;
885
- }
886
- }
944
+ };
945
+ return DataConnect;
946
+ }());
887
947
  /**
888
948
  * Connect to the DataConnect Emulator
889
949
  * @param dc Data Connect instance
@@ -891,12 +951,13 @@ class DataConnect {
891
951
  * @param port port of emulator server
892
952
  * @param sslEnabled use https
893
953
  */
894
- function connectDataConnectEmulator(dc, host, port, sslEnabled = false) {
895
- dc.enableEmulator({ host, port, sslEnabled });
954
+ function connectDataConnectEmulator(dc, host, port, sslEnabled) {
955
+ if (sslEnabled === void 0) { sslEnabled = false; }
956
+ dc.enableEmulator({ host: host, port: port, sslEnabled: sslEnabled });
896
957
  }
897
958
  function getDataConnect(appOrOptions, optionalOptions) {
898
- let app;
899
- let dcOptions;
959
+ var app;
960
+ var dcOptions;
900
961
  if ('location' in appOrOptions) {
901
962
  dcOptions = appOrOptions;
902
963
  app = getApp();
@@ -908,12 +969,12 @@ function getDataConnect(appOrOptions, optionalOptions) {
908
969
  if (!app || Object.keys(app).length === 0) {
909
970
  app = getApp();
910
971
  }
911
- const provider = _getProvider(app, 'data-connect');
912
- const identifier = JSON.stringify(dcOptions);
972
+ var provider = _getProvider(app, 'data-connect');
973
+ var identifier = JSON.stringify(dcOptions);
913
974
  if (provider.isInitialized(identifier)) {
914
- const dcInstance = provider.getImmediate({ identifier });
915
- const options = provider.getOptions(identifier);
916
- const optionsValid = Object.keys(options).length > 0;
975
+ var dcInstance = provider.getImmediate({ identifier: identifier });
976
+ var options = provider.getOptions(identifier);
977
+ var optionsValid = Object.keys(options).length > 0;
917
978
  if (optionsValid) {
918
979
  logDebug('Re-using cached instance');
919
980
  return dcInstance;
@@ -934,13 +995,13 @@ function getDataConnect(appOrOptions, optionalOptions) {
934
995
  * @internal
935
996
  */
936
997
  function validateDCOptions(dcOptions) {
937
- const fields = ['connector', 'location', 'service'];
998
+ var fields = ['connector', 'location', 'service'];
938
999
  if (!dcOptions) {
939
1000
  throw new DataConnectError(Code.INVALID_ARGUMENT, 'DC Option Required');
940
1001
  }
941
- fields.forEach(field => {
1002
+ fields.forEach(function (field) {
942
1003
  if (dcOptions[field] === null || dcOptions[field] === undefined) {
943
- throw new DataConnectError(Code.INVALID_ARGUMENT, `${field} Required`);
1004
+ throw new DataConnectError(Code.INVALID_ARGUMENT, "".concat(field, " Required"));
944
1005
  }
945
1006
  });
946
1007
  return true;
@@ -955,36 +1016,21 @@ function terminate(dataConnect) {
955
1016
  // TODO(mtewani): Stop pending tasks
956
1017
  }
957
1018
 
958
- /**
959
- * @license
960
- * Copyright 2024 Google LLC
961
- *
962
- * Licensed under the Apache License, Version 2.0 (the "License");
963
- * you may not use this file except in compliance with the License.
964
- * You may obtain a copy of the License at
965
- *
966
- * http://www.apache.org/licenses/LICENSE-2.0
967
- *
968
- * Unless required by applicable law or agreed to in writing, software
969
- * distributed under the License is distributed on an "AS IS" BASIS,
970
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
971
- * See the License for the specific language governing permissions and
972
- * limitations under the License.
973
- */
974
1019
  function registerDataConnect(variant) {
975
1020
  setSDKVersion(SDK_VERSION$1);
976
- _registerComponent(new Component('data-connect', (container, { instanceIdentifier: settings, options }) => {
977
- const app = container.getProvider('app').getImmediate();
978
- const authProvider = container.getProvider('auth-internal');
979
- const appCheckProvider = container.getProvider('app-check-internal');
980
- let newOpts = options;
1021
+ _registerComponent(new Component('data-connect', function (container, _a) {
1022
+ var settings = _a.instanceIdentifier, options = _a.options;
1023
+ var app = container.getProvider('app').getImmediate();
1024
+ var authProvider = container.getProvider('auth-internal');
1025
+ var appCheckProvider = container.getProvider('app-check-internal');
1026
+ var newOpts = options;
981
1027
  if (settings) {
982
1028
  newOpts = JSON.parse(settings);
983
1029
  }
984
1030
  if (!app.options.projectId) {
985
1031
  throw new DataConnectError(Code.INVALID_ARGUMENT, 'Project ID must be provided. Did you pass in a proper projectId to initializeApp?');
986
1032
  }
987
- return new DataConnect(app, Object.assign(Object.assign({}, newOpts), { projectId: app.options.projectId }), authProvider, appCheckProvider);
1033
+ return new DataConnect(app, __assign(__assign({}, newOpts), { projectId: app.options.projectId }), authProvider, appCheckProvider);
988
1034
  }, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
989
1035
  registerVersion(name, version, variant);
990
1036
  // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
@@ -1039,7 +1085,7 @@ function queryRef(dcInstance, queryName, variables, initialCache) {
1039
1085
  * @returns `QueryRef`
1040
1086
  */
1041
1087
  function toQueryRef(serializedRef) {
1042
- const { refInfo: { name, variables, connectorConfig } } = serializedRef;
1088
+ var _a = serializedRef.refInfo, name = _a.name, variables = _a.variables, connectorConfig = _a.connectorConfig;
1043
1089
  return queryRef(getDataConnect(connectorConfig), name, variables);
1044
1090
  }
1045
1091
 
@@ -1070,8 +1116,8 @@ function toQueryRef(serializedRef) {
1070
1116
  * @internal
1071
1117
  */
1072
1118
  function validateArgs(connectorConfig, dcOrVars, vars, validateVars) {
1073
- let dcInstance;
1074
- let realVars;
1119
+ var dcInstance;
1120
+ var realVars;
1075
1121
  if (dcOrVars && 'enableEmulator' in dcOrVars) {
1076
1122
  dcInstance = dcOrVars;
1077
1123
  realVars = vars;
@@ -1111,22 +1157,22 @@ function validateArgs(connectorConfig, dcOrVars, vars, validateVars) {
1111
1157
  * @returns `SubscriptionOptions`
1112
1158
  */
1113
1159
  function subscribe(queryRefOrSerializedResult, observerOrOnNext, onError, onComplete) {
1114
- let ref;
1115
- let initialCache;
1160
+ var ref;
1161
+ var initialCache;
1116
1162
  if ('refInfo' in queryRefOrSerializedResult) {
1117
- const serializedRef = queryRefOrSerializedResult;
1118
- const { data, source, fetchTime } = serializedRef;
1163
+ var serializedRef = queryRefOrSerializedResult;
1164
+ var data = serializedRef.data, source = serializedRef.source, fetchTime = serializedRef.fetchTime;
1119
1165
  initialCache = {
1120
- data,
1121
- source,
1122
- fetchTime
1166
+ data: data,
1167
+ source: source,
1168
+ fetchTime: fetchTime
1123
1169
  };
1124
1170
  ref = toQueryRef(serializedRef);
1125
1171
  }
1126
1172
  else {
1127
1173
  ref = queryRefOrSerializedResult;
1128
1174
  }
1129
- let onResult = undefined;
1175
+ var onResult = undefined;
1130
1176
  if (typeof observerOrOnNext === 'function') {
1131
1177
  onResult = observerOrOnNext;
1132
1178
  }