index.node.cjs.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827
  1. 'use strict';
  2. Object.defineProperty(exports, '__esModule', { value: true });
  3. var app = require('@firebase/app');
  4. var tslib = require('tslib');
  5. var util = require('@firebase/util');
  6. var component = require('@firebase/component');
  7. var nodeFetch = require('node-fetch');
  8. function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
  9. var nodeFetch__default = /*#__PURE__*/_interopDefaultLegacy(nodeFetch);
  10. /**
  11. * @license
  12. * Copyright 2017 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. var LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';
  27. var UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';
  28. function mapValues(
  29. // { [k: string]: unknown } is no longer a wildcard assignment target after typescript 3.5
  30. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  31. o, f) {
  32. var result = {};
  33. for (var key in o) {
  34. if (o.hasOwnProperty(key)) {
  35. result[key] = f(o[key]);
  36. }
  37. }
  38. return result;
  39. }
  40. /**
  41. * Takes data and encodes it in a JSON-friendly way, such that types such as
  42. * Date are preserved.
  43. * @internal
  44. * @param data - Data to encode.
  45. */
  46. function encode(data) {
  47. if (data == null) {
  48. return null;
  49. }
  50. if (data instanceof Number) {
  51. data = data.valueOf();
  52. }
  53. if (typeof data === 'number' && isFinite(data)) {
  54. // Any number in JS is safe to put directly in JSON and parse as a double
  55. // without any loss of precision.
  56. return data;
  57. }
  58. if (data === true || data === false) {
  59. return data;
  60. }
  61. if (Object.prototype.toString.call(data) === '[object String]') {
  62. return data;
  63. }
  64. if (data instanceof Date) {
  65. return data.toISOString();
  66. }
  67. if (Array.isArray(data)) {
  68. return data.map(function (x) { return encode(x); });
  69. }
  70. if (typeof data === 'function' || typeof data === 'object') {
  71. return mapValues(data, function (x) { return encode(x); });
  72. }
  73. // If we got this far, the data is not encodable.
  74. throw new Error('Data cannot be encoded in JSON: ' + data);
  75. }
  76. /**
  77. * Takes data that's been encoded in a JSON-friendly form and returns a form
  78. * with richer datatypes, such as Dates, etc.
  79. * @internal
  80. * @param json - JSON to convert.
  81. */
  82. function decode(json) {
  83. if (json == null) {
  84. return json;
  85. }
  86. if (json['@type']) {
  87. switch (json['@type']) {
  88. case LONG_TYPE:
  89. // Fall through and handle this the same as unsigned.
  90. case UNSIGNED_LONG_TYPE: {
  91. // Technically, this could work return a valid number for malformed
  92. // data if there was a number followed by garbage. But it's just not
  93. // worth all the extra code to detect that case.
  94. var value = Number(json['value']);
  95. if (isNaN(value)) {
  96. throw new Error('Data cannot be decoded from JSON: ' + json);
  97. }
  98. return value;
  99. }
  100. default: {
  101. throw new Error('Data cannot be decoded from JSON: ' + json);
  102. }
  103. }
  104. }
  105. if (Array.isArray(json)) {
  106. return json.map(function (x) { return decode(x); });
  107. }
  108. if (typeof json === 'function' || typeof json === 'object') {
  109. return mapValues(json, function (x) { return decode(x); });
  110. }
  111. // Anything else is safe to return.
  112. return json;
  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. var FUNCTIONS_TYPE = 'functions';
  134. /**
  135. * @license
  136. * Copyright 2017 Google LLC
  137. *
  138. * Licensed under the Apache License, Version 2.0 (the "License");
  139. * you may not use this file except in compliance with the License.
  140. * You may obtain a copy of the License at
  141. *
  142. * http://www.apache.org/licenses/LICENSE-2.0
  143. *
  144. * Unless required by applicable law or agreed to in writing, software
  145. * distributed under the License is distributed on an "AS IS" BASIS,
  146. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  147. * See the License for the specific language governing permissions and
  148. * limitations under the License.
  149. */
  150. /**
  151. * Standard error codes for different ways a request can fail, as defined by:
  152. * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  153. *
  154. * This map is used primarily to convert from a backend error code string to
  155. * a client SDK error code string, and make sure it's in the supported set.
  156. */
  157. var errorCodeMap = {
  158. OK: 'ok',
  159. CANCELLED: 'cancelled',
  160. UNKNOWN: 'unknown',
  161. INVALID_ARGUMENT: 'invalid-argument',
  162. DEADLINE_EXCEEDED: 'deadline-exceeded',
  163. NOT_FOUND: 'not-found',
  164. ALREADY_EXISTS: 'already-exists',
  165. PERMISSION_DENIED: 'permission-denied',
  166. UNAUTHENTICATED: 'unauthenticated',
  167. RESOURCE_EXHAUSTED: 'resource-exhausted',
  168. FAILED_PRECONDITION: 'failed-precondition',
  169. ABORTED: 'aborted',
  170. OUT_OF_RANGE: 'out-of-range',
  171. UNIMPLEMENTED: 'unimplemented',
  172. INTERNAL: 'internal',
  173. UNAVAILABLE: 'unavailable',
  174. DATA_LOSS: 'data-loss'
  175. };
  176. /**
  177. * An explicit error that can be thrown from a handler to send an error to the
  178. * client that called the function.
  179. */
  180. var FunctionsError = /** @class */ (function (_super) {
  181. tslib.__extends(FunctionsError, _super);
  182. function FunctionsError(
  183. /**
  184. * A standard error code that will be returned to the client. This also
  185. * determines the HTTP status code of the response, as defined in code.proto.
  186. */
  187. code, message,
  188. /**
  189. * Extra data to be converted to JSON and included in the error response.
  190. */
  191. details) {
  192. var _this = _super.call(this, "".concat(FUNCTIONS_TYPE, "/").concat(code), message || '') || this;
  193. _this.details = details;
  194. return _this;
  195. }
  196. return FunctionsError;
  197. }(util.FirebaseError));
  198. /**
  199. * Takes an HTTP status code and returns the corresponding ErrorCode.
  200. * This is the standard HTTP status code -> error mapping defined in:
  201. * https://github.com/googleapis/googleapis/blob/master/google/rpc/code.proto
  202. *
  203. * @param status An HTTP status code.
  204. * @return The corresponding ErrorCode, or ErrorCode.UNKNOWN if none.
  205. */
  206. function codeForHTTPStatus(status) {
  207. // Make sure any successful status is OK.
  208. if (status >= 200 && status < 300) {
  209. return 'ok';
  210. }
  211. switch (status) {
  212. case 0:
  213. // This can happen if the server returns 500.
  214. return 'internal';
  215. case 400:
  216. return 'invalid-argument';
  217. case 401:
  218. return 'unauthenticated';
  219. case 403:
  220. return 'permission-denied';
  221. case 404:
  222. return 'not-found';
  223. case 409:
  224. return 'aborted';
  225. case 429:
  226. return 'resource-exhausted';
  227. case 499:
  228. return 'cancelled';
  229. case 500:
  230. return 'internal';
  231. case 501:
  232. return 'unimplemented';
  233. case 503:
  234. return 'unavailable';
  235. case 504:
  236. return 'deadline-exceeded';
  237. }
  238. return 'unknown';
  239. }
  240. /**
  241. * Takes an HTTP response and returns the corresponding Error, if any.
  242. */
  243. function _errorForResponse(status, bodyJSON) {
  244. var code = codeForHTTPStatus(status);
  245. // Start with reasonable defaults from the status code.
  246. var description = code;
  247. var details = undefined;
  248. // Then look through the body for explicit details.
  249. try {
  250. var errorJSON = bodyJSON && bodyJSON.error;
  251. if (errorJSON) {
  252. var status_1 = errorJSON.status;
  253. if (typeof status_1 === 'string') {
  254. if (!errorCodeMap[status_1]) {
  255. // They must've included an unknown error code in the body.
  256. return new FunctionsError('internal', 'internal');
  257. }
  258. code = errorCodeMap[status_1];
  259. // TODO(klimt): Add better default descriptions for error enums.
  260. // The default description needs to be updated for the new code.
  261. description = status_1;
  262. }
  263. var message = errorJSON.message;
  264. if (typeof message === 'string') {
  265. description = message;
  266. }
  267. details = errorJSON.details;
  268. if (details !== undefined) {
  269. details = decode(details);
  270. }
  271. }
  272. }
  273. catch (e) {
  274. // If we couldn't parse explicit error data, that's fine.
  275. }
  276. if (code === 'ok') {
  277. // Technically, there's an edge case where a developer could explicitly
  278. // return an error code of OK, and we will treat it as success, but that
  279. // seems reasonable.
  280. return null;
  281. }
  282. return new FunctionsError(code, description, details);
  283. }
  284. /**
  285. * @license
  286. * Copyright 2017 Google LLC
  287. *
  288. * Licensed under the Apache License, Version 2.0 (the "License");
  289. * you may not use this file except in compliance with the License.
  290. * You may obtain a copy of the License at
  291. *
  292. * http://www.apache.org/licenses/LICENSE-2.0
  293. *
  294. * Unless required by applicable law or agreed to in writing, software
  295. * distributed under the License is distributed on an "AS IS" BASIS,
  296. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  297. * See the License for the specific language governing permissions and
  298. * limitations under the License.
  299. */
  300. /**
  301. * Helper class to get metadata that should be included with a function call.
  302. * @internal
  303. */
  304. var ContextProvider = /** @class */ (function () {
  305. function ContextProvider(authProvider, messagingProvider, appCheckProvider) {
  306. var _this = this;
  307. this.auth = null;
  308. this.messaging = null;
  309. this.appCheck = null;
  310. this.auth = authProvider.getImmediate({ optional: true });
  311. this.messaging = messagingProvider.getImmediate({
  312. optional: true
  313. });
  314. if (!this.auth) {
  315. authProvider.get().then(function (auth) { return (_this.auth = auth); }, function () {
  316. /* get() never rejects */
  317. });
  318. }
  319. if (!this.messaging) {
  320. messagingProvider.get().then(function (messaging) { return (_this.messaging = messaging); }, function () {
  321. /* get() never rejects */
  322. });
  323. }
  324. if (!this.appCheck) {
  325. appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); }, function () {
  326. /* get() never rejects */
  327. });
  328. }
  329. }
  330. ContextProvider.prototype.getAuthToken = function () {
  331. return tslib.__awaiter(this, void 0, void 0, function () {
  332. var token;
  333. return tslib.__generator(this, function (_a) {
  334. switch (_a.label) {
  335. case 0:
  336. if (!this.auth) {
  337. return [2 /*return*/, undefined];
  338. }
  339. _a.label = 1;
  340. case 1:
  341. _a.trys.push([1, 3, , 4]);
  342. return [4 /*yield*/, this.auth.getToken()];
  343. case 2:
  344. token = _a.sent();
  345. return [2 /*return*/, token === null || token === void 0 ? void 0 : token.accessToken];
  346. case 3:
  347. _a.sent();
  348. // If there's any error when trying to get the auth token, leave it off.
  349. return [2 /*return*/, undefined];
  350. case 4: return [2 /*return*/];
  351. }
  352. });
  353. });
  354. };
  355. ContextProvider.prototype.getMessagingToken = function () {
  356. return tslib.__awaiter(this, void 0, void 0, function () {
  357. return tslib.__generator(this, function (_a) {
  358. switch (_a.label) {
  359. case 0:
  360. if (!this.messaging ||
  361. !('Notification' in self) ||
  362. Notification.permission !== 'granted') {
  363. return [2 /*return*/, undefined];
  364. }
  365. _a.label = 1;
  366. case 1:
  367. _a.trys.push([1, 3, , 4]);
  368. return [4 /*yield*/, this.messaging.getToken()];
  369. case 2: return [2 /*return*/, _a.sent()];
  370. case 3:
  371. _a.sent();
  372. // We don't warn on this, because it usually means messaging isn't set up.
  373. // console.warn('Failed to retrieve instance id token.', e);
  374. // If there's any error when trying to get the token, leave it off.
  375. return [2 /*return*/, undefined];
  376. case 4: return [2 /*return*/];
  377. }
  378. });
  379. });
  380. };
  381. ContextProvider.prototype.getAppCheckToken = function (limitedUseAppCheckTokens) {
  382. return tslib.__awaiter(this, void 0, void 0, function () {
  383. var result, _a;
  384. return tslib.__generator(this, function (_b) {
  385. switch (_b.label) {
  386. case 0:
  387. if (!this.appCheck) return [3 /*break*/, 5];
  388. if (!limitedUseAppCheckTokens) return [3 /*break*/, 2];
  389. return [4 /*yield*/, this.appCheck.getLimitedUseToken()];
  390. case 1:
  391. _a = _b.sent();
  392. return [3 /*break*/, 4];
  393. case 2: return [4 /*yield*/, this.appCheck.getToken()];
  394. case 3:
  395. _a = _b.sent();
  396. _b.label = 4;
  397. case 4:
  398. result = _a;
  399. if (result.error) {
  400. // Do not send the App Check header to the functions endpoint if
  401. // there was an error from the App Check exchange endpoint. The App
  402. // Check SDK will already have logged the error to console.
  403. return [2 /*return*/, null];
  404. }
  405. return [2 /*return*/, result.token];
  406. case 5: return [2 /*return*/, null];
  407. }
  408. });
  409. });
  410. };
  411. ContextProvider.prototype.getContext = function (limitedUseAppCheckTokens) {
  412. return tslib.__awaiter(this, void 0, void 0, function () {
  413. var authToken, messagingToken, appCheckToken;
  414. return tslib.__generator(this, function (_a) {
  415. switch (_a.label) {
  416. case 0: return [4 /*yield*/, this.getAuthToken()];
  417. case 1:
  418. authToken = _a.sent();
  419. return [4 /*yield*/, this.getMessagingToken()];
  420. case 2:
  421. messagingToken = _a.sent();
  422. return [4 /*yield*/, this.getAppCheckToken(limitedUseAppCheckTokens)];
  423. case 3:
  424. appCheckToken = _a.sent();
  425. return [2 /*return*/, { authToken: authToken, messagingToken: messagingToken, appCheckToken: appCheckToken }];
  426. }
  427. });
  428. });
  429. };
  430. return ContextProvider;
  431. }());
  432. /**
  433. * @license
  434. * Copyright 2017 Google LLC
  435. *
  436. * Licensed under the Apache License, Version 2.0 (the "License");
  437. * you may not use this file except in compliance with the License.
  438. * You may obtain a copy of the License at
  439. *
  440. * http://www.apache.org/licenses/LICENSE-2.0
  441. *
  442. * Unless required by applicable law or agreed to in writing, software
  443. * distributed under the License is distributed on an "AS IS" BASIS,
  444. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  445. * See the License for the specific language governing permissions and
  446. * limitations under the License.
  447. */
  448. var DEFAULT_REGION = 'us-central1';
  449. /**
  450. * Returns a Promise that will be rejected after the given duration.
  451. * The error will be of type FunctionsError.
  452. *
  453. * @param millis Number of milliseconds to wait before rejecting.
  454. */
  455. function failAfter(millis) {
  456. // Node timers and browser timers are fundamentally incompatible, but we
  457. // don't care about the value here
  458. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  459. var timer = null;
  460. return {
  461. promise: new Promise(function (_, reject) {
  462. timer = setTimeout(function () {
  463. reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));
  464. }, millis);
  465. }),
  466. cancel: function () {
  467. if (timer) {
  468. clearTimeout(timer);
  469. }
  470. }
  471. };
  472. }
  473. /**
  474. * The main class for the Firebase Functions SDK.
  475. * @internal
  476. */
  477. var FunctionsService = /** @class */ (function () {
  478. /**
  479. * Creates a new Functions service for the given app.
  480. * @param app - The FirebaseApp to use.
  481. */
  482. function FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl) {
  483. if (regionOrCustomDomain === void 0) { regionOrCustomDomain = DEFAULT_REGION; }
  484. var _this = this;
  485. this.app = app;
  486. this.fetchImpl = fetchImpl;
  487. this.emulatorOrigin = null;
  488. this.contextProvider = new ContextProvider(authProvider, messagingProvider, appCheckProvider);
  489. // Cancels all ongoing requests when resolved.
  490. this.cancelAllRequests = new Promise(function (resolve) {
  491. _this.deleteService = function () {
  492. return Promise.resolve(resolve());
  493. };
  494. });
  495. // Resolve the region or custom domain overload by attempting to parse it.
  496. try {
  497. var url = new URL(regionOrCustomDomain);
  498. this.customDomain = url.origin;
  499. this.region = DEFAULT_REGION;
  500. }
  501. catch (e) {
  502. this.customDomain = null;
  503. this.region = regionOrCustomDomain;
  504. }
  505. }
  506. FunctionsService.prototype._delete = function () {
  507. return this.deleteService();
  508. };
  509. /**
  510. * Returns the URL for a callable with the given name.
  511. * @param name - The name of the callable.
  512. * @internal
  513. */
  514. FunctionsService.prototype._url = function (name) {
  515. var projectId = this.app.options.projectId;
  516. if (this.emulatorOrigin !== null) {
  517. var origin_1 = this.emulatorOrigin;
  518. return "".concat(origin_1, "/").concat(projectId, "/").concat(this.region, "/").concat(name);
  519. }
  520. if (this.customDomain !== null) {
  521. return "".concat(this.customDomain, "/").concat(name);
  522. }
  523. return "https://".concat(this.region, "-").concat(projectId, ".cloudfunctions.net/").concat(name);
  524. };
  525. return FunctionsService;
  526. }());
  527. /**
  528. * Modify this instance to communicate with the Cloud Functions emulator.
  529. *
  530. * Note: this must be called before this instance has been used to do any operations.
  531. *
  532. * @param host The emulator host (ex: localhost)
  533. * @param port The emulator port (ex: 5001)
  534. * @public
  535. */
  536. function connectFunctionsEmulator$1(functionsInstance, host, port) {
  537. functionsInstance.emulatorOrigin = "http://".concat(host, ":").concat(port);
  538. }
  539. /**
  540. * Returns a reference to the callable https trigger with the given name.
  541. * @param name - The name of the trigger.
  542. * @public
  543. */
  544. function httpsCallable$1(functionsInstance, name, options) {
  545. return (function (data) {
  546. return call(functionsInstance, name, data, options || {});
  547. });
  548. }
  549. /**
  550. * Returns a reference to the callable https trigger with the given url.
  551. * @param url - The url of the trigger.
  552. * @public
  553. */
  554. function httpsCallableFromURL$1(functionsInstance, url, options) {
  555. return (function (data) {
  556. return callAtURL(functionsInstance, url, data, options || {});
  557. });
  558. }
  559. /**
  560. * Does an HTTP POST and returns the completed response.
  561. * @param url The url to post to.
  562. * @param body The JSON body of the post.
  563. * @param headers The HTTP headers to include in the request.
  564. * @return A Promise that will succeed when the request finishes.
  565. */
  566. function postJSON(url, body, headers, fetchImpl) {
  567. return tslib.__awaiter(this, void 0, void 0, function () {
  568. var response, json;
  569. return tslib.__generator(this, function (_a) {
  570. switch (_a.label) {
  571. case 0:
  572. headers['Content-Type'] = 'application/json';
  573. _a.label = 1;
  574. case 1:
  575. _a.trys.push([1, 3, , 4]);
  576. return [4 /*yield*/, fetchImpl(url, {
  577. method: 'POST',
  578. body: JSON.stringify(body),
  579. headers: headers
  580. })];
  581. case 2:
  582. response = _a.sent();
  583. return [3 /*break*/, 4];
  584. case 3:
  585. _a.sent();
  586. // This could be an unhandled error on the backend, or it could be a
  587. // network error. There's no way to know, since an unhandled error on the
  588. // backend will fail to set the proper CORS header, and thus will be
  589. // treated as a network error by fetch.
  590. return [2 /*return*/, {
  591. status: 0,
  592. json: null
  593. }];
  594. case 4:
  595. json = null;
  596. _a.label = 5;
  597. case 5:
  598. _a.trys.push([5, 7, , 8]);
  599. return [4 /*yield*/, response.json()];
  600. case 6:
  601. json = _a.sent();
  602. return [3 /*break*/, 8];
  603. case 7:
  604. _a.sent();
  605. return [3 /*break*/, 8];
  606. case 8: return [2 /*return*/, {
  607. status: response.status,
  608. json: json
  609. }];
  610. }
  611. });
  612. });
  613. }
  614. /**
  615. * Calls a callable function asynchronously and returns the result.
  616. * @param name The name of the callable trigger.
  617. * @param data The data to pass as params to the function.s
  618. */
  619. function call(functionsInstance, name, data, options) {
  620. var url = functionsInstance._url(name);
  621. return callAtURL(functionsInstance, url, data, options);
  622. }
  623. /**
  624. * Calls a callable function asynchronously and returns the result.
  625. * @param url The url of the callable trigger.
  626. * @param data The data to pass as params to the function.s
  627. */
  628. function callAtURL(functionsInstance, url, data, options) {
  629. return tslib.__awaiter(this, void 0, void 0, function () {
  630. var body, headers, context, timeout, failAfterHandle, response, error, responseData, decodedData;
  631. return tslib.__generator(this, function (_a) {
  632. switch (_a.label) {
  633. case 0:
  634. // Encode any special types, such as dates, in the input data.
  635. data = encode(data);
  636. body = { data: data };
  637. headers = {};
  638. return [4 /*yield*/, functionsInstance.contextProvider.getContext(options.limitedUseAppCheckTokens)];
  639. case 1:
  640. context = _a.sent();
  641. if (context.authToken) {
  642. headers['Authorization'] = 'Bearer ' + context.authToken;
  643. }
  644. if (context.messagingToken) {
  645. headers['Firebase-Instance-ID-Token'] = context.messagingToken;
  646. }
  647. if (context.appCheckToken !== null) {
  648. headers['X-Firebase-AppCheck'] = context.appCheckToken;
  649. }
  650. timeout = options.timeout || 70000;
  651. failAfterHandle = failAfter(timeout);
  652. return [4 /*yield*/, Promise.race([
  653. postJSON(url, body, headers, functionsInstance.fetchImpl),
  654. failAfterHandle.promise,
  655. functionsInstance.cancelAllRequests
  656. ])];
  657. case 2:
  658. response = _a.sent();
  659. // Always clear the failAfter timeout
  660. failAfterHandle.cancel();
  661. // If service was deleted, interrupted response throws an error.
  662. if (!response) {
  663. throw new FunctionsError('cancelled', 'Firebase Functions instance was deleted.');
  664. }
  665. error = _errorForResponse(response.status, response.json);
  666. if (error) {
  667. throw error;
  668. }
  669. if (!response.json) {
  670. throw new FunctionsError('internal', 'Response is not valid JSON object.');
  671. }
  672. responseData = response.json.data;
  673. // TODO(klimt): For right now, allow "result" instead of "data", for
  674. // backwards compatibility.
  675. if (typeof responseData === 'undefined') {
  676. responseData = response.json.result;
  677. }
  678. if (typeof responseData === 'undefined') {
  679. // Consider the response malformed.
  680. throw new FunctionsError('internal', 'Response is missing data field.');
  681. }
  682. decodedData = decode(responseData);
  683. return [2 /*return*/, { data: decodedData }];
  684. }
  685. });
  686. });
  687. }
  688. var name = "@firebase/functions";
  689. var version = "0.10.0";
  690. /**
  691. * @license
  692. * Copyright 2019 Google LLC
  693. *
  694. * Licensed under the Apache License, Version 2.0 (the "License");
  695. * you may not use this file except in compliance with the License.
  696. * You may obtain a copy of the License at
  697. *
  698. * http://www.apache.org/licenses/LICENSE-2.0
  699. *
  700. * Unless required by applicable law or agreed to in writing, software
  701. * distributed under the License is distributed on an "AS IS" BASIS,
  702. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  703. * See the License for the specific language governing permissions and
  704. * limitations under the License.
  705. */
  706. var AUTH_INTERNAL_NAME = 'auth-internal';
  707. var APP_CHECK_INTERNAL_NAME = 'app-check-internal';
  708. var MESSAGING_INTERNAL_NAME = 'messaging-internal';
  709. function registerFunctions(fetchImpl, variant) {
  710. var factory = function (container, _a) {
  711. var regionOrCustomDomain = _a.instanceIdentifier;
  712. // Dependencies
  713. var app = container.getProvider('app').getImmediate();
  714. var authProvider = container.getProvider(AUTH_INTERNAL_NAME);
  715. var messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);
  716. var appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);
  717. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  718. return new FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl);
  719. };
  720. app._registerComponent(new component.Component(FUNCTIONS_TYPE, factory, "PUBLIC" /* ComponentType.PUBLIC */).setMultipleInstances(true));
  721. app.registerVersion(name, version, variant);
  722. // BUILD_TARGET will be replaced by values like esm5, esm2017, cjs5, etc during the compilation
  723. app.registerVersion(name, version, 'cjs5');
  724. }
  725. /**
  726. * @license
  727. * Copyright 2020 Google LLC
  728. *
  729. * Licensed under the Apache License, Version 2.0 (the "License");
  730. * you may not use this file except in compliance with the License.
  731. * You may obtain a copy of the License at
  732. *
  733. * http://www.apache.org/licenses/LICENSE-2.0
  734. *
  735. * Unless required by applicable law or agreed to in writing, software
  736. * distributed under the License is distributed on an "AS IS" BASIS,
  737. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  738. * See the License for the specific language governing permissions and
  739. * limitations under the License.
  740. */
  741. /**
  742. * Returns a {@link Functions} instance for the given app.
  743. * @param app - The {@link @firebase/app#FirebaseApp} to use.
  744. * @param regionOrCustomDomain - one of:
  745. * a) The region the callable functions are located in (ex: us-central1)
  746. * b) A custom domain hosting the callable functions (ex: https://mydomain.com)
  747. * @public
  748. */
  749. function getFunctions(app$1, regionOrCustomDomain) {
  750. if (app$1 === void 0) { app$1 = app.getApp(); }
  751. if (regionOrCustomDomain === void 0) { regionOrCustomDomain = DEFAULT_REGION; }
  752. // Dependencies
  753. var functionsProvider = app._getProvider(util.getModularInstance(app$1), FUNCTIONS_TYPE);
  754. var functionsInstance = functionsProvider.getImmediate({
  755. identifier: regionOrCustomDomain
  756. });
  757. var emulator = util.getDefaultEmulatorHostnameAndPort('functions');
  758. if (emulator) {
  759. connectFunctionsEmulator.apply(void 0, tslib.__spreadArray([functionsInstance], emulator, false));
  760. }
  761. return functionsInstance;
  762. }
  763. /**
  764. * Modify this instance to communicate with the Cloud Functions emulator.
  765. *
  766. * Note: this must be called before this instance has been used to do any operations.
  767. *
  768. * @param host - The emulator host (ex: localhost)
  769. * @param port - The emulator port (ex: 5001)
  770. * @public
  771. */
  772. function connectFunctionsEmulator(functionsInstance, host, port) {
  773. connectFunctionsEmulator$1(util.getModularInstance(functionsInstance), host, port);
  774. }
  775. /**
  776. * Returns a reference to the callable HTTPS trigger with the given name.
  777. * @param name - The name of the trigger.
  778. * @public
  779. */
  780. function httpsCallable(functionsInstance, name, options) {
  781. return httpsCallable$1(util.getModularInstance(functionsInstance), name, options);
  782. }
  783. /**
  784. * Returns a reference to the callable HTTPS trigger with the specified url.
  785. * @param url - The url of the trigger.
  786. * @public
  787. */
  788. function httpsCallableFromURL(functionsInstance, url, options) {
  789. return httpsCallableFromURL$1(util.getModularInstance(functionsInstance), url, options);
  790. }
  791. /**
  792. * @license
  793. * Copyright 2017 Google LLC
  794. *
  795. * Licensed under the Apache License, Version 2.0 (the "License");
  796. * you may not use this file except in compliance with the License.
  797. * You may obtain a copy of the License at
  798. *
  799. * http://www.apache.org/licenses/LICENSE-2.0
  800. *
  801. * Unless required by applicable law or agreed to in writing, software
  802. * distributed under the License is distributed on an "AS IS" BASIS,
  803. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  804. * See the License for the specific language governing permissions and
  805. * limitations under the License.
  806. */
  807. // eslint-disable-next-line @typescript-eslint/no-explicit-any
  808. registerFunctions(nodeFetch__default["default"], 'node');
  809. exports.connectFunctionsEmulator = connectFunctionsEmulator;
  810. exports.getFunctions = getFunctions;
  811. exports.httpsCallable = httpsCallable;
  812. exports.httpsCallableFromURL = httpsCallableFromURL;
  813. //# sourceMappingURL=index.node.cjs.js.map