@firebase/data-connect 0.1.0 → 0.1.1

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