123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819 |
- 'use strict';
-
- Object.defineProperty(exports, '__esModule', { value: true });
-
- var app = require('@firebase/app');
- var tslib = require('tslib');
- var util = require('@firebase/util');
- var component = require('@firebase/component');
- var nodeFetch = require('node-fetch');
-
- function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
-
- var nodeFetch__default = _interopDefaultLegacy(nodeFetch);
-
-
- var LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';
- var UNSIGNED_LONG_TYPE = 'type.googleapis.com/google.protobuf.UInt64Value';
- function mapValues(
- // { [k: string]: unknown } is no longer a wildcard assignment target after typescript 3.5
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
- o, f) {
- var result = {};
- for (var key in o) {
- if (o.hasOwnProperty(key)) {
- result[key] = f(o[key]);
- }
- }
- return result;
- }
- /**
- * Takes data and encodes it in a JSON-friendly way, such that types such as
- * Date are preserved.
- * @internal
- * @param data - Data to encode.
- */
- function encode(data) {
- if (data == null) {
- return null;
- }
- if (data instanceof Number) {
- data = data.valueOf();
- }
- if (typeof data === 'number' && isFinite(data)) {
- // Any number in JS is safe to put directly in JSON and parse as a double
- // without any loss of precision.
- return data;
- }
- if (data === true || data === false) {
- return data;
- }
- if (Object.prototype.toString.call(data) === '[object String]') {
- return data;
- }
- if (data instanceof Date) {
- return data.toISOString();
- }
- if (Array.isArray(data)) {
- return data.map(function (x) { return encode(x); });
- }
- if (typeof data === 'function' || typeof data === 'object') {
- return mapValues(data, function (x) { return encode(x); });
- }
- // If we got this far, the data is not encodable.
- throw new Error('Data cannot be encoded in JSON: ' + data);
- }
- /**
- * Takes data that's been encoded in a JSON-friendly form and returns a form
- * with richer datatypes, such as Dates, etc.
- * @internal
- * @param json - JSON to convert.
- */
- function decode(json) {
- if (json == null) {
- return json;
- }
- if (json['@type']) {
- switch (json['@type']) {
- case LONG_TYPE:
- // Fall through and handle this the same as unsigned.
- case UNSIGNED_LONG_TYPE: {
- // Technically, this could work return a valid number for malformed
- // data if there was a number followed by garbage. But it's just not
- // worth all the extra code to detect that case.
- var value = Number(json['value']);
- if (isNaN(value)) {
- throw new Error('Data cannot be decoded from JSON: ' + json);
- }
- return value;
- }
- default: {
- throw new Error('Data cannot be decoded from JSON: ' + json);
- }
- }
- }
- if (Array.isArray(json)) {
- return json.map(function (x) { return decode(x); });
- }
- if (typeof json === 'function' || typeof json === 'object') {
- return mapValues(json, function (x) { return decode(x); });
- }
-
- return json;
- }
-
-
-
- var FUNCTIONS_TYPE = 'functions';
-
-
-
- var errorCodeMap = {
- OK: 'ok',
- CANCELLED: 'cancelled',
- UNKNOWN: 'unknown',
- INVALID_ARGUMENT: 'invalid-argument',
- DEADLINE_EXCEEDED: 'deadline-exceeded',
- NOT_FOUND: 'not-found',
- ALREADY_EXISTS: 'already-exists',
- PERMISSION_DENIED: 'permission-denied',
- UNAUTHENTICATED: 'unauthenticated',
- RESOURCE_EXHAUSTED: 'resource-exhausted',
- FAILED_PRECONDITION: 'failed-precondition',
- ABORTED: 'aborted',
- OUT_OF_RANGE: 'out-of-range',
- UNIMPLEMENTED: 'unimplemented',
- INTERNAL: 'internal',
- UNAVAILABLE: 'unavailable',
- DATA_LOSS: 'data-loss'
- };
-
- var FunctionsError = (function (_super) {
- tslib.__extends(FunctionsError, _super);
- function FunctionsError(
- /**
- * A standard error code that will be returned to the client. This also
- * determines the HTTP status code of the response, as defined in code.proto.
- */
- code, message,
- /**
- * Extra data to be converted to JSON and included in the error response.
- */
- details) {
- var _this = _super.call(this, "".concat(FUNCTIONS_TYPE, "/").concat(code), message || '') || this;
- _this.details = details;
- return _this;
- }
- return FunctionsError;
- }(util.FirebaseError));
-
- function codeForHTTPStatus(status) {
-
- if (status >= 200 && status < 300) {
- return 'ok';
- }
- switch (status) {
- case 0:
-
- return 'internal';
- case 400:
- return 'invalid-argument';
- case 401:
- return 'unauthenticated';
- case 403:
- return 'permission-denied';
- case 404:
- return 'not-found';
- case 409:
- return 'aborted';
- case 429:
- return 'resource-exhausted';
- case 499:
- return 'cancelled';
- case 500:
- return 'internal';
- case 501:
- return 'unimplemented';
- case 503:
- return 'unavailable';
- case 504:
- return 'deadline-exceeded';
- }
- return 'unknown';
- }
-
- function _errorForResponse(status, bodyJSON) {
- var code = codeForHTTPStatus(status);
-
- var description = code;
- var details = undefined;
-
- try {
- var errorJSON = bodyJSON && bodyJSON.error;
- if (errorJSON) {
- var status_1 = errorJSON.status;
- if (typeof status_1 === 'string') {
- if (!errorCodeMap[status_1]) {
-
- return new FunctionsError('internal', 'internal');
- }
- code = errorCodeMap[status_1];
-
-
- description = status_1;
- }
- var message = errorJSON.message;
- if (typeof message === 'string') {
- description = message;
- }
- details = errorJSON.details;
- if (details !== undefined) {
- details = decode(details);
- }
- }
- }
- catch (e) {
-
- }
- if (code === 'ok') {
-
-
-
- return null;
- }
- return new FunctionsError(code, description, details);
- }
-
-
-
- var ContextProvider = (function () {
- function ContextProvider(authProvider, messagingProvider, appCheckProvider) {
- var _this = this;
- this.auth = null;
- this.messaging = null;
- this.appCheck = null;
- this.auth = authProvider.getImmediate({ optional: true });
- this.messaging = messagingProvider.getImmediate({
- optional: true
- });
- if (!this.auth) {
- authProvider.get().then(function (auth) { return (_this.auth = auth); }, function () {
-
- });
- }
- if (!this.messaging) {
- messagingProvider.get().then(function (messaging) { return (_this.messaging = messaging); }, function () {
-
- });
- }
- if (!this.appCheck) {
- appCheckProvider.get().then(function (appCheck) { return (_this.appCheck = appCheck); }, function () {
-
- });
- }
- }
- ContextProvider.prototype.getAuthToken = function () {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var token;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!this.auth) {
- return [2 , undefined];
- }
- _a.label = 1;
- case 1:
- _a.trys.push([1, 3, , 4]);
- return [4 , this.auth.getToken()];
- case 2:
- token = _a.sent();
- return [2 , token === null || token === void 0 ? void 0 : token.accessToken];
- case 3:
- _a.sent();
-
- return [2 , undefined];
- case 4: return [2 ];
- }
- });
- });
- };
- ContextProvider.prototype.getMessagingToken = function () {
- return tslib.__awaiter(this, void 0, void 0, function () {
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!this.messaging ||
- !('Notification' in self) ||
- Notification.permission !== 'granted') {
- return [2 , undefined];
- }
- _a.label = 1;
- case 1:
- _a.trys.push([1, 3, , 4]);
- return [4 , this.messaging.getToken()];
- case 2: return [2 , _a.sent()];
- case 3:
- _a.sent();
-
-
-
- return [2 , undefined];
- case 4: return [2 ];
- }
- });
- });
- };
- ContextProvider.prototype.getAppCheckToken = function () {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var result;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- if (!this.appCheck) return [3 , 2];
- return [4 , this.appCheck.getToken()];
- case 1:
- result = _a.sent();
- if (result.error) {
-
-
-
- return [2 , null];
- }
- return [2 , result.token];
- case 2: return [2 , null];
- }
- });
- });
- };
- ContextProvider.prototype.getContext = function () {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var authToken, messagingToken, appCheckToken;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0: return [4 , this.getAuthToken()];
- case 1:
- authToken = _a.sent();
- return [4 , this.getMessagingToken()];
- case 2:
- messagingToken = _a.sent();
- return [4 , this.getAppCheckToken()];
- case 3:
- appCheckToken = _a.sent();
- return [2 , { authToken: authToken, messagingToken: messagingToken, appCheckToken: appCheckToken }];
- }
- });
- });
- };
- return ContextProvider;
- }());
-
-
- var DEFAULT_REGION = 'us-central1';
-
- function failAfter(millis) {
-
-
-
- var timer = null;
- return {
- promise: new Promise(function (_, reject) {
- timer = setTimeout(function () {
- reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));
- }, millis);
- }),
- cancel: function () {
- if (timer) {
- clearTimeout(timer);
- }
- }
- };
- }
-
- var FunctionsService = (function () {
-
-
- function FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl) {
- if (regionOrCustomDomain === void 0) { regionOrCustomDomain = DEFAULT_REGION; }
- var _this = this;
- this.app = app;
- this.fetchImpl = fetchImpl;
- this.emulatorOrigin = null;
- this.contextProvider = new ContextProvider(authProvider, messagingProvider, appCheckProvider);
-
- this.cancelAllRequests = new Promise(function (resolve) {
- _this.deleteService = function () {
- return Promise.resolve(resolve());
- };
- });
-
- try {
- var url = new URL(regionOrCustomDomain);
- this.customDomain = url.origin;
- this.region = DEFAULT_REGION;
- }
- catch (e) {
- this.customDomain = null;
- this.region = regionOrCustomDomain;
- }
- }
- FunctionsService.prototype._delete = function () {
- return this.deleteService();
- };
-
-
- FunctionsService.prototype._url = function (name) {
- var projectId = this.app.options.projectId;
- if (this.emulatorOrigin !== null) {
- var origin_1 = this.emulatorOrigin;
- return "".concat(origin_1, "/").concat(projectId, "/").concat(this.region, "/").concat(name);
- }
- if (this.customDomain !== null) {
- return "".concat(this.customDomain, "/").concat(name);
- }
- return "https://".concat(this.region, "-").concat(projectId, ".cloudfunctions.net/").concat(name);
- };
- return FunctionsService;
- }());
-
- function connectFunctionsEmulator$1(functionsInstance, host, port) {
- functionsInstance.emulatorOrigin = "http://".concat(host, ":").concat(port);
- }
-
- function httpsCallable$1(functionsInstance, name, options) {
- return (function (data) {
- return call(functionsInstance, name, data, options || {});
- });
- }
-
- function httpsCallableFromURL$1(functionsInstance, url, options) {
- return (function (data) {
- return callAtURL(functionsInstance, url, data, options || {});
- });
- }
-
- function postJSON(url, body, headers, fetchImpl) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var response, json;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
- headers['Content-Type'] = 'application/json';
- _a.label = 1;
- case 1:
- _a.trys.push([1, 3, , 4]);
- return [4 , fetchImpl(url, {
- method: 'POST',
- body: JSON.stringify(body),
- headers: headers
- })];
- case 2:
- response = _a.sent();
- return [3 , 4];
- case 3:
- _a.sent();
-
-
-
-
- return [2 , {
- status: 0,
- json: null
- }];
- case 4:
- json = null;
- _a.label = 5;
- case 5:
- _a.trys.push([5, 7, , 8]);
- return [4 , response.json()];
- case 6:
- json = _a.sent();
- return [3 , 8];
- case 7:
- _a.sent();
- return [3 , 8];
- case 8: return [2 , {
- status: response.status,
- json: json
- }];
- }
- });
- });
- }
-
- function call(functionsInstance, name, data, options) {
- var url = functionsInstance._url(name);
- return callAtURL(functionsInstance, url, data, options);
- }
-
- function callAtURL(functionsInstance, url, data, options) {
- return tslib.__awaiter(this, void 0, void 0, function () {
- var body, headers, context, timeout, failAfterHandle, response, error, responseData, decodedData;
- return tslib.__generator(this, function (_a) {
- switch (_a.label) {
- case 0:
-
- data = encode(data);
- body = { data: data };
- headers = {};
- return [4 , functionsInstance.contextProvider.getContext()];
- case 1:
- context = _a.sent();
- if (context.authToken) {
- headers['Authorization'] = 'Bearer ' + context.authToken;
- }
- if (context.messagingToken) {
- headers['Firebase-Instance-ID-Token'] = context.messagingToken;
- }
- if (context.appCheckToken !== null) {
- headers['X-Firebase-AppCheck'] = context.appCheckToken;
- }
- timeout = options.timeout || 70000;
- failAfterHandle = failAfter(timeout);
- return [4 , Promise.race([
- postJSON(url, body, headers, functionsInstance.fetchImpl),
- failAfterHandle.promise,
- functionsInstance.cancelAllRequests
- ])];
- case 2:
- response = _a.sent();
-
- failAfterHandle.cancel();
-
- if (!response) {
- throw new FunctionsError('cancelled', 'Firebase Functions instance was deleted.');
- }
- error = _errorForResponse(response.status, response.json);
- if (error) {
- throw error;
- }
- if (!response.json) {
- throw new FunctionsError('internal', 'Response is not valid JSON object.');
- }
- responseData = response.json.data;
-
-
- if (typeof responseData === 'undefined') {
- responseData = response.json.result;
- }
- if (typeof responseData === 'undefined') {
-
- throw new FunctionsError('internal', 'Response is missing data field.');
- }
- decodedData = decode(responseData);
- return [2 , { data: decodedData }];
- }
- });
- });
- }
-
- var name = "@firebase/functions";
- var version = "0.9.1";
-
-
- var AUTH_INTERNAL_NAME = 'auth-internal';
- var APP_CHECK_INTERNAL_NAME = 'app-check-internal';
- var MESSAGING_INTERNAL_NAME = 'messaging-internal';
- function registerFunctions(fetchImpl, variant) {
- var factory = function (container, _a) {
- var regionOrCustomDomain = _a.instanceIdentifier;
-
- var app = container.getProvider('app').getImmediate();
- var authProvider = container.getProvider(AUTH_INTERNAL_NAME);
- var messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);
- var appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);
-
- return new FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl);
- };
- app._registerComponent(new component.Component(FUNCTIONS_TYPE, factory, "PUBLIC" ).setMultipleInstances(true));
- app.registerVersion(name, version, variant);
-
- app.registerVersion(name, version, 'cjs5');
- }
-
-
-
- function getFunctions(app$1, regionOrCustomDomain) {
- if (app$1 === void 0) { app$1 = app.getApp(); }
- if (regionOrCustomDomain === void 0) { regionOrCustomDomain = DEFAULT_REGION; }
-
- var functionsProvider = app._getProvider(util.getModularInstance(app$1), FUNCTIONS_TYPE);
- var functionsInstance = functionsProvider.getImmediate({
- identifier: regionOrCustomDomain
- });
- var emulator = util.getDefaultEmulatorHostnameAndPort('functions');
- if (emulator) {
- connectFunctionsEmulator.apply(void 0, tslib.__spreadArray([functionsInstance], emulator, false));
- }
- return functionsInstance;
- }
-
- function connectFunctionsEmulator(functionsInstance, host, port) {
- connectFunctionsEmulator$1(util.getModularInstance(functionsInstance), host, port);
- }
-
- function httpsCallable(functionsInstance, name, options) {
- return httpsCallable$1(util.getModularInstance(functionsInstance), name, options);
- }
-
- function httpsCallableFromURL(functionsInstance, url, options) {
- return httpsCallableFromURL$1(util.getModularInstance(functionsInstance), url, options);
- }
-
-
-
- registerFunctions(nodeFetch__default["default"], 'node');
-
- exports.connectFunctionsEmulator = connectFunctionsEmulator;
- exports.getFunctions = getFunctions;
- exports.httpsCallable = httpsCallable;
- exports.httpsCallableFromURL = httpsCallableFromURL;
|