123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728 |
- import { _registerComponent, registerVersion, _getProvider, getApp } from '@firebase/app';
- import { FirebaseError, getModularInstance, getDefaultEmulatorHostnameAndPort } from '@firebase/util';
- import { Component } from '@firebase/component';
- import nodeFetch from 'node-fetch';
-
-
- const LONG_TYPE = 'type.googleapis.com/google.protobuf.Int64Value';
- const 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) {
- const result = {};
- for (const 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(x => encode(x));
- }
- if (typeof data === 'function' || typeof data === 'object') {
- return mapValues(data, x => 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.
- const 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(x => decode(x));
- }
- if (typeof json === 'function' || typeof json === 'object') {
- return mapValues(json, x => decode(x));
- }
-
- return json;
- }
-
-
-
- const FUNCTIONS_TYPE = 'functions';
-
-
-
- const 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'
- };
-
- class FunctionsError extends FirebaseError {
- constructor(
- /**
- * 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) {
- super(`${FUNCTIONS_TYPE}/${code}`, message || '');
- this.details = details;
- }
- }
-
- 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) {
- let code = codeForHTTPStatus(status);
-
- let description = code;
- let details = undefined;
-
- try {
- const errorJSON = bodyJSON && bodyJSON.error;
- if (errorJSON) {
- const status = errorJSON.status;
- if (typeof status === 'string') {
- if (!errorCodeMap[status]) {
-
- return new FunctionsError('internal', 'internal');
- }
- code = errorCodeMap[status];
-
-
- description = status;
- }
- const 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);
- }
-
-
-
- class ContextProvider {
- constructor(authProvider, messagingProvider, appCheckProvider) {
- 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(auth => (this.auth = auth), () => {
-
- });
- }
- if (!this.messaging) {
- messagingProvider.get().then(messaging => (this.messaging = messaging), () => {
-
- });
- }
- if (!this.appCheck) {
- appCheckProvider.get().then(appCheck => (this.appCheck = appCheck), () => {
-
- });
- }
- }
- async getAuthToken() {
- if (!this.auth) {
- return undefined;
- }
- try {
- const token = await this.auth.getToken();
- return token === null || token === void 0 ? void 0 : token.accessToken;
- }
- catch (e) {
-
- return undefined;
- }
- }
- async getMessagingToken() {
- if (!this.messaging ||
- !('Notification' in self) ||
- Notification.permission !== 'granted') {
- return undefined;
- }
- try {
- return await this.messaging.getToken();
- }
- catch (e) {
-
-
-
- return undefined;
- }
- }
- async getAppCheckToken() {
- if (this.appCheck) {
- const result = await this.appCheck.getToken();
- if (result.error) {
-
-
-
- return null;
- }
- return result.token;
- }
- return null;
- }
- async getContext() {
- const authToken = await this.getAuthToken();
- const messagingToken = await this.getMessagingToken();
- const appCheckToken = await this.getAppCheckToken();
- return { authToken, messagingToken, appCheckToken };
- }
- }
-
-
- const DEFAULT_REGION = 'us-central1';
-
- function failAfter(millis) {
-
-
-
- let timer = null;
- return {
- promise: new Promise((_, reject) => {
- timer = setTimeout(() => {
- reject(new FunctionsError('deadline-exceeded', 'deadline-exceeded'));
- }, millis);
- }),
- cancel: () => {
- if (timer) {
- clearTimeout(timer);
- }
- }
- };
- }
-
- class FunctionsService {
-
-
- constructor(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain = DEFAULT_REGION, fetchImpl) {
- this.app = app;
- this.fetchImpl = fetchImpl;
- this.emulatorOrigin = null;
- this.contextProvider = new ContextProvider(authProvider, messagingProvider, appCheckProvider);
-
- this.cancelAllRequests = new Promise(resolve => {
- this.deleteService = () => {
- return Promise.resolve(resolve());
- };
- });
-
- try {
- const url = new URL(regionOrCustomDomain);
- this.customDomain = url.origin;
- this.region = DEFAULT_REGION;
- }
- catch (e) {
- this.customDomain = null;
- this.region = regionOrCustomDomain;
- }
- }
- _delete() {
- return this.deleteService();
- }
-
-
- _url(name) {
- const projectId = this.app.options.projectId;
- if (this.emulatorOrigin !== null) {
- const origin = this.emulatorOrigin;
- return `${origin}/${projectId}/${this.region}/${name}`;
- }
- if (this.customDomain !== null) {
- return `${this.customDomain}/${name}`;
- }
- return `https://${this.region}-${projectId}.cloudfunctions.net/${name}`;
- }
- }
-
- function connectFunctionsEmulator$1(functionsInstance, host, port) {
- functionsInstance.emulatorOrigin = `http://${host}:${port}`;
- }
-
- function httpsCallable$1(functionsInstance, name, options) {
- return (data => {
- return call(functionsInstance, name, data, options || {});
- });
- }
-
- function httpsCallableFromURL$1(functionsInstance, url, options) {
- return (data => {
- return callAtURL(functionsInstance, url, data, options || {});
- });
- }
-
- async function postJSON(url, body, headers, fetchImpl) {
- headers['Content-Type'] = 'application/json';
- let response;
- try {
- response = await fetchImpl(url, {
- method: 'POST',
- body: JSON.stringify(body),
- headers
- });
- }
- catch (e) {
-
-
-
-
- return {
- status: 0,
- json: null
- };
- }
- let json = null;
- try {
- json = await response.json();
- }
- catch (e) {
-
- }
- return {
- status: response.status,
- json
- };
- }
-
- function call(functionsInstance, name, data, options) {
- const url = functionsInstance._url(name);
- return callAtURL(functionsInstance, url, data, options);
- }
-
- async function callAtURL(functionsInstance, url, data, options) {
-
- data = encode(data);
- const body = { data };
-
- const headers = {};
- const context = await functionsInstance.contextProvider.getContext();
- 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;
- }
-
- const timeout = options.timeout || 70000;
- const failAfterHandle = failAfter(timeout);
- const response = await Promise.race([
- postJSON(url, body, headers, functionsInstance.fetchImpl),
- failAfterHandle.promise,
- functionsInstance.cancelAllRequests
- ]);
-
- failAfterHandle.cancel();
-
- if (!response) {
- throw new FunctionsError('cancelled', 'Firebase Functions instance was deleted.');
- }
-
- const error = _errorForResponse(response.status, response.json);
- if (error) {
- throw error;
- }
- if (!response.json) {
- throw new FunctionsError('internal', 'Response is not valid JSON object.');
- }
- let 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.');
- }
-
- const decodedData = decode(responseData);
- return { data: decodedData };
- }
-
- const name = "@firebase/functions";
- const version = "0.9.1";
-
-
- const AUTH_INTERNAL_NAME = 'auth-internal';
- const APP_CHECK_INTERNAL_NAME = 'app-check-internal';
- const MESSAGING_INTERNAL_NAME = 'messaging-internal';
- function registerFunctions(fetchImpl, variant) {
- const factory = (container, { instanceIdentifier: regionOrCustomDomain }) => {
-
- const app = container.getProvider('app').getImmediate();
- const authProvider = container.getProvider(AUTH_INTERNAL_NAME);
- const messagingProvider = container.getProvider(MESSAGING_INTERNAL_NAME);
- const appCheckProvider = container.getProvider(APP_CHECK_INTERNAL_NAME);
-
- return new FunctionsService(app, authProvider, messagingProvider, appCheckProvider, regionOrCustomDomain, fetchImpl);
- };
- _registerComponent(new Component(FUNCTIONS_TYPE, factory, "PUBLIC" ).setMultipleInstances(true));
- registerVersion(name, version, variant);
-
- registerVersion(name, version, 'esm2017');
- }
-
-
-
- function getFunctions(app = getApp(), regionOrCustomDomain = DEFAULT_REGION) {
-
- const functionsProvider = _getProvider(getModularInstance(app), FUNCTIONS_TYPE);
- const functionsInstance = functionsProvider.getImmediate({
- identifier: regionOrCustomDomain
- });
- const emulator = getDefaultEmulatorHostnameAndPort('functions');
- if (emulator) {
- connectFunctionsEmulator(functionsInstance, ...emulator);
- }
- return functionsInstance;
- }
-
- function connectFunctionsEmulator(functionsInstance, host, port) {
- connectFunctionsEmulator$1(getModularInstance(functionsInstance), host, port);
- }
-
- function httpsCallable(functionsInstance, name, options) {
- return httpsCallable$1(getModularInstance(functionsInstance), name, options);
- }
-
- function httpsCallableFromURL(functionsInstance, url, options) {
- return httpsCallableFromURL$1(getModularInstance(functionsInstance), url, options);
- }
-
-
-
- registerFunctions(nodeFetch, 'node');
-
- export { connectFunctionsEmulator, getFunctions, httpsCallable, httpsCallableFromURL };
|