flowscale
TypeScript icon, indicating that this package has built-in type declarations

1.0.17 • Public • Published

Flowscale Node.js SDK

A comprehensive SDK designed to simplify interaction with the FlowScale ComfyUI API. This library works in both Node.js and browser environments.


⚠️ Important Security Notice for Browser Usage

When using this SDK in a browser environment, your API key will be exposed to end users. This is a significant security risk. We strongly recommend:

  1. Using this SDK in a Node.js backend environment
  2. Creating a proxy API that securely handles the API key server-side

If you understand the risks and still need to use the SDK directly in the browser, you must explicitly acknowledge this by setting the allowDangerouslyExposeApiKey option:

const flowscale = new FlowscaleAPI({
  apiKey: 'your-api-key',
  baseUrl: 'your-api-url',
  allowDangerouslyExposeApiKey: false // Only set to true if you understand the security risks
});

Installation

Install the Flowscale SDK by npm, yarn, pnpm or bun:

npm install flowscale

yarn add flowscale

pnpm install flowscale

bun install flowscale

Quick Start

Importing the SDK

To get started, import the Flowscale SDK into your project:

import { FlowscaleAPI } from 'flowscale';

// Node.js Environment (Recommended)
const apiKey = process.env.FLOWSCALE_API_KEY;
const apiUrl = process.env.FLOWSCALE_API_URL;

const flowscale = new FlowscaleAPI({
  apiKey,
  baseUrl: apiUrl
});

// Browser Environment (Not Recommended)
const flowscale = new FlowscaleAPI({
  apiKey: 'your-api-key', // ⚠️ WARNING: This will be exposed to users
  baseUrl: 'https://your-api-url.pod.flowscale.ai',
  allowDangerouslyExposeApiKey: true // Explicitly acknowledge the security risk
});

Environment-Specific Considerations

Node.js (Recommended)

  • Store API keys in environment variables
  • Use .env files for configuration
  • Full access to all SDK features

Browser

  • API key will be visible in network requests
  • Supports File/Blob uploads directly from browser
  • Consider implementing a backend proxy instead

Environment Variables: Add the following to your .env file:

FLOWSCALE_API_KEY=your-api-key
FLOWSCALE_API_URL=https://your-api-url.pod.flowscale.ai

SDK Methods

Below is a detailed guide to the SDK methods, including descriptions, usage, and response formats.

1. checkHealth()

Description: Check the health status of the Flowscale platform, including the status of containers and services.

Usage:

const health = await flowscale.checkHealth();
console.log('API Health:', health);

Response Example:

{
  "status": "success",
  "data": [
    {
      "container": "container #1",
      "status": "idle"
    },
    {
      "container": "container #2",
      "status": "running"
    }
  ]
}

2. getQueue()

Description: Retrieve the current status of the workflow queue, including running and pending jobs.

Usage:

const queue = await flowscale.getQueue();
console.log('Queue Details:', queue);

Response Example:

{
  "status": "success",
  "data": [
    {
      "container": "container #1",
      "queue": {
        "queue_running": [
          [
            0,
            "2a0babc4-acce-4521-9576-00fa0e6ecc91"
          ]
        ],
        "queue_pending": [
          [
            1,
            "5d60718a-7e89-4c64-b32d-0d1366b44e2a"
          ]
        ]
      }
    }
  ]
}

3. getWorkflows()

Description: Retrieves the list of all deployed workflows available in the cluster.

Usage:

const workflows = await flowscale.getWorkflows();
console.log('Available Workflows:', workflows);

Response Example:

{
  "status": "success",
  "data": [
    {
      "id": "bncu0a1kipv",
      "name": "Text to Image",
      "description": "Generate an image from text input",
      "inputs": "{ \"text_51536\": \"string\" }",
      "outputs": "{ \"image_output\": \"image\" }"
    },
    {
      "id": "a9bc45rt2kpm",
      "name": "Image to Image",
      "description": "Transform an existing image",
      "inputs": "{ \"image_input\": \"image\", \"prompt\": \"string\" }",
      "outputs": "{ \"transformed_image\": \"image\" }"
    }
  ]
}

4. executeWorkflow(workflowId, data, groupId?)

Description: Trigger a workflow execution using its unique workflowId. Input data and an optional groupId can be provided for better organization and tracking.

Parameters:

  • workflowId (string): The unique ID of the workflow.
  • data (object): Input parameters for the workflow.
  • groupId (string, optional): A custom identifier for grouping runs.

Usage:

const workflowId = "bncu0a1kipv";
const groupId = "test_group";

const inputs = {
   "text_51536": "Prompt test",
   "image_1234": { /* File or Blob of image */ },
   "video_1239": { /* File or Blob of video */ }
};

const result = await flowscale.executeWorkflow(workflowId, inputs, groupId);
console.log('Workflow Result:', result);

Response Example:

{
  "status": "success",
  "data": {
    "number": 0,
    "node_errors": {},
    "output_names": [
      "filename_prefix_58358_5WWF7GQUYF"
    ],
    "run_id": "808f34d0-ef97-4b78-a00f-1268077ea6db"
  }
}

5 executeWorkflowAsync(workflowId, data, groupId?, pollIntervalMs?, timeoutMs?)

Description: Execute a workflow and automatically wait for the result by polling the output. This is a convenience method that combines executeWorkflow and getOutput with automatic polling.

Parameters:

  • workflowId (string): The unique ID of the workflow.
  • data (object): Input parameters for the workflow.
  • groupId (string, optional): A custom identifier for grouping runs.
  • pollIntervalMs (number, optional): Polling interval in milliseconds (default: 1000).
  • timeoutMs (number, optional): Maximum time to wait for results in milliseconds (default: 300000 - 5 minutes).

Usage:

const workflowId = "bncu0a1kipv";
const inputs = {
   "text_51536": "Prompt test",
   "image_1234": { /* File or Blob of image */ }
};

try {
  const result = await flowscale.executeWorkflowAsync(workflowId, inputs);
  console.log('Workflow Result:', result);
} catch (error) {
  if (error.message.includes('timed out')) {
    console.error('Workflow took too long to complete');
  } else {
    console.error('Workflow error:', error);
  }
}

Response Example:

{
  "status": "success",
  "data": {
    "download_url": "https://runs.s3.amazonaws.com/generations/...",
    "generation_status": "success"
  }
}

6. getOutput(filename)

Description: Fetch the output of a completed workflow using its filename. Outputs typically include downloadable files or results.

Parameters:

  • filename (string): The name of the output file.

Usage:

const output = await flowscale.getOutput('filename_prefix_58358_5WWF7GQUYF.png');
console.log('Workflow Output:', output);

Response Example:

{
  "status": "success",
  "data": {
    "download_url": "https://runs.s3.amazonaws.com/generations/...",
    "generation_status": "success"
  }
}

7. cancelRun(runId)

Description: Cancel a running workflow execution using its unique runId.

Parameters:

  • runId (string): The unique identifier of the running workflow.

Usage:

const result = await flowscale.cancelRun('808f34d0-ef97-4b78-a00f-1268077ea6db');
console.log('Cancellation Result:', result);

Response Example:

{
  "status": "success",
  "data": "Run cancelled successfully"
}

8. getRun(runId)

Description: Retrieve detailed information about a specific workflow run.

Parameters:

  • runId (string): The unique identifier of the run.

Usage:

const runDetails = await flowscale.getRun('808f34d0-ef97-4b78-a00f-1268077ea6db');
console.log('Run Details:', runDetails);

Response Example:

{
  "status": "success",
  "data": {
    "_id": "808f34d0-ef97-4b78-a00f-1268077ea6db",
    "status": "completed",
    "inputs": [
      {
        "path": "text_51536",
        "value": "a man riding a bike"
      }
    ],
    "outputs": [
      {
        "filename": "filename_prefix_58358_5WWF7GQUYF.png",
        "url": "https://runs.s3.amazonaws.com/generations/..."
      }
    ]
  }
}

9. getRuns(groupId)

Description: Retrieve all workflow runs associated with a specific groupId. If no groupId is provided, all runs for the team are returned.

Parameters:

  • groupId (string, optional): The identifier for grouping runs.

Usage:

const runs = await flowscale.getRuns('test_group');
console.log('Runs for Group:', runs);

// Get all runs for the team
const allRuns = await flowscale.getRuns();
console.log('All Runs:', allRuns);

Response Example:

{
  "status": "success",
  "data": {
    "group_id": "test_group",
    "count": 2,
    "runs": [
      {
        "_id": "cc29a72d-75b9-4c7b-b991-ccaf2a04d6ea",
        "status": "completed",
        "outputs": [
          {
            "filename": "filename_prefix_58358_G3DRLIVVYP.png",
            "url": "https://runs.s3.amazonaws.com/generations/..."
          }
        ]
      }
    ]
  }
}

Best Practices

Environment Configuration

  • Always store sensitive information such as API keys in environment variables.
  • Use .env files and libraries like dotenv for easy environment management.

Logging Configuration

The SDK includes configurable logging to help with debugging and monitoring. By default, logging is enabled with the 'info' level.

Configuration Options

const flowscale = new FlowscaleAPI({
  apiKey: 'your-api-key',
  baseUrl: 'https://your-api-url.pod.flowscale.ai',
  enableLogging: true,        // Enable/disable logging (default: true)
  logLevel: 'info'           // Set log level: 'debug', 'info', 'warn', 'error' (default: 'info')
});

Dynamic Logging Control

You can also change logging settings after initialization:

// Enable debug logging
flowscale.setLoggingConfig(true, 'debug');

// Disable logging completely
flowscale.setLoggingConfig(false);

// Check current logging configuration
const loggingConfig = flowscale.getLoggingConfig();
console.log(loggingConfig); // { enabled: true, level: 'debug' }

Log Levels

  • debug: Most verbose, includes detailed operation information
  • info: General information about operations (default)
  • warn: Warning messages for potential issues
  • error: Only error messages

Log Format

All logs are prefixed with timestamp and level:

[Flowscale INFO] 2025-06-03T10:30:45.123Z: WebSocket connection established
[Flowscale DEBUG] 2025-06-03T10:30:46.456Z: Polling workflow output: {...}

Error Handling

  • Wrap API calls in try-catch blocks to handle errors gracefully.
  • Log errors for debugging and improve resilience.

Testing and Debugging

  • Test workflows in a development environment before deploying to production.
  • Validate inputs to ensure they match the workflow requirements.

WebSocket API

The Flowscale SDK provides WebSocket functionality to enable real-time communication with the Flowscale API. This is particularly useful for receiving updates about workflow execution status and other events in real-time.

1. connectWebSocket(options)

Description: Establishes a WebSocket connection to the Flowscale API.

Parameters:

  • options (object, optional): Configuration options for the WebSocket connection.
    • onOpen (function, optional): Callback function executed when the connection opens.
    • onClose (function, optional): Callback function executed when the connection closes.
    • onError (function, optional): Callback function executed when an error occurs.
    • onMessage (function, optional): Callback function executed when a message is received.
    • reconnect (boolean, optional): Whether to attempt reconnection if the connection is lost. Default: true.
    • reconnectInterval (number, optional): Milliseconds to wait before attempting to reconnect. Default: 5000.
    • maxReconnectAttempts (number, optional): Maximum number of reconnection attempts. Default: 5.

Usage:

// Connect to WebSocket and set up event handlers
const disconnect = flowscale.connectWebSocket({
  onOpen: () => {
    console.log('WebSocket connected!');
  },
  onMessage: (message) => {
    console.log('Received message:', message);
    // Handle different message types
    if (message.type === 'run_status_update') {
      console.log('Run status updated:', message.data);
    }
  },
  onClose: (event) => {
    console.log('WebSocket closed:', event.code, event.reason);
  },
  onError: (error) => {
    console.error('WebSocket error:', error);
  }
});

// Later, to disconnect:
disconnect();

2. disconnectWebSocket()

Description: Closes the WebSocket connection if it is open.

Usage:

flowscale.disconnectWebSocket();
console.log('WebSocket disconnected');

3. sendWebSocketMessage(message)

Description: Sends a message through the WebSocket connection.

Parameters:

  • message (any): The message to send. Objects will be automatically stringified.

Returns:

  • (boolean): true if the message was sent successfully, false otherwise.

Usage:

const success = flowscale.sendWebSocketMessage({
  type: 'client_event',
  data: {
    action: 'subscribe',
    runId: '808f34d0-ef97-4b78-a00f-1268077ea6db'
  }
});

if (success) {
  console.log('Message sent successfully');
} else {
  console.error('Failed to send message');
}

4. isWebSocketConnected()

Description: Checks if the WebSocket connection is currently open.

Returns:

  • (boolean): true if the WebSocket is connected, false otherwise.

Usage:

if (flowscale.isWebSocketConnected()) {
  console.log('WebSocket is connected');
} else {
  console.log('WebSocket is not connected');
}

WebSocket Examples

The SDK includes example implementations for both browser and Node.js environments:

Browser Example

See examples/websocket-example.html for a complete browser example with a user interface.

Node.js Example

Node.js requires a custom WebSocket implementation since the WebSocket API is not built-in. See examples/node-websocket-example.js for an example using the 'ws' library.

Note: To use WebSockets in Node.js, you'll need to install the 'ws' package:

npm install ws

Note: WebSocket functionality is natively available only in browser environments. For Node.js, you need to use a WebSocket library like ws.


Support

For any questions or assistance, join the Flowscale community on Discord or refer to the Flowscale Documentation.


Simplify your workflow management with the Flowscale Node.js SDK. Happy coding!

Package Sidebar

Install

npm i flowscale

Weekly Downloads

48

Version

1.0.17

License

MIT

Unpacked Size

67.5 kB

Total Files

11

Last publish

Collaborators

  • rupayan10