0.1.40 • Published 5 months ago

@onlive.ai/flow-client v0.1.40

Weekly downloads
-
License
-
Repository
-
Last release
5 months ago

Onlive Flow Client

The Flow Client package offers a convenient interface for interacting with a multi-step process flow. The client helps you initiate, retrieve, and progress through flow steps while tracking events. It leverages robust type validation and provides a modern TypeScript-first API.

Installation

Using pnpm (recommended)

pnpm add @onlive.ai/flow-client
# or
npm install @onlive.ai/flow-client

Package Structure

This package is organized into the following main components:

packages/flow-client/
├── client/                     # Core client implementation
│   ├── client.service.ts      # Main FlowClient class
│   ├── client.types.ts        # Type definitions and schemas
│   └── client.service.spec.ts # Unit tests
├── tracking/                   # Event tracking functionality
│   ├── tracking.service.ts    # Tracking service implementation
│   └── tracking.types.ts      # Tracking-related types
├── flow.types.ts              # Flow-specific type definitions
├── index.ts                   # Main package exports
├── schema-generator.ts        # JSON schema generation utilities
└── README.md                  # This documentation

Main Exports

The package exports the following main components:

  • FlowClient: Main client class for flow interactions
  • Type definitions: Comprehensive TypeScript types for flows, steps, actions, and events
  • Event types: Types for tracking and event handling from @onlive.ai/tracker

Dependencies

This package depends on:

  • @onlive.ai/tracker: Event tracking functionality
  • @onlive.ai/calendar: Calendar-related utilities
  • @onlive.ai/common-121: Shared utilities and types
  • zod: Runtime type validation and schema definitions

Usage

Basic Import

import { FlowClient } from '@onlive.ai/flow-client';
// or
import { FlowClient, type FlowContext, type ClientOptions } from '@onlive.ai/flow-client';

Initialization

Create an instance of the FlowClient by passing a valid ClientOptions object. The options must conform to the ClientOptionsSchema. The options include:

  • baseUrl: (string) URL of the service.
  • flowId: (string) 24-character identifier.
  • organizationId: (string) UUID.
  • lang: (string) 2-character language code.
const client = new FlowClient({
  baseUrl: "https://api.example.com",
  flowId: "0123456789abcdef01234567",
  organizationId: "550e8400-e29b-41d4-a716-446655440000",
  lang: "en",
});

API Reference

FlowClient Class

The main class for interacting with flows. All methods are type-safe and include runtime validation.

Methods

firstStep(options?: GetStepOptions): Promise

Initiates the first step of the flow.

  • Parameters:
    • options (optional): An object conforming to GetStepOptionsSchema.
  • Response:
    • Returns a Promise that resolves to a FlowContext object, representing the flow’s status, the current step (as defined in StepSchema), and flow metadata (FlowSchema).
  • Process:
    • Validates the options.
    • Sends a POST request to flow/{flowId}/first-step.
    • Analyzes and emits "track" events via the tracking service.
getStep(stepId: string, options?: GetStepOptions): Promise

Retrieves a specific step in the flow.

  • Parameters:
    • stepId: (string) A non-empty string identifier validated by StepIdSchema.
    • options (optional): Additional parameters adhering to GetStepOptionsSchema.
  • Response:
    • Returns a Promise resolving to a FlowContext.
  • Process:
    • Validates the stepId.
    • Sends a POST request to flow/{flowId}/steps/{stepId}.
    • Tracks request and response events.
nextStep(trigger: GetStepTrigger, options?: GetStepOptions): Promise

Proceeds to the next step in the flow based on user actions.

  • Parameters:
    • trigger: An object conforming to GetStepTriggerSchema containing:
      • currentStepId (string): Current step identifier.
      • actionId (string): Identifier of the action to trigger.
    • options (optional): Configuration for step retrieval following GetStepOptionsSchema.
  • Response:
    • Returns a Promise that resolves to an updated FlowContext.
  • Process:
    • Validates the trigger.
    • Sends a POST request to flow/{flowId}/steps/{currentStepId}/action/{actionId}.
    • Analyzes both request and response by emitting tracking events.

Event Handling

on(type: EventType, listener: EventListener): void

Registers a listener for specific events.

  • Parameters:
    • type: A string event type, currently supporting "track" as defined by EventTypeSchema.
    • listener: Callback accepting the event type and event data.
  • Usage: Register multiple listener functions to react to tracking events.

Internally, FlowClient uses a private emit method to deliver events to all registered listeners.

Types & Schemas

The methods and the overall flow behavior are governed by types and validation schemas defined in the package:

  • FlowContext: Contains the status of the flow, current step details, and flow metadata.
  • StepSchema, ActionSchema, FieldSchema: Define properties and validation for steps, actions, and form fields.
  • GetStepOptions and GetStepTrigger: Govern the payload structure for step operations.
  • EventData: Structure for tracking events, ensuring consistency with the "track" event type.

Features

  • Type Safety: Full TypeScript support with runtime validation using Zod schemas
  • Event Tracking: Built-in event tracking for flow interactions
  • Multi-format Support: Supports both ESM and CommonJS
  • Modern API: Promise-based API with async/await support
  • Flexible Configuration: Configurable client options with validation
  • Error Handling: Comprehensive error handling with type-safe error responses

Development

Building the Package

pnpm build:package

Running Tests

# Run tests
pnpm test

# Run tests with coverage
pnpm test:coverage

Cleaning Build Artifacts

pnpm clean

Examples

Complete Flow Example

import { FlowClient } from '@onlive.ai/flow-client';

const client = new FlowClient({
  baseUrl: "https://api.example.com",
  flowId: "0123456789abcdef01234567",
  organizationId: "550e8400-e29b-41d4-a716-446655440000",
  lang: "en",
});

// Set up event tracking
client.on('track', (eventType, eventData) => {
  console.log('Flow event:', eventType, eventData);
});

// Start the flow
try {
  const firstStep = await client.firstStep();
  console.log('First step:', firstStep);
  
  // Progress through the flow
  const nextStep = await client.nextStep({
    currentStepId: firstStep.step.id,
    actionId: 'continue'
  });
  
  console.log('Next step:', nextStep);
} catch (error) {
  console.error('Flow error:', error);
}

Getting a Specific Step

const specificStep = await client.getStep('step-id-123', {
  // optional additional parameters
});

License

This package is part of the Onlive workspace and follows the project's licensing terms.


This documentation mirrors common npm package libraries by providing a straightforward interface with strong type validations and event tracking, ensuring that clients can interact with a dynamic flow efficiently.