UNPKG

dymo-api

Version:

Flow system for Dymo API.

216 lines (215 loc) 11 kB
"use strict"; var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) { if (k2 === undefined) k2 = k; var desc = Object.getOwnPropertyDescriptor(m, k); if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) { desc = { enumerable: true, get: function() { return m[k]; } }; } Object.defineProperty(o, k2, desc); }) : (function(o, m, k, k2) { if (k2 === undefined) k2 = k; o[k2] = m[k]; })); var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) { Object.defineProperty(o, "default", { enumerable: true, value: v }); }) : function(o, v) { o["default"] = v; }); var __importStar = (this && this.__importStar) || (function () { var ownKeys = function(o) { ownKeys = Object.getOwnPropertyNames || function (o) { var ar = []; for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k; return ar; }; return ownKeys(o); }; return function (mod) { if (mod && mod.__esModule) return mod; var result = {}; if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]); __setModuleDefault(result, mod); return result; }; })(); var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; Object.defineProperty(exports, "__esModule", { value: true }); exports.extractWithTextly = exports.getRandom = exports.sendEmail = exports.isValidData = void 0; const path_1 = __importDefault(require("path")); const react_1 = __importDefault(require("react")); const promises_1 = __importDefault(require("fs/promises")); const tw_to_css_1 = require("tw-to-css"); const render_1 = require("@react-email/render"); const config_1 = __importStar(require("../config/index.cjs")); const customError = (code, message) => { return Object.assign(new Error(), { code, message: `[${config_1.default.lib.name}] ${message}` }); }; const convertTailwindToInlineCss = (htmlContent) => { return htmlContent.replace(/class="([^"]+)"( style="([^"]+)")?/g, (match, classList, _, existingStyle) => { const compiledStyles = (0, tw_to_css_1.twi)(classList, { minify: true, merge: true }); return match.replace(/class="[^"]+"/, "").replace(/ style="[^"]+"/, "").concat(` style="${existingStyle ? `${existingStyle.trim().slice(0, -1)}; ${compiledStyles}` : compiledStyles}"`); }); }; /** * Validates the provided data using a secure verification endpoint. * * @param token - A string or null representing the authentication token. Must not be null. * @param data - An object adhering to the Validator interface, containing at least one of the following fields: * url, email, phone, domain, creditCard, ip, wallet or user agent. * * @returns A promise that resolves to the response data from the verification endpoint. * * @throws Will throw an error if the token is null, if none of the required fields are present in the data, * or if an error occurs during the verification request. */ const isValidData = async (token, data) => { if (token === null) throw customError(3000, "Invalid private token."); if (!Object.keys(data).some((key) => ["url", "email", "phone", "domain", "creditCard", "ip", "wallet", "userAgent"].includes(key) && data.hasOwnProperty(key))) throw customError(1500, "You must provide at least one parameter."); try { const response = await config_1.axiosApiUrl.post("/private/secure/verify", data, { headers: { "Content-Type": "application/json", "Authorization": token } }); return response.data; } catch (error) { const statusCode = error.response?.status || 500; const errorMessage = error.response?.data?.message || error.message; const errorDetails = JSON.stringify(error.response?.data || {}); throw customError(5000, `Error ${statusCode}: ${errorMessage}. Details: ${errorDetails}`); } }; exports.isValidData = isValidData; /** * Sends an email using a secure sending endpoint. * * @param token - A string or null representing the authentication token. Must not be null. * @param data - An object adhering to the SendEmail interface, containing the following fields: * 'from', 'to', 'subject', 'html' or 'react', and optionally 'attachments', 'options', 'priority', 'waitToResponse', and 'composeTailwindClasses'. * * @returns A promise that resolves to the response data from the sending endpoint. * * @throws Will throw an error if the token is null, if any of the required fields are missing, * if the 'react' field is not a valid React element, if the 'attachments' field exceeds the maximum allowed size of 40 MB, * or if an error occurs during the sending request. */ const sendEmail = async (token, data) => { if (token === null) throw customError(3000, "Invalid private token."); if (!data.from) throw customError(1500, "You must provide an email address from which the following will be sent."); if (!data.to) throw customError(1500, "You must provide an email to be sent to."); if (!data.subject) throw customError(1500, "You must provide a subject for the email to be sent."); if (!data.html && !data.react && !react_1.default.isValidElement(data.react)) throw customError(1500, "You must provide HTML or a React component."); if (data.html && data.react) throw customError(1500, "You must provide only HTML or a React component, not both."); try { if (data.react) { //@ts-ignore data.html = await (0, render_1.render)(data.react); delete data.react; } if (data.options && data.options.composeTailwindClasses) { data.html = convertTailwindToInlineCss(data.html); delete data.options.composeTailwindClasses; } } catch (error) { throw customError(1500, `An error occurred while rendering your React component. Details: ${error}`); } try { let totalSize = 0; if (data.attachments && Array.isArray(data.attachments)) { const processedAttachments = await Promise.all(data.attachments.map(async (attachment) => { if ((attachment.path && attachment.content) || (!attachment.path && !attachment.content)) throw customError(1500, "You must provide either 'path' or 'content', not both."); let contentBuffer; if (attachment.path) contentBuffer = await promises_1.default.readFile(path_1.default.resolve(attachment.path)); else if (attachment.content) contentBuffer = attachment.content instanceof Buffer ? attachment.content : Buffer.from(attachment.content); totalSize += Buffer.byteLength(contentBuffer); if (totalSize > 40 * 1024 * 1024) throw customError(1500, "Attachments exceed the maximum allowed size of 40 MB."); return { filename: attachment.filename || path_1.default.basename(attachment.path || ""), content: contentBuffer, cid: attachment.cid || attachment.filename }; })); data.attachments = processedAttachments; } const response = await config_1.axiosApiUrl.post("/private/sender/sendEmail", data, { headers: { "Authorization": token } }); return response.data; } catch (error) { throw customError(5000, error.response?.data?.message || error.message); } }; exports.sendEmail = sendEmail; /** * Retrieves a random number within a specified range using a secure endpoint. * * @param token - A string or null representing the authentication token. Must not be null. * @param data - An object adhering to the SRNG interface, containing 'min' and 'max' fields, * which define the inclusive range within which the random number should be generated. * * @returns A promise that resolves to the response data containing the random number. * * @throws Will throw an error if the token is null, if 'min' or 'max' are not defined, * if 'min' is not less than 'max', if 'min' or 'max' are out of the allowed range, * or if an error occurs during the request to the random number generator endpoint. */ const getRandom = async (token, data) => { if (token === null) throw customError(3000, "Invalid private token."); if (!data.min || !data.max) throw customError(1500, "Both 'min' and 'max' parameters must be defined."); if (data.min >= data.max) throw customError(1500, "'min' must be less than 'max'."); if (data.min < -1000000000 || data.min > 1000000000) throw customError(1500, "'min' must be an integer in the interval [-1000000000}, 1000000000]."); if (data.max < -1000000000 || data.max > 1000000000) throw customError(1500, "'max' must be an integer in the interval [-1000000000}, 1000000000]."); try { const response = await config_1.axiosApiUrl.post("/private/srng", data, { headers: { "Content-Type": "application/json", "Authorization": token } }); return response.data; } catch (error) { throw customError(5000, error.response?.data?.message || error.message); } }; exports.getRandom = getRandom; /** * Extracts structured data from a given string using a secure endpoint. * * @param token - A string or null representing the authentication token. Must not be null. * @param data - An object adhering to the ExtractWithTextly interface, containing 'data' and 'format' fields. * The 'data' field is the string from which structured data should be extracted. * The 'format' field is an object defining the structure of the data to be extracted. * * @returns A promise that resolves to the response data containing the extracted structured data. * * @throws Will throw an error if the token is null, if 'data' or 'format' are not defined, * or if an error occurs during the request to the extraction endpoint. */ const extractWithTextly = async (token, data) => { if (token === null) throw customError(3000, "Invalid private token."); if (!data.data) throw customError(1500, "No data provided."); if (!data.format) throw customError(1500, "No format provided."); try { const response = await config_1.axiosApiUrl.post("/private/textly/extract", data, { headers: { "Content-Type": "application/json", "Authorization": token } }); return response.data; } catch (error) { throw customError(5000, error.response?.data?.message || error.message); } }; exports.extractWithTextly = extractWithTextly;