UNPKG

zapsea

Version:

Official JavaScript SDK for ZapSEA Intelligence Engine API

689 lines (671 loc) 19.4 kB
/** * Common types and interfaces for the ZapSEA JavaScript SDK */ interface ClientConfig { /** API key for authentication */ apiKey: string; /** Base URL for the API (defaults to https://api.politycs.ai) */ baseUrl?: string; /** Request timeout in milliseconds (defaults to 60000) */ timeout?: number; /** Maximum number of retry attempts (defaults to 3) */ maxRetries?: number; } interface HealthCheckResponse { /** API status */ status: string; /** API version */ apiVersion: string; /** Response timestamp */ timestamp: string; /** User tier if authenticated */ userTier?: string; } interface ErrorResponse { /** Error message */ detail: string; /** Error code */ code?: string; /** Additional error context */ context?: Record<string, any>; } interface PaginationParams { /** Number of items per page */ limit?: number; /** Page offset */ offset?: number; /** Cursor for cursor-based pagination */ cursor?: string; } interface PaginatedResponse<T> { /** Array of items */ data: T[]; /** Total count of items */ totalCount: number; /** Whether there are more items */ hasMore: boolean; /** Next cursor for pagination */ nextCursor?: string; } /** * Request types for the ZapSEA JavaScript SDK */ interface ImpactSimulationRequest { /** Description of the policy to analyze */ policyDescription: string; /** Depth of analysis to perform */ analysisDepth?: 'quick' | 'standard' | 'comprehensive'; /** Specific focus areas for the analysis */ focusAreas?: string[]; /** Time horizon for the analysis */ timeHorizon?: string; /** Custom parameters for the simulation */ customParameters?: Record<string, any>; } interface ScenarioComparisonRequest { /** Array of scenarios to compare */ scenarios: Array<{ /** Name of the scenario */ name: string; /** Policy description for this scenario */ policyDescription: string; }>; /** Criteria to use for comparison */ comparisonCriteria?: string[]; /** Custom parameters for the comparison */ customParameters?: Record<string, any>; } interface InfluencePathRequest { /** Source entity for influence path analysis */ sourceEntity: string; /** Target entity for influence path analysis */ targetEntity: string; /** Maximum path length to consider */ maxPathLength?: number; /** Minimum influence threshold */ minInfluenceThreshold?: number; /** Custom parameters for pathfinding */ customParameters?: Record<string, any>; } interface FeedbackRequest { /** Page or feature where feedback was given */ page: string; /** Rating from 1-5 stars */ rating?: number; /** Written feedback comment */ comment?: string; /** Type of feedback */ feedbackType?: 'general' | 'bug_report' | 'feature_request' | 'support'; /** Category of feedback */ category?: string; /** Customer email (for anonymous feedback) */ customerEmail?: string; /** Customer organization */ customerOrganization?: string; /** API endpoint related to feedback */ apiEndpoint?: string; /** Session ID for tracking */ sessionId?: string; } interface JobListRequest { /** Filter by job status */ statusFilter?: 'processing' | 'completed' | 'failed' | 'cancelled'; /** Maximum number of jobs to return */ limit?: number; /** Offset for pagination */ offset?: number; } /** * Response types for the ZapSEA JavaScript SDK */ interface JobResponse { /** Unique job identifier */ jobId: string; /** Current job status */ status: string; /** Estimated completion time */ estimatedCompletion?: string; /** Status message */ message: string; } interface JobStatusResponse { /** Unique job identifier */ jobId: string; /** Current job status */ status: 'processing' | 'completed' | 'failed' | 'cancelled'; /** Progress percentage (0-100) */ progressPercentage: number; /** Job creation timestamp */ createdAt: string; /** Job completion timestamp */ completedAt?: string; /** Job result data (when completed) */ resultData?: any; /** Error message (when failed) */ errorMessage?: string; /** API version used */ apiVersion: string; } interface JobListResponse { /** Array of job status objects */ jobs: JobStatusResponse[]; /** Total number of jobs */ totalCount: number; /** Whether there are more jobs */ hasMore: boolean; } interface ImpactSimulationResult { /** Unique simulation identifier */ simulationId: string; /** Policy identifier */ policyId: string; /** Success probability (0-1) */ successProbability: number; /** Confidence score (0-1) */ confidenceScore: number; /** Number of documents analyzed */ totalDocumentsAnalyzed: number; /** Key insights from the analysis */ keyInsights: string[]; /** Stakeholder analysis results */ stakeholderAnalysis: { /** Supporting stakeholders */ supporters: string[]; /** Opposing stakeholders */ opponents: string[]; /** Neutral stakeholders */ neutral: string[]; }; /** Identified risk factors */ riskFactors: Array<{ /** Risk factor description */ factor: string; /** Risk severity level */ severity: 'low' | 'medium' | 'high'; /** Risk probability (0-1) */ probability: number; }>; /** Identified opportunities */ opportunities: Array<{ /** Opportunity description */ opportunity: string; /** Impact level */ impact: 'low' | 'medium' | 'high'; /** Opportunity probability (0-1) */ probability: number; }>; } interface InfluencePathResult { /** Source entity */ sourceEntity: string; /** Target entity */ targetEntity: string; /** Length of the influence path */ pathLength: number; /** Total influence score */ totalInfluenceScore: number; /** Detailed path information */ pathDetails: Array<{ /** Entity in the path */ entity: string; /** Influence score to next entity */ influenceScore: number; /** Relationship type */ relationshipType: string; }>; } interface FeedbackResponse { /** Feedback submission ID */ feedbackId: string; /** Submission status */ status: 'received' | 'processed'; /** Confirmation message */ message: string; } /** * Impact Analysis Resource */ declare class ImpactResource { private client; constructor(client: ZapSEA); /** * Submit policy impact simulation * * @example * ```typescript * const job = await client.impact.simulate({ * policyDescription: 'Federal AI regulation requiring algorithmic transparency', * analysisDepth: 'comprehensive', * focusAreas: ['financial_services', 'artificial_intelligence'], * timeHorizon: '12_months' * }); * * console.log(`Job submitted: ${job.jobId}`); * ``` */ simulate(request: ImpactSimulationRequest): Promise<JobResponse>; /** * Compare multiple policy scenarios * * @example * ```typescript * const job = await client.impact.compareScenarios({ * scenarios: [ * { * name: 'Strict Regulation', * policyDescription: 'Mandatory AI audits for all financial algorithms' * }, * { * name: 'Self-Regulation', * policyDescription: 'Industry-led voluntary AI transparency standards' * } * ], * comparisonCriteria: ['implementation_cost', 'effectiveness', 'industry_acceptance'] * }); * ``` */ compareScenarios(request: ScenarioComparisonRequest): Promise<JobResponse>; /** * Get impact simulation result by job ID * * @example * ```typescript * const result = await client.impact.getResult('job_abc123'); * console.log(`Success probability: ${result.successProbability}`); * ``` */ getResult(jobId: string): Promise<any>; /** * Validate impact simulation request */ private _validateSimulationRequest; /** * Validate scenario comparison request */ private _validateScenarioComparisonRequest; } /** * Influence Analysis Resource */ declare class InfluenceResource { private client; constructor(client: ZapSEA); /** * Find influence path between entities * * @example * ```typescript * const job = await client.influence.findPath({ * sourceEntity: 'Congress', * targetEntity: 'Tech Industry', * maxPathLength: 5, * minInfluenceThreshold: 0.3 * }); * * console.log(`Job submitted: ${job.jobId}`); * ``` */ findPath(request: InfluencePathRequest): Promise<JobResponse>; /** * Get influence network for an entity * * @example * ```typescript * const job = await client.influence.getNetwork({ * entity: 'Federal Reserve', * depth: 2, * minInfluenceThreshold: 0.2 * }); * ``` */ getNetwork(request: { entity: string; depth?: number; minInfluenceThreshold?: number; customParameters?: Record<string, any>; }): Promise<JobResponse>; /** * Get influence path result by job ID * * @example * ```typescript * const result = await client.influence.getPathResult('job_abc123'); * console.log(`Path length: ${result.pathLength}`); * ``` */ getPathResult(jobId: string): Promise<any>; /** * Get top influencers in a domain * * @example * ```typescript * const influencers = await client.influence.getTopInfluencers({ * domain: 'technology_policy', * limit: 10 * }); * ``` */ getTopInfluencers(request: { domain: string; limit?: number; timeframe?: string; }): Promise<any>; /** * Validate influence path request */ private _validateInfluencePathRequest; /** * Validate network request */ private _validateNetworkRequest; /** * Validate top influencers request */ private _validateTopInfluencersRequest; } /** * Jobs Resource for managing asynchronous operations */ declare class JobsResource { private client; constructor(client: ZapSEA); /** * Get job status and results * * @example * ```typescript * const status = await client.jobs.get('job_abc123'); * * if (status.status === 'completed') { * console.log('Results:', status.resultData); * } * ``` */ get(jobId: string): Promise<JobStatusResponse>; /** * Wait for job completion with polling * * @example * ```typescript * const result = await client.jobs.waitForCompletion('job_abc123', { * timeout: 300000, // 5 minutes * pollInterval: 5000 // 5 seconds * }); * * console.log('Final result:', result.resultData); * ``` */ waitForCompletion(jobId: string, options?: { timeout?: number; pollInterval?: number; onProgress?: (status: JobStatusResponse) => void; }): Promise<JobStatusResponse>; /** * List user's jobs * * @example * ```typescript * const jobs = await client.jobs.list({ * statusFilter: 'completed', * limit: 10 * }); * * jobs.forEach(job => { * console.log(`${job.jobId}: ${job.status}`); * }); * ``` */ list(options?: JobListRequest): Promise<JobStatusResponse[]>; /** * Cancel a running job * * @example * ```typescript * await client.jobs.cancel('job_abc123'); * console.log('Job cancelled successfully'); * ``` */ cancel(jobId: string): Promise<void>; /** * Get job logs for debugging * * @example * ```typescript * const logs = await client.jobs.getLogs('job_abc123'); * console.log('Job logs:', logs); * ``` */ getLogs(jobId: string): Promise<any>; /** * Stream job progress updates * * @example * ```typescript * for await (const update of client.jobs.streamProgress('job_abc123')) { * console.log(`Progress: ${update.progressPercentage}%`); * if (update.status === 'completed') break; * } * ``` */ streamProgress(jobId: string, pollInterval?: number): AsyncGenerator<JobStatusResponse>; /** * Validate list request parameters */ private _validateListRequest; } /** * Feedback Resource for collecting user feedback */ declare class FeedbackResource { private client; constructor(client: ZapSEA); /** * Submit user feedback * * @example * ```typescript * const response = await client.feedback.submit({ * page: 'impact-simulation', * rating: 5, * comment: 'Great feature! Very helpful for policy analysis.', * feedbackType: 'general', * category: 'usability' * }); * * console.log('Feedback submitted:', response.feedbackId); * ``` */ submit(request: FeedbackRequest): Promise<FeedbackResponse>; /** * Submit bug report * * @example * ```typescript * const response = await client.feedback.reportBug({ * page: 'dashboard', * comment: 'Charts not loading properly on mobile devices', * apiEndpoint: '/v2/impact/simulate', * sessionId: 'session_123' * }); * ``` */ reportBug(request: { page: string; comment: string; apiEndpoint?: string; sessionId?: string; customerEmail?: string; }): Promise<FeedbackResponse>; /** * Submit feature request * * @example * ```typescript * const response = await client.feedback.requestFeature({ * page: 'general', * comment: 'Would love to see real-time collaboration features', * customerEmail: 'user@company.com', * customerOrganization: 'Acme Corp' * }); * ``` */ requestFeature(request: { page: string; comment: string; customerEmail?: string; customerOrganization?: string; }): Promise<FeedbackResponse>; /** * Submit rating only (quick feedback) * * @example * ```typescript * const response = await client.feedback.rate({ * page: 'api-documentation', * rating: 4 * }); * ``` */ rate(request: { page: string; rating: number; sessionId?: string; }): Promise<FeedbackResponse>; /** * Get feedback status * * @example * ```typescript * const status = await client.feedback.getStatus('feedback_abc123'); * console.log('Feedback status:', status); * ``` */ getStatus(feedbackId: string): Promise<any>; /** * Validate feedback request */ private _validateFeedbackRequest; } /** * Main ZapSEA API client */ declare class ZapSEA { private apiKey; private baseUrl; private timeout; private maxRetries; private userAgent; readonly impact: ImpactResource; readonly influence: InfluenceResource; readonly jobs: JobsResource; readonly feedback: FeedbackResource; /** * ZapSEA API Client * * @example * ```typescript * const client = new ZapSEA({ * apiKey: 'pk_live_...', * baseUrl: 'https://api.politycs.ai' * }); * * const job = await client.impact.simulate({ * policyDescription: 'AI regulation for financial services', * analysisDepth: 'comprehensive' * }); * ``` */ constructor(config: ClientConfig); /** * Make authenticated HTTP request */ request<T = any>(method: 'GET' | 'POST' | 'PUT' | 'DELETE', endpoint: string, data?: any, options?: RequestInit): Promise<T>; /** * Check API health status */ healthCheck(): Promise<HealthCheckResponse>; /** * Get current API configuration */ getConfig(): Readonly<{ baseUrl: string; timeout: number; maxRetries: number; userAgent: string; }>; /** * Update client configuration */ updateConfig(updates: Partial<Omit<ClientConfig, 'apiKey'>>): void; } /** * Error classes for the ZapSEA JavaScript SDK */ declare class ZapSEAError extends Error { readonly status?: number; readonly code?: string; constructor(message: string, status?: number, code?: string); static fromResponse(response: Response): Promise<ZapSEAError>; } declare class AuthenticationError extends ZapSEAError { constructor(message: string, status?: number, code?: string); } declare class PermissionError extends ZapSEAError { constructor(message: string, status?: number, code?: string); } declare class NotFoundError extends ZapSEAError { constructor(message: string, status?: number, code?: string); } declare class RateLimitError extends ZapSEAError { constructor(message: string, status?: number, code?: string); } declare class JobNotFoundError extends NotFoundError { constructor(message: string); } declare class TimeoutError extends ZapSEAError { constructor(message: string); } declare class ValidationError extends ZapSEAError { constructor(message: string, status?: number, code?: string); } declare class NetworkError extends ZapSEAError { readonly cause?: Error; constructor(message: string, cause?: Error); } /** * Validate API key format */ declare function validateApiKey(apiKey: string): boolean; /** * Validate job ID format */ declare function validateJobId(jobId: string): boolean; /** * ZapSEA JavaScript SDK * * A production-ready JavaScript SDK for the ZapSEA Intelligence Engine API V2. * Provides simple, async-first interfaces for policy impact simulation and analysis. * * @example * ```typescript * import { ZapSEA } from 'zapsea'; * * // Initialize client * const client = new ZapSEA({ * apiKey: 'pk_live_your_api_key_here' * }); * * // Run impact simulation * const job = await client.impact.simulate({ * policyDescription: 'AI regulation for financial services', * analysisDepth: 'comprehensive' * }); * * // Wait for completion * const result = await client.jobs.waitForCompletion(job.jobId); * console.log('Analysis complete:', result.resultData); * ``` */ declare const VERSION = "1.0.0"; export { AuthenticationError, FeedbackResource, ImpactResource, InfluenceResource, JobNotFoundError, JobsResource, NetworkError, NotFoundError, PermissionError, RateLimitError, TimeoutError, VERSION, ValidationError, ZapSEA, ZapSEAError, validateApiKey, validateJobId }; export type { ClientConfig, ErrorResponse, FeedbackRequest, FeedbackResponse, HealthCheckResponse, ImpactSimulationRequest, ImpactSimulationResult, InfluencePathRequest, InfluencePathResult, JobListRequest, JobListResponse, JobResponse, JobStatusResponse, PaginatedResponse, PaginationParams, ScenarioComparisonRequest };