@firebase/data-connect 0.1.0-canary.64db19264 → 0.1.0-canary.8fb044e8d

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