Skip to content

Latest commit

 

History

History
256 lines (181 loc) · 6.73 KB

README.md

File metadata and controls

256 lines (181 loc) · 6.73 KB

PredictFlow JavaScript & TypeScript SDK

npm version TypeScript License: MIT Dependencies

The official JavaScript and TypeScript SDK for PredictFlow — an intelligent demand forecasting, inventory optimization, and e-commerce analytics platform.


Features

  • ⚡ Zero Runtime Dependencies — Ultra-lightweight, high-performance footprint.
  • 🔒 100% Type-Safe — Complete TypeScript definitions generated from the official PredictFlow API.
  • 🌐 Universal Compatibility — Works seamlessly in Node.js 18+, Next.js (Server & Edge), Browsers, Bun, and Cloudflare Workers.
  • 🔁 Automatic Retries & Backoff — Built-in resilience for rate limits (429) and transient network errors on safe, idempotent requests.
  • 📦 Dual ESM & CommonJS — Native support for import and require().

Installation

# npm
npm install @predictflow/sdk

# pnpm
pnpm add @predictflow/sdk

# yarn
yarn add @predictflow/sdk

# bun
bun add @predictflow/sdk

Quickstart

1. Initialize the Client

import { PredictFlow } from '@predictflow/sdk';

// Initialize with API Key or let it read from process.env.PREDICTFLOW_API_KEY
const predictFlow = new PredictFlow({
  apiKey: process.env.PREDICTFLOW_API_KEY,
});

// Verify connectivity
const health = await predictFlow.health();
console.log('API Status:', health.status);

2. CommonJS (Node.js)

const { PredictFlow } = require('@predictflow/sdk');

const predictFlow = new PredictFlow({
  apiKey: process.env.PREDICTFLOW_API_KEY,
});

Core Guides & Usage

📊 Demand Forecasting & Predictions

// 1. Generate a 30-day demand forecast for a product
const forecast = await predictFlow.predictions.forecastProduct('prod_123', {
  horizon_days: 30,
  include_confidence_intervals: true,
});

console.log(`Forecasted Units: ${forecast.forecast_data.total_forecasted_units}`);

// 2. Simulate stockout risk
const stockout = await predictFlow.predictions.simulateStockout(forecast.id, {
  lead_time_days: 7,
  safety_stock: 15,
});

console.log(`Days to Stockout: ${stockout.days_to_stockout} days`);

// 3. Get optimal inventory reorder quantity & reorder point
const recommendation = await predictFlow.predictions.getInventoryRecommendation(forecast.id);
console.log(`Optimal Reorder Point: ${recommendation.optimal_reorder_point} units`);
console.log(`Recommended Order Qty: ${recommendation.recommended_order_quantity} units`);

📦 Products & Inventory Health

const storeId = 'store_abc123';

// List low stock products requiring immediate attention
const lowStock = await predictFlow.products.listLowStock(storeId);

// Get overall inventory health overview
const health = await predictFlow.products.getInventoryHealth(storeId);
console.log(`Dead Stock Items: ${health.dead_stock_count}`);
console.log(`Estimated Dead Stock Value: $${health.estimated_dead_stock_value}`);

// Get ABC Revenue Analysis (80/15/5 revenue drivers)
const abc = await predictFlow.products.getAbcAnalysis(storeId);

🏪 Stores & Catalog Sync

// List all connected stores
const stores = await predictFlow.stores.list();

// Trigger a catalog sync for a store
const syncResult = await predictFlow.stores.triggerSync('store_abc123');
console.log('Sync triggered:', syncResult.message);

📈 Analytics & KPIs

// Get dashboard KPIs and growth percentages
const kpis = await predictFlow.analytics.getKpis({
  period_days: 30,
  store_id: 'store_abc123',
});

console.log(`Current Revenue: $${kpis.current.total_revenue}`);
console.log(`Revenue Growth: ${kpis.growth.revenue_growth}%`);

// Get sales historical trend data points
const trend = await predictFlow.analytics.getTrend({ period_days: 30 });

🏷️ Pricing Elasticity & Simulations

// Check price elasticity coefficient for a product
const elasticity = await predictFlow.pricing.getElasticity('prod_123');
console.log(`Category: ${elasticity.elasticity_category}`); // 'elastic' | 'inelastic'
console.log(`Suggested Optimal Price: $${elasticity.optimal_price}`);

// Simulate a hypothetical price change
const sim = await predictFlow.pricing.simulate('prod_123', { test_price: 49.99 });
console.log(`Projected Monthly Revenue: $${sim.predicted_monthly_revenue}`);

Error Handling

The SDK provides a typed error hierarchy for error handling:

import {
  PredictFlow,
  AuthenticationError,
  NotFoundError,
  ValidationError,
  RateLimitError,
  PredictFlowError,
} from '@predictflow/sdk';

try {
  const forecast = await predictFlow.predictions.forecastProduct('prod_missing');
} catch (err) {
  if (err instanceof AuthenticationError) {
    console.error('Check your API Key credentials');
  } else if (err instanceof NotFoundError) {
    console.error('Product was not found');
  } else if (err instanceof RateLimitError) {
    console.warn(`Rate limited. Retry after ${err.retryAfterSeconds}s`);
  } else if (err instanceof ValidationError) {
    console.error('Invalid parameter payload:', err.details);
  } else if (err instanceof PredictFlowError) {
    console.error(`API Error [${err.status}]: ${err.message}`);
  }
}

Client Options

const predictFlow = new PredictFlow({
  // PredictFlow API Key (defaults to process.env.PREDICTFLOW_API_KEY)
  apiKey: 'pk_live_...',

  // Custom API Base URL (defaults to 'https://predictflow.co/api/v1')
  baseUrl: 'https://predictflow.co/api/v1',

  // Request timeout in milliseconds (defaults to 30000ms / 30s)
  timeoutMs: 15000,

  // Maximum retry attempts for rate limits & network errors (defaults to 2)
  maxRetries: 3,

  // Custom default headers to include with every request
  defaultHeaders: {
    'X-Custom-App': 'MyDashboard/1.0',
  },

  // Optional custom fetch implementation (useful for tests or edge runtimes)
  fetch: customFetch,
});

Development & Testing

# Install dependencies
npm install

# Run Vitest test suite
npm test

# Build dual ESM/CJS bundles + TypeScript declarations
npm run build

# Run type check
npm run typecheck

Changelog

See CHANGELOG.md.

Contributing

See CONTRIBUTING.md for local setup, the PR process, and what a reviewer checks first.

Security

Found a vulnerability? See SECURITY.md - please don't open a public issue for it.

License

MIT © PredictFlow