UNPKG

@companydna/rcp-client

Version:
581 lines (576 loc) 15.9 kB
// src/rcp.ts import Nango from "@nangohq/frontend"; // src/helpers/Enums.ts var CompanyUserAppStatus = /* @__PURE__ */ ((CompanyUserAppStatus2) => { CompanyUserAppStatus2["None"] = ""; CompanyUserAppStatus2["Approved"] = "Approved"; CompanyUserAppStatus2["Declined"] = "Declined"; CompanyUserAppStatus2["InProgress"] = "InProgress"; return CompanyUserAppStatus2; })(CompanyUserAppStatus || {}); var CompanyUserAppStatus = /* @__PURE__ */ ((CompanyUserAppStatus2) => { CompanyUserAppStatus2[CompanyUserAppStatus2["SYNC_DATA_RESULT"] = 2] = "SYNC_DATA_RESULT"; CompanyUserAppStatus2[CompanyUserAppStatus2["UPLOAD_FILES"] = 3] = "UPLOAD_FILES"; CompanyUserAppStatus2[CompanyUserAppStatus2["CREATE_INDEX"] = 4] = "CREATE_INDEX"; CompanyUserAppStatus2[CompanyUserAppStatus2["DELETE_DATA_AND_INDEX"] = 5] = "DELETE_DATA_AND_INDEX"; CompanyUserAppStatus2[CompanyUserAppStatus2["STREAM_RESULT"] = 7] = "STREAM_RESULT"; return CompanyUserAppStatus2; })(CompanyUserAppStatus || {}); // src/helpers/SocketHelper.ts import { io } from "socket.io-client"; var SocketHelper = class { socketIo; messageHandlers = []; pingInterval; lastPongTime = Date.now(); reconnectAttempts = 0; maxReconnectAttempts = 5; clientId; init(socketUrl) { if (!socketUrl) { throw new Error("Socket URL is required."); } this.socketIo = io(socketUrl, { path: "/socket.io", transports: ["websocket", "polling"], secure: true, reconnectionAttempts: this.maxReconnectAttempts, timeout: 2e4 }); this.socketIo.on("json", (json) => { this.messageHandlers.forEach((handler) => handler(json)); }); this.socketIo.on("clientId", (clientId) => { this.clientId = clientId; console.log("Received clientId:", clientId); }); this.socketIo.on("pong", () => { this.lastPongTime = Date.now(); }); this.socketIo.on("disconnect", () => { this.handleReconnect(); }); this.startPing(); } startPing() { this.pingInterval = setInterval(() => { if (this.socketIo && this.socketIo.connected) { const currentTime = Date.now(); if (currentTime - this.lastPongTime > 1e4) { console.warn("No pong received from server. Reconnecting..."); this.handleReconnect(); this.clearPingInterval(); } else { this.socketIo.emit("ping"); } } }, 5e3); } handleReconnect() { if (this.reconnectAttempts < this.maxReconnectAttempts) { this.reconnectAttempts++; this.clearPingInterval(); this.socketIo?.connect(); this.startPing(); } else { console.error( "Max reconnect attempts reached. Stopping reconnection attempts." ); this.clearPingInterval(); } } clearPingInterval() { if (this.pingInterval) { clearInterval(this.pingInterval); this.pingInterval = void 0; } } close() { this.socketIo?.disconnect(); this.clearPingInterval(); } addMessageHandler(handler) { this.messageHandlers.push(handler); } removeMessageHandler(handler) { this.messageHandlers = this.messageHandlers.filter((h) => h !== handler); } getClientId() { return this.clientId; } }; var SocketHelper_default = new SocketHelper(); // src/helpers/Api.ts var API_URL = "http://localhost:3003/api/v1"; async function getApps(secretKey) { return new Promise(async (resolve) => { if (!secretKey) { throw new Error("Secret key is required."); } fetch(`${API_URL}/getApps`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey } }).then((res) => res.json()).then((data) => { if (data) { const result = data; resolve(result); } else { resolve(void 0); } }); }); } async function getCompany(secretKey) { return new Promise(async (resolve) => { if (!secretKey) { throw new Error("Secret key is required."); } fetch(`${API_URL}/getCompany`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey } }).then((res) => res.json()).then((data) => { if (data) { const result = data; resolve(result); } else { resolve(void 0); } }); }); } async function getCompanyUser(secretKey, userId) { return new Promise(async (resolve) => { if (!secretKey) { throw new Error("Secret key is required."); } fetch(`${API_URL}/getCompanyUser`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey }, body: JSON.stringify({ userId: Number(userId) }) }).then((res) => res.json()).then((data) => { if (data) { const result = data; resolve(result); } else { resolve(void 0); } }).catch((err) => { resolve(void 0); }); }); } async function createCompanyUser(secretKey, userId) { return new Promise(async (resolve) => { if (!secretKey) { throw new Error("Secret key is required."); } fetch(`${API_URL}/createCompanyUser`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey }, body: JSON.stringify({ user_id: Number(userId), role_id: 2, status: "Approved" /* Approved */ }) }).then((res) => res.json()).then((data) => { if (data) { const result = data; resolve(result); } else { resolve(void 0); } }).catch((err) => { resolve(void 0); }); }); } async function deleteCompanyUser(secretKey, userId) { return new Promise(async (resolve) => { const clientId = SocketHelper_default.getClientId(); if (!secretKey) { throw new Error("Secret key is required."); } fetch(`${API_URL}/deleteCompanyUser`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey, "client-id": clientId || "" }, body: JSON.stringify({ userId: Number(userId) }) }).then((res) => res.json()).then((data) => { if (data) { resolve(data); } else { resolve(null); } }).catch((err) => { resolve(void 0); }); }); } async function getCompanyUserApp(secretKey, appId, userId) { return new Promise(async (resolve) => { if (!secretKey) { throw new Error("Secret key is required."); } fetch(`${API_URL}/getCompanyUserApp`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey }, body: JSON.stringify({ appId: Number(appId), userId: Number(userId) }) }).then((res) => res.json()).then((data) => { if (data) { const result = data; resolve(result); } else { resolve(void 0); } }).catch((err) => { resolve(void 0); }); }); } async function createCompanyUserApp(secretKey, appId, userId, credentials) { return new Promise(async (resolve) => { if (!secretKey) { throw new Error("Secret key is required."); } fetch(`${API_URL}/createCompanyUserApp`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey }, body: JSON.stringify({ company_user_id: Number(userId), app_id: Number(appId), credentials, status: CompanyUserAppStatus.Approved }) }).then((res) => res.json()).then((data) => { if (data) { const result = data; resolve(result); } else { resolve(void 0); } }).catch((err) => { resolve(void 0); }); }); } async function deleteCompanyUserApp(secretKey, companyUserAppId) { return new Promise(async (resolve) => { const clientId = SocketHelper_default.getClientId(); if (!secretKey) { throw new Error("Secret key is required."); } fetch(`${API_URL}/deleteCompanyUserApp`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey, "client-id": clientId || "" }, body: JSON.stringify({ id: Number(companyUserAppId) }) }).then((res) => res.json()).then((data) => { if (data) { resolve(data); } else { resolve(null); } }).catch((err) => { resolve(void 0); }); }); } async function checkAuthCredentials(secretKey, companyUserAppId) { return new Promise(async (resolve) => { fetch(`${API_URL}/checkAuthCredentials`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey }, body: JSON.stringify({ companyUserAppId: Number(companyUserAppId) }) }).then((res) => res.json()).then((data) => { if (data) { const result = data; resolve(result); } else { resolve(void 0); } }).catch((err) => { resolve(void 0); }); }); } async function syncCompanyUserAppData(secretKey, companyUserAppId) { return new Promise(async (resolve) => { const clientId = SocketHelper_default.getClientId(); fetch(`${API_URL}/syncCompanyUserAppData`, { method: "POST", headers: { "Content-Type": "application/json", "x-api-key": secretKey, "client-id": clientId || "" }, body: JSON.stringify({ companyUserAppId: Number(companyUserAppId) }) }).then((res) => res.json()).then((data) => { if (data) { const result = data; resolve(result); } else { resolve(void 0); } }).catch((err) => { resolve(void 0); }); }); } // src/helpers/Utils.ts var transformArrayToObject = (params) => { return params.reduce((param, current) => { param[current.key] = current.info; return param; }, {}); }; var Utils_default = { transformArrayToObject }; // src/rcp.ts var RCP = class { secretKey; constructor(config) { this.secretKey = config.secretKey; if (config.socketUrl) { SocketHelper_default.init(config.socketUrl); } } async getApps() { const company = await getCompany(this.secretKey); if (!company) { return { success: false, message: "Company not found." }; } const apps = await getApps(this.secretKey); if (!apps) { return { success: false, message: "Apps not found." }; } return { success: true, message: "Apps retrieved successfully.", apps }; } async connectUserApp(app, userId, credential) { const company = await getCompany(this.secretKey); if (!company) { return { success: false, message: "Company not found." }; } let user = await getCompanyUser(this.secretKey, userId); if (!user) { user = await createCompanyUser(this.secretKey, userId); if (!user) { return { success: false, message: "User creation failed." }; } } const nango = new Nango({ publicKey: "213b5d01-4757-40bb-9848-a2ee421ead34" }); const connectionId = `${company.id}-${user.id}-${app.id}`; const apiCredentials = app.auth_type === "API_KEY" /* ApiKey */ && credential ? { apiKey: credential.params.find( (param) => param.key === "API_KEY" /* ApiKey */ )?.info } : void 0; try { await nango.auth(app.integration_id, connectionId, { params: credential ? Utils_default.transformArrayToObject(credential.params) : {}, credentials: apiCredentials || {}, detectClosedAuthWindow: true }); const updatedCredential = credential ?? { params: [], connectionId: "" }; updatedCredential.connectionId = connectionId; let companyUserApp = await getCompanyUserApp( this.secretKey, app.id, user.id ); if (!companyUserApp) { companyUserApp = await createCompanyUserApp( this.secretKey, app.id, user.id, connectionId ); if (!companyUserApp) { return { success: false, message: "User app creation failed." }; } } const authCheck = await checkAuthCredentials( this.secretKey, companyUserApp.id ); if (!authCheck || !authCheck.success) { return { success: false, message: "Authentication credentials check failed." }; } return { success: true, message: "Connection successful.", companyUserApp }; } catch (error) { return { success: false, message: `Connection error: ${error.message}` }; } } async syncUserAppData(app, userId) { const company = await getCompany(this.secretKey); if (!company) { return { success: false, message: "Company not found." }; } const user = await getCompanyUser(this.secretKey, userId); if (!user) { return { success: false, message: "Company user not found." }; } const companyUserApp = await getCompanyUserApp( this.secretKey, app.id, user.id ); if (!companyUserApp) { return { success: false, message: "Company user app not found." }; } try { const syncCompanyUserAppDataResponse = await syncCompanyUserAppData( this.secretKey, companyUserApp.id ); if (!syncCompanyUserAppDataResponse || !syncCompanyUserAppDataResponse.success) { return { success: false, message: "Sync company user app data failed." }; } return { success: true, message: "Company user app data syncronization started." }; } catch (error) { return { success: false, message: `Connection error: ${error.message}` }; } } async deleteCompanyUserApp(app, userId) { const user = await getCompanyUser(this.secretKey, userId); if (!user) { return { success: false, message: "Company user not found." }; } const companyUserApp = await getCompanyUserApp( this.secretKey, app.id, user.id ); if (!companyUserApp) { return { success: false, message: "Company user app not found." }; } try { const deleteCompanyUserAppResponse = await deleteCompanyUserApp( this.secretKey, companyUserApp.id ); if (!deleteCompanyUserAppResponse || !deleteCompanyUserAppResponse.success) { return { success: false, message: "Delete company user app data failed." }; } return { success: true, message: "Company user app data deletion started." }; } catch (error) { return { success: false, message: `Connection error: ${error.message}` }; } } async deleteCompanyUser(userId) { try { const deleteCompanyUserResponse = await deleteCompanyUser( this.secretKey, userId ); if (!deleteCompanyUserResponse || !deleteCompanyUserResponse.success) { return { success: false, message: "Delete company user failed." }; } return { success: true, message: "Company user deletion started." }; } catch (error) { return { success: false, message: `Connection error: ${error.message}` }; } } subscribeSocket(handler) { SocketHelper_default.addMessageHandler(handler); } unsubscribeSocket(handler) { SocketHelper_default.removeMessageHandler(handler); } closeSocket() { SocketHelper_default.close(); } }; export { RCP }; //# sourceMappingURL=index.js.map