UNPKG

n8n-nodes-wuzapi

Version:

n8n community nodes for Wuzapi - WhatsApp Multi-Device REST API

150 lines 6.18 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 __exportStar = (this && this.__exportStar) || function(m, exports) { for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p); }; Object.defineProperty(exports, "__esModule", { value: true }); exports.wuzapiApiRequest = wuzapiApiRequest; exports.wuzapiApiRequestAllItems = wuzapiApiRequestAllItems; exports.handleErrorResponse = handleErrorResponse; exports.validatePhoneNumber = validatePhoneNumber; exports.formatJID = formatJID; exports.prepareMediaData = prepareMediaData; exports.parseWebhookEvents = parseWebhookEvents; const n8n_workflow_1 = require("n8n-workflow"); async function wuzapiApiRequest(method, endpoint, body = {}, qs = {}, uri, option = {}) { const credentials = await this.getCredentials('wuzapiApi'); const advancedOptions = credentials.advancedOptions || {}; const options = { method, body, qs, url: uri || `${credentials.url}${endpoint}`, json: true, returnFullResponse: false, ignoreHttpStatusErrors: true, ...option, }; // Add timeout if specified if (advancedOptions.timeout) { options.timeout = advancedOptions.timeout; } // Add proxy if specified if (advancedOptions.proxyUrl) { // For n8n, proxy is a string URL options.proxy = advancedOptions.proxyUrl; } // Implement retry logic const maxRetries = advancedOptions.retryOnFailure === false ? 0 : (advancedOptions.maxRetries || 3); let lastError; for (let attempt = 0; attempt <= maxRetries; attempt++) { try { const response = await this.helpers.httpRequestWithAuthentication.call(this, 'wuzapiApi', options); // Check if response indicates an error if (response && typeof response === 'object') { if (response.success === false || response.code >= 400) { throw new n8n_workflow_1.NodeApiError(this.getNode(), response, { message: response.error || response.message || 'API request failed', httpCode: response.code?.toString() || undefined, }); } } return response; } catch (error) { lastError = error; // Don't retry on certain errors const errorMessage = error.message || ''; const httpCode = error.httpCode || ''; if (errorMessage.includes('Authentication') || errorMessage.includes('Invalid token') || httpCode === '401' || httpCode === '403') { throw error; } // If not the last attempt, wait before retrying if (attempt < maxRetries) { const waitTime = Math.min(1000 * Math.pow(2, attempt), 10000); // Exponential backoff, max 10 seconds await (0, n8n_workflow_1.sleep)(waitTime); continue; } // Last attempt failed, throw the error throw error; } } // This should never be reached, but just in case throw lastError || new n8n_workflow_1.NodeOperationError(this.getNode(), 'Request failed after all retries'); } async function wuzapiApiRequestAllItems(method, endpoint, body = {}, qs = {}) { // For now, Wuzapi doesn't seem to have paginated endpoints // This function is here for future implementation if needed return wuzapiApiRequest.call(this, method, endpoint, body, qs); } function handleErrorResponse(error, node) { if (error instanceof n8n_workflow_1.NodeApiError || error instanceof n8n_workflow_1.NodeOperationError) { throw error; } if (error.response?.data) { const errorData = error.response.data; throw new n8n_workflow_1.NodeApiError(node, errorData, { message: errorData.error || errorData.message || 'Unknown error occurred', httpCode: error.response.status?.toString(), }); } throw new n8n_workflow_1.NodeOperationError(node, error.message || 'An unexpected error occurred'); } function validatePhoneNumber(phone) { // Remove any non-numeric characters let cleaned = phone.replace(/\D/g, ''); // Remove leading zeros cleaned = cleaned.replace(/^0+/, ''); // Validate that we have a reasonable phone number if (cleaned.length < 7 || cleaned.length > 15) { throw new Error(`Invalid phone number format: ${phone}. Phone numbers should be between 7 and 15 digits.`); } return cleaned; } function formatJID(phone, isGroup = false) { if (isGroup) { // Group JIDs have a different format if (!phone.includes('@')) { return `${phone}@g.us`; } return phone; } // Individual JIDs if (!phone.includes('@')) { const cleaned = validatePhoneNumber(phone); return `${cleaned}@s.whatsapp.net`; } return phone; } function prepareMediaData(binaryData, mimeType) { // Convert binary data to base64 with data URL format const base64 = binaryData.toString('base64'); return `data:${mimeType};base64,${base64}`; } function parseWebhookEvents(events) { if (Array.isArray(events)) { return events; } if (typeof events === 'string') { // Handle comma-separated values return events.split(',').map(e => e.trim()).filter(e => e.length > 0); } return ['All']; } // Import AI Tool functions __exportStar(require("./WuzapiAI/WuzapiFunctions"), exports); __exportStar(require("./WuzapiAI/MediaFunctions"), exports); //# sourceMappingURL=GenericFunctions.js.map