UNPKG

zapsea

Version:

Official JavaScript SDK for ZapSEA Intelligence Engine API

404 lines (313 loc) 9.89 kB
# ZapSEA JavaScript SDK [![npm version](https://badge.fury.io/js/zapsea.svg)](https://badge.fury.io/js/zapsea) [![TypeScript](https://img.shields.io/badge/TypeScript-Ready-blue.svg)](https://www.typescriptlang.org/) [![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT) The official JavaScript/TypeScript SDK for the ZapSEA Intelligence Engine API. Build powerful policy analysis applications with comprehensive impact simulation and influence mapping capabilities. ## Features - 🚀 **Modern & Fast**: Built with TypeScript, async/await, and modern JavaScript features - 🌐 **Isomorphic**: Works in both Node.js and browser environments - 📦 **Tree Shakeable**: Modular design for optimal bundle sizes - 🔄 **Auto-Retry**: Built-in retry logic with exponential backoff - 📊 **Job Management**: Comprehensive async job handling with progress tracking - 🛡️ **Type Safe**: Full TypeScript support with comprehensive type definitions - 🔧 **Developer Friendly**: Excellent IDE support and debugging capabilities ## Installation ```bash npm install zapsea ``` ```bash yarn add zapsea ``` ```bash pnpm add zapsea ``` ## Quick Start ```typescript import { ZapSEA } from 'zapsea'; // Initialize the client const client = new ZapSEA({ apiKey: 'pk_live_your_api_key_here' }); // Run a policy impact simulation async function analyzePolicy() { try { // Submit simulation job const job = await client.impact.simulate({ policyDescription: 'Federal AI regulation requiring algorithmic transparency', analysisDepth: 'comprehensive', focusAreas: ['financial_services', 'artificial_intelligence'] }); console.log(`Job submitted: ${job.jobId}`); // Wait for completion with progress updates const result = await client.jobs.waitForCompletion(job.jobId, { onProgress: (status) => { console.log(`Progress: ${status.progressPercentage}%`); } }); console.log('Analysis complete:', result.resultData); } catch (error) { console.error('Error:', error.message); } } analyzePolicy(); ``` ## Authentication Get your API key from the [ZapSEA Developer Portal](https://api.polityflow.com/developer): ```typescript import { ZapSEA } from 'zapsea'; // Production API key const client = new ZapSEA({ apiKey: 'pk_live_...' }); // Test API key (for development) const testClient = new ZapSEA({ apiKey: 'pk_test_...' }); ``` ## Core Features ### Impact Simulation Analyze the potential impact of policy changes: ```typescript // Basic simulation const job = await client.impact.simulate({ policyDescription: 'Carbon tax implementation for manufacturing sector', analysisDepth: 'standard' }); // Advanced simulation with custom parameters const advancedJob = await client.impact.simulate({ policyDescription: 'Healthcare reform with universal coverage', analysisDepth: 'comprehensive', focusAreas: ['healthcare', 'insurance', 'pharmaceuticals'], timeHorizon: '24_months', customParameters: { includeEconomicImpact: true, stakeholderAnalysis: 'detailed' } }); ``` ### Scenario Comparison Compare multiple policy scenarios: ```typescript const comparison = await client.impact.compareScenarios({ scenarios: [ { name: 'Gradual Implementation', policyDescription: 'Phased rollout over 3 years with industry consultation' }, { name: 'Immediate Implementation', policyDescription: 'Full implementation within 6 months' } ], comparisonCriteria: ['cost', 'effectiveness', 'stakeholder_acceptance'] }); ``` ### Influence Mapping Analyze influence networks and pathways: ```typescript // Find influence path between entities const pathJob = await client.influence.findPath({ sourceEntity: 'Federal Reserve', targetEntity: 'Banking Industry', maxPathLength: 4 }); // Get influence network for an entity const networkJob = await client.influence.getNetwork({ entity: 'Congress', depth: 2, minInfluenceThreshold: 0.3 }); ``` ### Job Management Handle asynchronous operations efficiently: ```typescript // Get job status const status = await client.jobs.get('job_abc123'); // Wait for completion with custom timeout const result = await client.jobs.waitForCompletion('job_abc123', { timeout: 600000, // 10 minutes pollInterval: 3000, // 3 seconds onProgress: (status) => { console.log(`${status.progressPercentage}% complete`); } }); // Stream progress updates for await (const update of client.jobs.streamProgress('job_abc123')) { console.log(`Status: ${update.status}, Progress: ${update.progressPercentage}%`); if (update.status === 'completed') break; } // List recent jobs const recentJobs = await client.jobs.list({ statusFilter: 'completed', limit: 10 }); ``` ### Feedback Collection Collect user feedback for continuous improvement: ```typescript // Submit general feedback await client.feedback.submit({ page: 'impact-simulation', rating: 5, comment: 'Excellent analysis capabilities!', feedbackType: 'general' }); // Report a bug await client.feedback.reportBug({ page: 'dashboard', comment: 'Charts not loading on mobile devices', apiEndpoint: '/v2/impact/simulate' }); // Request a feature await client.feedback.requestFeature({ page: 'general', comment: 'Would love real-time collaboration features', customerEmail: 'user@company.com' }); ``` ## Framework Integration ### React Hook Example ```typescript import { useState, useEffect } from 'react'; import { ZapSEA, JobStatusResponse } from 'zapsea'; export function useZapSEAJob(jobId: string | null) { const [status, setStatus] = useState<JobStatusResponse | null>(null); const [loading, setLoading] = useState(false); const [error, setError] = useState<string | null>(null); useEffect(() => { if (!jobId) return; const client = new ZapSEA({ apiKey: process.env.REACT_APP_ZAPSEA_API_KEY! }); const pollJob = async () => { setLoading(true); setError(null); try { await client.jobs.waitForCompletion(jobId, { onProgress: setStatus }); } catch (err: any) { setError(err.message); } finally { setLoading(false); } }; pollJob(); }, [jobId]); return { status, loading, error }; } ``` ### Vue Composition API Example ```typescript import { ref, watch } from 'vue'; import { ZapSEA } from 'zapsea'; export function useZapSEAAnalysis() { const client = new ZapSEA({ apiKey: process.env.VUE_APP_ZAPSEA_API_KEY! }); const isLoading = ref(false); const result = ref(null); const error = ref(null); const runAnalysis = async (policyDescription: string) => { isLoading.value = true; error.value = null; try { const job = await client.impact.simulate({ policyDescription, analysisDepth: 'standard' }); const finalResult = await client.jobs.waitForCompletion(job.jobId); result.value = finalResult.resultData; } catch (err: any) { error.value = err.message; } finally { isLoading.value = false; } }; return { runAnalysis, isLoading, result, error }; } ``` ## Error Handling The SDK provides comprehensive error handling: ```typescript import { ZapSEAError, AuthenticationError, RateLimitError, ValidationError } from 'zapsea'; try { const result = await client.impact.simulate({ policyDescription: 'AI regulation' }); } catch (error) { if (error instanceof AuthenticationError) { console.error('Invalid API key'); } else if (error instanceof RateLimitError) { console.error('Rate limit exceeded, please try again later'); } else if (error instanceof ValidationError) { console.error('Invalid request parameters:', error.message); } else if (error instanceof ZapSEAError) { console.error('API error:', error.message, error.status); } else { console.error('Unexpected error:', error); } } ``` ## Configuration ### Client Configuration ```typescript const client = new ZapSEA({ apiKey: 'pk_live_...', baseUrl: 'https://api.polityflow.com', // Custom API endpoint timeout: 30000, // 30 second timeout maxRetries: 3 // Retry failed requests 3 times }); // Update configuration after initialization client.updateConfig({ timeout: 60000, maxRetries: 5 }); ``` ### Environment Variables ```bash # .env file ZAPSEA_API_KEY=pk_live_your_api_key_here ZAPSEA_BASE_URL=https://api.polityflow.com ``` ## TypeScript Support The SDK is built with TypeScript and provides comprehensive type definitions: ```typescript import { ZapSEA, ImpactSimulationResult, InfluencePathResult, JobStatusResponse } from 'zapsea'; const client = new ZapSEA({ apiKey: process.env.ZAPSEA_API_KEY! }); // Fully typed responses const job = await client.impact.simulate({ policyDescription: 'Healthcare reform', analysisDepth: 'comprehensive' // TypeScript will validate this }); const result: JobStatusResponse = await client.jobs.waitForCompletion(job.jobId); const analysisData: ImpactSimulationResult = result.resultData; ``` ## Browser Support The SDK works in all modern browsers and supports: - Chrome 60+ - Firefox 60+ - Safari 12+ - Edge 79+ For older browsers, you may need polyfills for `fetch` and `Promise`. ## Node.js Support Requires Node.js 16.0.0 or higher. ## Contributing We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details. ## License MIT License - see [LICENSE](LICENSE) file for details. ## Support - 📖 [API Documentation](https://api.polityflow.com/docs) - 💬 [Developer Portal](https://api.polityflow.com/developer) - 🐛 [Issue Tracker](https://github.com/zapsea/zapsea-js/issues) - 📧 [Support Email](mailto:support@polityflow.com)