@depup/firebase__functions 0.13.2-depup.0

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.
@@ -0,0 +1,978 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var app = require('@firebase/app');
6
+ var util = require('@firebase/util');
7
+ var component = require('@firebase/component');
8
+
9
+ /**
10
+ * @license
11
+ * Copyright 2017 Google LLC
12
+ *
13
+ * Licensed under the Apache License, Version 2.0 (the "License");
14
+ * you may not use this file except in compliance with the License.
15
+ * You may obtain a copy of the License at
16
+ *
17
+ * http://www.apache.org/licenses/LICENSE-2.0
18
+ *
19
+ * Unless required by applicable law or agreed to in writing, software
20
+ * distributed under the License is distributed on an "AS IS" BASIS,
21
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
22
+ * See the License for the specific language governing permissions and
23
+ * limitations under the License.
24
+ */
25
+ const LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';
26
+ const UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';
27
+ function mapValues(
28
+ // { [k: string]: unknown } is no longer a wildcard assignment target after typescript 3.5
29
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
30
+ o, f) {
31
+ const result = {};
32
+ for (const key in o) {
33
+ if (o.hasOwnProperty(key)) {
34
+ result[key] = f(o[key]);
35
+ }
36
+ }
37
+ return result;
38
+ }
39
+ /**
40
+ * Takes data and encodes it in a JSON-friendly way, such that types such as
41
+ * Date are preserved.
42
+ * @internal
43
+ * @param data - Data to encode.
44
+ */
45
+ function encode(data) {
46
+ if (data == null) {
47
+ return null;
48
+ }
49
+ if (data instanceof Number) {
50
+ data = data.valueOf();
51
+ }
52
+ if (typeof data === 'number' && isFinite(data)) {
53
+ // Any number in JS is safe to put directly in JSON and parse as a double
54
+ // without any loss of precision.
55
+ return data;
56
+ }
57
+ if (data === true || data === false) {
58
+ return data;
59
+ }
60
+ if (Object.prototype.toString.call(data) === '[object String]') {
61
+ return data;
62
+ }
63
+ if (data instanceof Date) {
64
+ return data.toISOString();
65
+ }
66
+ if (Array.isArray(data)) {
67
+ return data.map(x => encode(x));
68
+ }
69
+ if (typeof data === 'function' || typeof data === 'object') {
70
+ return mapValues(data, x => encode(x));
71
+ }
72
+ // If we got this far, the data is not encodable.
73
+ throw new Error('Data cannot be encoded in JSON: ' + data);
74
+ }
75
+ /**
76
+ * Takes data that's been encoded in a JSON-friendly form and returns a form
77
+ * with richer datatypes, such as Dates, etc.
78
+ * @internal
79
+ * @param json - JSON to convert.
80
+ */
81
+ function decode(json) {
82
+ if (json == null) {
83
+ return json;
84
+ }
85
+ if (json['@type']) {
86
+ switch (json['@type']) {
87
+ case LONG_TYPE:
88
+ // Fall through and handle this the same as unsigned.
89
+ case UNSIGNED_LONG_TYPE: {
90
+ // Technically, this could work return a valid number for malformed
91
+ // data if there was a number followed by garbage. But it's just not
92
+ // worth all the extra code to detect that case.
93
+ const value = Number(json['value']);
94
+ if (isNaN(value)) {
95
+ throw new Error('Data cannot be decoded from JSON: ' + json);
96
+ }
97
+ return value;
98
+ }
99
+ default: {
100
+ throw new Error('Data cannot be decoded from JSON: ' + json);
101
+ }
102
+ }
103
+ }
104
+ if (Array.isArray(json)) {
105
+ return json.map(x => decode(x));
106
+ }
107
+ if (typeof json === 'function' || typeof json === 'object') {
108
+ return mapValues(json, x => decode(x));
109
+ }
110
+ // Anything else is safe to return.
111
+ return json;
112
+ }
113
+
114
+ /**
115
+ * @license
116
+ * Copyright 2020 Google LLC
117
+ *
118
+ * Licensed under the Apache License, Version 2.0 (the "License");
119
+ * you may not use this file except in compliance with the License.
120
+ * You may obtain a copy of the License at
121
+ *
122
+ * http://www.apache.org/licenses/LICENSE-2.0
123
+ *
124
+ * Unless required by applicable law or agreed to in writing, software
125
+ * distributed under the License is distributed on an "AS IS" BASIS,
126
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
127
+ * See the License for the specific language governing permissions and
128
+ * limitations under the License.
129
+ */
130
+ /**
131
+ * Type constant for Firebase Functions.
132
+ */
133
+ const FUNCTIONS_TYPE = 'functions';
134
+
135
+ /**
136
+ * @license
137
+ * Copyright 2017 Google LLC
138
+ *
139
+ * Licensed under the Apache License, Version 2.0 (the "License");
140
+ * you may not use this file except in compliance with the License.
141
+ * You may obtain a copy of the License at
142
+ *
143
+ * http://www.apache.org/licenses/LICENSE-2.0
144
+ *
145
+ * Unless required by applicable law or agreed to in writing, software
146
+ * distributed under the License is distributed on an "AS IS" BASIS,
147
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
148
+ * See the License for the specific language governing permissions and
149
+ * limitations under the License.
150
+ */
151
+ /**
152
+ * Standard error codes for different ways a request can fail, as defined by:
153
+ * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
154
+ *
155
+ * This map is used primarily to convert from a backend error code string to
156
+ * a client SDK error code string, and make sure it's in the supported set.
157
+ */
158
+ const errorCodeMap = {
159
+ OK: 'ok',
160
+ CANCELLED: 'cancelled',
161
+ UNKNOWN: 'unknown',
162
+ INVALID_ARGUMENT: 'invalid-argument',
163
+ DEADLINE_EXCEEDED: 'deadline-exceeded',
164
+ NOT_FOUND: 'not-found',
165
+ ALREADY_EXISTS: 'already-exists',
166
+ PERMISSION_DENIED: 'permission-denied',
167
+ UNAUTHENTICATED: 'unauthenticated',
168
+ RESOURCE_EXHAUSTED: 'resource-exhausted',
169
+ FAILED_PRECONDITION: 'failed-precondition',
170
+ ABORTED: 'aborted',
171
+ OUT_OF_RANGE: 'out-of-range',
172
+ UNIMPLEMENTED: 'unimplemented',
173
+ INTERNAL: 'internal',
174
+ UNAVAILABLE: 'unavailable',
175
+ DATA_LOSS: 'data-loss'
176
+ };
177
+ /**
178
+ * An error returned by the Firebase Functions client SDK.
179
+ *
180
+ * See {@link FunctionsErrorCode} for full documentation of codes.
181
+ *
182
+ * @public
183
+ */
184
+ class FunctionsError extends util.FirebaseError {
185
+ /**
186
+ * Constructs a new instance of the `FunctionsError` class.
187
+ */
188
+ constructor(
189
+ /**
190
+ * A standard error code that will be returned to the client. This also
191
+ * determines the HTTP status code of the response, as defined in code.proto.
192
+ */
193
+ code, message,
194
+ /**
195
+ * Additional details to be converted to JSON and included in the error response.
196
+ */
197
+ details) {
198
+ super(`${FUNCTIONS_TYPE}/${code}`, message || '');
199
+ this.details = details;
200
+ // Since the FirebaseError constructor sets the prototype of `this` to FirebaseError.prototype,
201
+ // we also have to do it in all subclasses to allow for correct `instanceof` checks.
202
+ Object.setPrototypeOf(this, FunctionsError.prototype);
203
+ }
204
+ }
205
+ /**
206
+ * Takes an HTTP status code and returns the corresponding ErrorCode.
207
+ * This is the standard HTTP status code -> error mapping defined in:
208
+ * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
209
+ *
210
+ * @param status An HTTP status code.
211
+ * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.
212
+ */
213
+ function codeForHTTPStatus(status) {
214
+ // Make sure any successful status is OK.
215
+ if (status >= 200 && status < 300) {
216
+ return 'ok';
217
+ }
218
+ switch (status) {
219
+ case 0:
220
+ // This can happen if the server returns 500.
221
+ return 'internal';
222
+ case 400:
223
+ return 'invalid-argument';
224
+ case 401:
225
+ return 'unauthenticated';
226
+ case 403:
227
+ return 'permission-denied';
228
+ case 404:
229
+ return 'not-found';
230
+ case 409:
231
+ return 'aborted';
232
+ case 429:
233
+ return 'resource-exhausted';
234
+ case 499:
235
+ return 'cancelled';
236
+ case 500:
237
+ return 'internal';
238
+ case 501:
239
+ return 'unimplemented';
240
+ case 503:
241
+ return 'unavailable';
242
+ case 504:
243
+ return 'deadline-exceeded';
244
+ }
245
+ return 'unknown';
246
+ }
247
+ /**
248
+ * Takes an HTTP response and returns the corresponding Error, if any.
249
+ */
250
+ function _errorForResponse(status, bodyJSON) {
251
+ let code = codeForHTTPStatus(status);
252
+ // Start with reasonable defaults from the status code.
253
+ let description = code;
254
+ let details = undefined;
255
+ // Then look through the body for explicit details.
256
+ try {
257
+ const errorJSON = bodyJSON && bodyJSON.error;
258
+ if (errorJSON) {
259
+ const status = errorJSON.status;
260
+ if (typeof status === 'string') {
261
+ if (!errorCodeMap[status]) {
262
+ // They must've included an unknown error code in the body.
263
+ return new FunctionsError('internal', 'internal');
264
+ }
265
+ code = errorCodeMap[status];
266
+ // TODO(klimt): Add better default descriptions for error enums.
267
+ // The default description needs to be updated for the new code.
268
+ description = status;
269
+ }
270
+ const message = errorJSON.message;
271
+ if (typeof message === 'string') {
272
+ description = message;
273
+ }
274
+ details = errorJSON.details;
275
+ if (details !== undefined) {
276
+ details = decode(details);
277
+ }
278
+ }
279
+ }
280
+ catch (e) {
281
+ // If we couldn't parse explicit error data, that's fine.
282
+ }
283
+ if (code === 'ok') {
284
+ // Technically, there's an edge case where a developer could explicitly
285
+ // return an error code of OK, and we will treat it as success, but that
286
+ // seems reasonable.
287
+ return null;
288
+ }
289
+ return new FunctionsError(code, description, details);
290
+ }
291
+
292
+ /**
293
+ * @license
294
+ * Copyright 2017 Google LLC
295
+ *
296
+ * Licensed under the Apache License, Version 2.0 (the "License");
297
+ * you may not use this file except in compliance with the License.
298
+ * You may obtain a copy of the License at
299
+ *
300
+ * http://www.apache.org/licenses/LICENSE-2.0
301
+ *
302
+ * Unless required by applicable law or agreed to in writing, software
303
+ * distributed under the License is distributed on an "AS IS" BASIS,
304
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
305
+ * See the License for the specific language governing permissions and
306
+ * limitations under the License.
307
+ */
308
+ /**
309
+ * Helper class to get metadata that should be included with a function call.
310
+ * @internal
311
+ */
312
+ class ContextProvider {
313
+ constructor(app$1, authProvider, messagingProvider, appCheckProvider) {
314
+ this.app = app$1;
315
+ this.auth = null;
316
+ this.messaging = null;
317
+ this.appCheck = null;
318
+ this.serverAppAppCheckToken = null;
319
+ if (app._isFirebaseServerApp(app$1) && app$1.settings.appCheckToken) {
320
+ this.serverAppAppCheckToken = app$1.settings.appCheckToken;
321
+ }
322
+ this.auth = authProvider.getImmediate({ optional: true });
323
+ this.messaging = messagingProvider.getImmediate({
324
+ optional: true
325
+ });
326
+ if (!this.auth) {
327
+ authProvider.get().then(auth => (this.auth = auth), () => {
328
+ /* get() never rejects */
329
+ });
330
+ }
331
+ if (!this.messaging) {
332
+ messagingProvider.get().then(messaging => (this.messaging = messaging), () => {
333
+ /* get() never rejects */
334
+ });
335
+ }
336
+ if (!this.appCheck) {
337
+ appCheckProvider?.get().then(appCheck => (this.appCheck = appCheck), () => {
338
+ /* get() never rejects */
339
+ });
340
+ }
341
+ }
342
+ async getAuthToken() {
343
+ if (!this.auth) {
344
+ return undefined;
345
+ }
346
+ try {
347
+ const token = await this.auth.getToken();
348
+ return token?.accessToken;
349
+ }
350
+ catch (e) {
351
+ // If there's any error when trying to get the auth token, leave it off.
352
+ return undefined;
353
+ }
354
+ }
355
+ async getMessagingToken() {
356
+ if (!this.messaging ||
357
+ !('Notification' in self) ||
358
+ Notification.permission !== 'granted') {
359
+ return undefined;
360
+ }
361
+ try {
362
+ return await this.messaging.getToken();
363
+ }
364
+ catch (e) {
365
+ // We don't warn on this, because it usually means messaging isn't set up.
366
+ // console.warn('Failed to retrieve instance id token.', e);
367
+ // If there's any error when trying to get the token, leave it off.
368
+ return undefined;
369
+ }
370
+ }
371
+ async getAppCheckToken(limitedUseAppCheckTokens) {
372
+ if (this.serverAppAppCheckToken) {
373
+ return this.serverAppAppCheckToken;
374
+ }
375
+ if (this.appCheck) {
376
+ const result = limitedUseAppCheckTokens
377
+ ? await this.appCheck.getLimitedUseToken()
378
+ : await this.appCheck.getToken();
379
+ if (result.error) {
380
+ // Do not send the App Check header to the functions endpoint if
381
+ // there was an error from the App Check exchange endpoint. The App
382
+ // Check SDK will already have logged the error to console.
383
+ return null;
384
+ }
385
+ return result.token;
386
+ }
387
+ return null;
388
+ }
389
+ async getContext(limitedUseAppCheckTokens) {
390
+ const authToken = await this.getAuthToken();
391
+ const messagingToken = await this.getMessagingToken();
392
+ const appCheckToken = await this.getAppCheckToken(limitedUseAppCheckTokens);
393
+ return { authToken, messagingToken, appCheckToken };
394
+ }
395
+ }
396
+
397
+ /**
398
+ * @license
399
+ * Copyright 2017 Google LLC
400
+ *
401
+ * Licensed under the Apache License, Version 2.0 (the "License");
402
+ * you may not use this file except in compliance with the License.
403
+ * You may obtain a copy of the License at
404
+ *
405
+ * http://www.apache.org/licenses/LICENSE-2.0
406
+ *
407
+ * Unless required by applicable law or agreed to in writing, software
408
+ * distributed under the License is distributed on an "AS IS" BASIS,
409
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
410
+ * See the License for the specific language governing permissions and
411
+ * limitations under the License.
412
+ */
413
+ const DEFAULT_REGION = 'us-central1';
414
+ const responseLineRE = /^data: (.*?)(?:\n|$)/;
415
+ /**
416
+ * Returns a Promise that will be rejected after the given duration.
417
+ * The error will be of type FunctionsError.
418
+ *
419
+ * @param millis Number of milliseconds to wait before rejecting.
420
+ */
421
+ function failAfter(millis) {
422
+ // Node timers and browser timers are fundamentally incompatible, but we
423
+ // don't care about the value here
424
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
425
+ let timer = null;
426
+ return {
427
+ promise: new Promise((_, reject) => {
428
+ timer = setTimeout(() => {
429
+ reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));
430
+ }, millis);
431
+ }),
432
+ cancel: () => {
433
+ if (timer) {
434
+ clearTimeout(timer);
435
+ }
436
+ }
437
+ };
438
+ }
439
+ /**
440
+ * The main class for the Firebase Functions SDK.
441
+ * @internal
442
+ */
443
+ class FunctionsService {
444
+ /**
445
+ * Creates a new Functions service for the given app.
446
+ * @param app - The FirebaseApp to use.
447
+ */
448
+ constructor(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain = DEFAULT_REGION, fetchImpl = (...args) => fetch(...args)) {
449
+ this.app = app;
450
+ this.fetchImpl = fetchImpl;
451
+ this.emulatorOrigin = null;
452
+ this.contextProvider = new ContextProvider(app, authProvider, messagingProvider, appCheckProvider);
453
+ // Cancels all ongoing requests when resolved.
454
+ this.cancelAllRequests = new Promise(resolve => {
455
+ this.deleteService = () => {
456
+ return Promise.resolve(resolve());
457
+ };
458
+ });
459
+ // Resolve the region or custom domain overload by attempting to parse it.
460
+ try {
461
+ const url = new URL(regionOrCustomDomain);
462
+ this.customDomain =
463
+ url.origin + (url.pathname === '/' ? '' : url.pathname);
464
+ this.region = DEFAULT_REGION;
465
+ }
466
+ catch (e) {
467
+ this.customDomain = null;
468
+ this.region = regionOrCustomDomain;
469
+ }
470
+ }
471
+ _delete() {
472
+ return this.deleteService();
473
+ }
474
+ /**
475
+ * Returns the URL for a callable with the given name.
476
+ * @param name - The name of the callable.
477
+ * @internal
478
+ */
479
+ _url(name) {
480
+ const projectId = this.app.options.projectId;
481
+ if (this.emulatorOrigin !== null) {
482
+ const origin = this.emulatorOrigin;
483
+ return `${origin}/${projectId}/${this.region}/${name}`;
484
+ }
485
+ if (this.customDomain !== null) {
486
+ return `${this.customDomain}/${name}`;
487
+ }
488
+ return `https://${this.region}-${projectId}.cloudfunctions.net/${name}`;
489
+ }
490
+ }
491
+ /**
492
+ * Modify this instance to communicate with the Cloud Functions emulator.
493
+ *
494
+ * Note: this must be called before this instance has been used to do any operations.
495
+ *
496
+ * @param host The emulator host (ex: localhost)
497
+ * @param port The emulator port (ex: 5001)
498
+ * @public
499
+ */
500
+ function connectFunctionsEmulator$1(functionsInstance, host, port) {
501
+ const useSsl = util.isCloudWorkstation(host);
502
+ functionsInstance.emulatorOrigin = `http${useSsl ? 's' : ''}://${host}:${port}`;
503
+ // Workaround to get cookies in Firebase Studio
504
+ if (useSsl) {
505
+ void util.pingServer(functionsInstance.emulatorOrigin + '/backends');
506
+ util.updateEmulatorBanner('Functions', true);
507
+ }
508
+ }
509
+ /**
510
+ * Returns a reference to the callable https trigger with the given name.
511
+ * @param name - The name of the trigger.
512
+ * @public
513
+ */
514
+ function httpsCallable$1(functionsInstance, name, options) {
515
+ const callable = (data) => {
516
+ return call(functionsInstance, name, data, options || {});
517
+ };
518
+ callable.stream = (data, options) => {
519
+ return stream(functionsInstance, name, data, options);
520
+ };
521
+ return callable;
522
+ }
523
+ /**
524
+ * Returns a reference to the callable https trigger with the given url.
525
+ * @param url - The url of the trigger.
526
+ * @public
527
+ */
528
+ function httpsCallableFromURL$1(functionsInstance, url, options) {
529
+ const callable = (data) => {
530
+ return callAtURL(functionsInstance, url, data, options || {});
531
+ };
532
+ callable.stream = (data, options) => {
533
+ return streamAtURL(functionsInstance, url, data, options || {});
534
+ };
535
+ return callable;
536
+ }
537
+ function getCredentials(functionsInstance) {
538
+ return functionsInstance.emulatorOrigin &&
539
+ util.isCloudWorkstation(functionsInstance.emulatorOrigin)
540
+ ? 'include'
541
+ : undefined;
542
+ }
543
+ /**
544
+ * Does an HTTP POST and returns the completed response.
545
+ * @param url The url to post to.
546
+ * @param body The JSON body of the post.
547
+ * @param headers The HTTP headers to include in the request.
548
+ * @param functionsInstance functions instance that is calling postJSON
549
+ * @return A Promise that will succeed when the request finishes.
550
+ */
551
+ async function postJSON(url, body, headers, fetchImpl, functionsInstance) {
552
+ headers['Content-Type'] = 'application/json';
553
+ let response;
554
+ try {
555
+ response = await fetchImpl(url, {
556
+ method: 'POST',
557
+ body: JSON.stringify(body),
558
+ headers,
559
+ credentials: getCredentials(functionsInstance)
560
+ });
561
+ }
562
+ catch (e) {
563
+ // This could be an unhandled error on the backend, or it could be a
564
+ // network error. There's no way to know, since an unhandled error on the
565
+ // backend will fail to set the proper CORS header, and thus will be
566
+ // treated as a network error by fetch.
567
+ return {
568
+ status: 0,
569
+ json: null
570
+ };
571
+ }
572
+ let json = null;
573
+ try {
574
+ json = await response.json();
575
+ }
576
+ catch (e) {
577
+ // If we fail to parse JSON, it will fail the same as an empty body.
578
+ }
579
+ return {
580
+ status: response.status,
581
+ json
582
+ };
583
+ }
584
+ /**
585
+ * Creates authorization headers for Firebase Functions requests.
586
+ * @param functionsInstance The Firebase Functions service instance.
587
+ * @param options Options for the callable function, including AppCheck token settings.
588
+ * @return A Promise that resolves a headers map to include in outgoing fetch request.
589
+ */
590
+ async function makeAuthHeaders(functionsInstance, options) {
591
+ const headers = {};
592
+ const context = await functionsInstance.contextProvider.getContext(options.limitedUseAppCheckTokens);
593
+ if (context.authToken) {
594
+ headers['Authorization'] = 'Bearer ' + context.authToken;
595
+ }
596
+ if (context.messagingToken) {
597
+ headers['Firebase-Instance-ID-Token'] = context.messagingToken;
598
+ }
599
+ if (context.appCheckToken !== null) {
600
+ headers['X-Firebase-AppCheck'] = context.appCheckToken;
601
+ }
602
+ return headers;
603
+ }
604
+ /**
605
+ * Calls a callable function asynchronously and returns the result.
606
+ * @param name The name of the callable trigger.
607
+ * @param data The data to pass as params to the function.
608
+ */
609
+ function call(functionsInstance, name, data, options) {
610
+ const url = functionsInstance._url(name);
611
+ return callAtURL(functionsInstance, url, data, options);
612
+ }
613
+ /**
614
+ * Calls a callable function asynchronously and returns the result.
615
+ * @param url The url of the callable trigger.
616
+ * @param data The data to pass as params to the function.
617
+ */
618
+ async function callAtURL(functionsInstance, url, data, options) {
619
+ // Encode any special types, such as dates, in the input data.
620
+ data = encode(data);
621
+ const body = { data };
622
+ // Add a header for the authToken.
623
+ const headers = await makeAuthHeaders(functionsInstance, options);
624
+ // Default timeout to 70s, but let the options override it.
625
+ const timeout = options.timeout || 70000;
626
+ const failAfterHandle = failAfter(timeout);
627
+ const response = await Promise.race([
628
+ postJSON(url, body, headers, functionsInstance.fetchImpl, functionsInstance),
629
+ failAfterHandle.promise,
630
+ functionsInstance.cancelAllRequests
631
+ ]);
632
+ // Always clear the failAfter timeout
633
+ failAfterHandle.cancel();
634
+ // If service was deleted, interrupted response throws an error.
635
+ if (!response) {
636
+ throw new FunctionsError('cancelled', 'Firebase Functions instance was deleted.');
637
+ }
638
+ // Check for an error status, regardless of http status.
639
+ const error = _errorForResponse(response.status, response.json);
640
+ if (error) {
641
+ throw error;
642
+ }
643
+ if (!response.json) {
644
+ throw new FunctionsError('internal', 'Response is not valid JSON object.');
645
+ }
646
+ let responseData = response.json.data;
647
+ // TODO(klimt): For right now, allow "result" instead of "data", for
648
+ // backwards compatibility.
649
+ if (typeof responseData === 'undefined') {
650
+ responseData = response.json.result;
651
+ }
652
+ if (typeof responseData === 'undefined') {
653
+ // Consider the response malformed.
654
+ throw new FunctionsError('internal', 'Response is missing data field.');
655
+ }
656
+ // Decode any special types, such as dates, in the returned data.
657
+ const decodedData = decode(responseData);
658
+ return { data: decodedData };
659
+ }
660
+ /**
661
+ * Calls a callable function asynchronously and returns a streaming result.
662
+ * @param name The name of the callable trigger.
663
+ * @param data The data to pass as params to the function.
664
+ * @param options Streaming request options.
665
+ */
666
+ function stream(functionsInstance, name, data, options) {
667
+ const url = functionsInstance._url(name);
668
+ return streamAtURL(functionsInstance, url, data, options || {});
669
+ }
670
+ /**
671
+ * Calls a callable function asynchronously and return a streaming result.
672
+ * @param url The url of the callable trigger.
673
+ * @param data The data to pass as params to the function.
674
+ * @param options Streaming request options.
675
+ */
676
+ async function streamAtURL(functionsInstance, url, data, options) {
677
+ // Encode any special types, such as dates, in the input data.
678
+ data = encode(data);
679
+ const body = { data };
680
+ //
681
+ // Add a header for the authToken.
682
+ const headers = await makeAuthHeaders(functionsInstance, options);
683
+ headers['Content-Type'] = 'application/json';
684
+ headers['Accept'] = 'text/event-stream';
685
+ let response;
686
+ try {
687
+ response = await functionsInstance.fetchImpl(url, {
688
+ method: 'POST',
689
+ body: JSON.stringify(body),
690
+ headers,
691
+ signal: options?.signal,
692
+ credentials: getCredentials(functionsInstance)
693
+ });
694
+ }
695
+ catch (e) {
696
+ if (e instanceof Error && e.name === 'AbortError') {
697
+ const error = new FunctionsError('cancelled', 'Request was cancelled.');
698
+ return {
699
+ data: Promise.reject(error),
700
+ stream: {
701
+ [Symbol.asyncIterator]() {
702
+ return {
703
+ next() {
704
+ return Promise.reject(error);
705
+ }
706
+ };
707
+ }
708
+ }
709
+ };
710
+ }
711
+ // This could be an unhandled error on the backend, or it could be a
712
+ // network error. There's no way to know, since an unhandled error on the
713
+ // backend will fail to set the proper CORS header, and thus will be
714
+ // treated as a network error by fetch.
715
+ const error = _errorForResponse(0, null);
716
+ return {
717
+ data: Promise.reject(error),
718
+ // Return an empty async iterator
719
+ stream: {
720
+ [Symbol.asyncIterator]() {
721
+ return {
722
+ next() {
723
+ return Promise.reject(error);
724
+ }
725
+ };
726
+ }
727
+ }
728
+ };
729
+ }
730
+ let resultResolver;
731
+ let resultRejecter;
732
+ const resultPromise = new Promise((resolve, reject) => {
733
+ resultResolver = resolve;
734
+ resultRejecter = reject;
735
+ });
736
+ options?.signal?.addEventListener('abort', () => {
737
+ const error = new FunctionsError('cancelled', 'Request was cancelled.');
738
+ resultRejecter(error);
739
+ });
740
+ const reader = response.body.getReader();
741
+ const rstream = createResponseStream(reader, resultResolver, resultRejecter, options?.signal);
742
+ return {
743
+ stream: {
744
+ [Symbol.asyncIterator]() {
745
+ const rreader = rstream.getReader();
746
+ return {
747
+ async next() {
748
+ const { value, done } = await rreader.read();
749
+ return { value: value, done };
750
+ },
751
+ async return() {
752
+ await rreader.cancel();
753
+ return { done: true, value: undefined };
754
+ }
755
+ };
756
+ }
757
+ },
758
+ data: resultPromise
759
+ };
760
+ }
761
+ /**
762
+ * Creates a ReadableStream that processes a streaming response from a streaming
763
+ * callable function that returns data in server-sent event format.
764
+ *
765
+ * @param reader The underlying reader providing raw response data
766
+ * @param resultResolver Callback to resolve the final result when received
767
+ * @param resultRejecter Callback to reject with an error if encountered
768
+ * @param signal Optional AbortSignal to cancel the stream processing
769
+ * @returns A ReadableStream that emits decoded messages from the response
770
+ *
771
+ * The returned ReadableStream:
772
+ * 1. Emits individual messages when "message" data is received
773
+ * 2. Resolves with the final result when a "result" message is received
774
+ * 3. Rejects with an error if an "error" message is received
775
+ */
776
+ function createResponseStream(reader, resultResolver, resultRejecter, signal) {
777
+ const processLine = (line, controller) => {
778
+ const match = line.match(responseLineRE);
779
+ // ignore all other lines (newline, comments, etc.)
780
+ if (!match) {
781
+ return;
782
+ }
783
+ const data = match[1];
784
+ try {
785
+ const jsonData = JSON.parse(data);
786
+ if ('result' in jsonData) {
787
+ resultResolver(decode(jsonData.result));
788
+ return;
789
+ }
790
+ if ('message' in jsonData) {
791
+ controller.enqueue(decode(jsonData.message));
792
+ return;
793
+ }
794
+ if ('error' in jsonData) {
795
+ const error = _errorForResponse(0, jsonData);
796
+ controller.error(error);
797
+ resultRejecter(error);
798
+ return;
799
+ }
800
+ }
801
+ catch (error) {
802
+ if (error instanceof FunctionsError) {
803
+ controller.error(error);
804
+ resultRejecter(error);
805
+ return;
806
+ }
807
+ // ignore other parsing errors
808
+ }
809
+ };
810
+ const decoder = new TextDecoder();
811
+ return new ReadableStream({
812
+ start(controller) {
813
+ let currentText = '';
814
+ return pump();
815
+ async function pump() {
816
+ if (signal?.aborted) {
817
+ const error = new FunctionsError('cancelled', 'Request was cancelled');
818
+ controller.error(error);
819
+ resultRejecter(error);
820
+ return Promise.resolve();
821
+ }
822
+ try {
823
+ const { value, done } = await reader.read();
824
+ if (done) {
825
+ if (currentText.trim()) {
826
+ processLine(currentText.trim(), controller);
827
+ }
828
+ controller.close();
829
+ return;
830
+ }
831
+ if (signal?.aborted) {
832
+ const error = new FunctionsError('cancelled', 'Request was cancelled');
833
+ controller.error(error);
834
+ resultRejecter(error);
835
+ await reader.cancel();
836
+ return;
837
+ }
838
+ currentText += decoder.decode(value, { stream: true });
839
+ const lines = currentText.split('\n');
840
+ currentText = lines.pop() || '';
841
+ for (const line of lines) {
842
+ if (line.trim()) {
843
+ processLine(line.trim(), controller);
844
+ }
845
+ }
846
+ return pump();
847
+ }
848
+ catch (error) {
849
+ const functionsError = error instanceof FunctionsError
850
+ ? error
851
+ : _errorForResponse(0, null);
852
+ controller.error(functionsError);
853
+ resultRejecter(functionsError);
854
+ }
855
+ }
856
+ },
857
+ cancel() {
858
+ return reader.cancel();
859
+ }
860
+ });
861
+ }
862
+
863
+ const name = "@firebase/functions";
864
+ const version = "0.13.2";
865
+
866
+ /**
867
+ * @license
868
+ * Copyright 2019 Google LLC
869
+ *
870
+ * Licensed under the Apache License, Version 2.0 (the "License");
871
+ * you may not use this file except in compliance with the License.
872
+ * You may obtain a copy of the License at
873
+ *
874
+ * http://www.apache.org/licenses/LICENSE-2.0
875
+ *
876
+ * Unless required by applicable law or agreed to in writing, software
877
+ * distributed under the License is distributed on an "AS IS" BASIS,
878
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
879
+ * See the License for the specific language governing permissions and
880
+ * limitations under the License.
881
+ */
882
+ const AUTH_INTERNAL_NAME = 'auth-internal';
883
+ const APP_CHECK_INTERNAL_NAME = 'app-check-internal';
884
+ const MESSAGING_INTERNAL_NAME = 'messaging-internal';
885
+ function registerFunctions(variant) {
886
+ const factory = (container, { instanceIdentifier: regionOrCustomDomain }) => {
887
+ // Dependencies
888
+ const app = container.getProvider('app').getImmediate();
889
+ const authProvider = container.getProvider(AUTH_INTERNAL_NAME);
890
+ const messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);
891
+ const appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);
892
+ // eslint-disable-next-line @typescript-eslint/no-explicit-any
893
+ return new FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain);
894
+ };
895
+ app._registerComponent(new component.Component(FUNCTIONS_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
896
+ app.registerVersion(name, version, variant);
897
+ // BUILD_TARGET will be replaced by values like esm, cjs, etc during the compilation
898
+ app.registerVersion(name, version, 'cjs2020');
899
+ }
900
+
901
+ /**
902
+ * @license
903
+ * Copyright 2020 Google LLC
904
+ *
905
+ * Licensed under the Apache License, Version 2.0 (the "License");
906
+ * you may not use this file except in compliance with the License.
907
+ * You may obtain a copy of the License at
908
+ *
909
+ * http://www.apache.org/licenses/LICENSE-2.0
910
+ *
911
+ * Unless required by applicable law or agreed to in writing, software
912
+ * distributed under the License is distributed on an "AS IS" BASIS,
913
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
914
+ * See the License for the specific language governing permissions and
915
+ * limitations under the License.
916
+ */
917
+ /**
918
+ * Returns a {@link Functions} instance for the given app.
919
+ * @param app - The {@link @firebase/app#FirebaseApp} to use.
920
+ * @param regionOrCustomDomain - one of:
921
+ * a) The region the callable functions are located in (ex: us-central1)
922
+ * b) A custom domain hosting the callable functions (ex: https://mydomain.com)
923
+ * @public
924
+ */
925
+ function getFunctions(app$1 = app.getApp(), regionOrCustomDomain = DEFAULT_REGION) {
926
+ // Dependencies
927
+ const functionsProvider = app._getProvider(util.getModularInstance(app$1), FUNCTIONS_TYPE);
928
+ const functionsInstance = functionsProvider.getImmediate({
929
+ identifier: regionOrCustomDomain
930
+ });
931
+ const emulator = util.getDefaultEmulatorHostnameAndPort('functions');
932
+ if (emulator) {
933
+ connectFunctionsEmulator(functionsInstance, ...emulator);
934
+ }
935
+ return functionsInstance;
936
+ }
937
+ /**
938
+ * Modify this instance to communicate with the Cloud Functions emulator.
939
+ *
940
+ * Note: this must be called before this instance has been used to do any operations.
941
+ *
942
+ * @param host - The emulator host (ex: localhost)
943
+ * @param port - The emulator port (ex: 5001)
944
+ * @public
945
+ */
946
+ function connectFunctionsEmulator(functionsInstance, host, port) {
947
+ connectFunctionsEmulator$1(util.getModularInstance(functionsInstance), host, port);
948
+ }
949
+ /**
950
+ * Returns a reference to the callable HTTPS trigger with the given name.
951
+ * @param name - The name of the trigger.
952
+ * @public
953
+ */
954
+ function httpsCallable(functionsInstance, name, options) {
955
+ return httpsCallable$1(util.getModularInstance(functionsInstance), name, options);
956
+ }
957
+ /**
958
+ * Returns a reference to the callable HTTPS trigger with the specified url.
959
+ * @param url - The url of the trigger.
960
+ * @public
961
+ */
962
+ function httpsCallableFromURL(functionsInstance, url, options) {
963
+ return httpsCallableFromURL$1(util.getModularInstance(functionsInstance), url, options);
964
+ }
965
+
966
+ /**
967
+ * Cloud Functions for Firebase
968
+ *
969
+ * @packageDocumentation
970
+ */
971
+ registerFunctions();
972
+
973
+ exports.FunctionsError = FunctionsError;
974
+ exports.connectFunctionsEmulator = connectFunctionsEmulator;
975
+ exports.getFunctions = getFunctions;
976
+ exports.httpsCallable = httpsCallable;
977
+ exports.httpsCallableFromURL = httpsCallableFromURL;
978
+ //# sourceMappingURL=index.cjs.js.map