Files
sim/packages/ts-sdk
Waleed d078c84ee6 chore(typescript): upgrade to TypeScript 7 (native Go compiler) (#5521)
* chore(typescript): upgrade to TypeScript 7 (native Go compiler)

Bumps typescript to ^7.0.2 across every workspace package. Full
bun run type-check/lint/build/test all pass; apps/sim's type-check
(the one needing an 8GB heap bump) drops from ~55s to ~7s wall time.

Migration fixes required by TS7's stricter defaults:
- baseUrl removed: drop it from 5 tsconfigs (paths already resolved
  relative to tsconfig dir, so behavior is unchanged) and prefix the
  one bare (non-relative) paths entry each in apps/sim and
  apps/realtime with './'
- moduleResolution=node10 removed: switch packages/cli and
  packages/ts-sdk to "bundler", matching the rest of the monorepo
- types now defaults to [] instead of auto-including every @types/*
  package: add "types": ["node"] to the shared base tsconfig (this
  is fundamentally a Node monorepo, so this restores prior behavior
  in one place instead of duplicating it per-package), add explicit
  @types/node deps to packages that now rely on it transitively via
  @sim/db/@sim/logger, and add "declare module '*.css'" to the two
  packages with plain (non-module) CSS side-effect imports that
  TS7's stricter checker now flags
- packages/logger's isomorphic `typeof window` check no longer needs
  DOM lib in every consumer: replaced with `'window' in globalThis`
- packages/testing and apps/realtime's fetch/DOM mocks need DOM lib
  where they're compiled, since they model the browser Fetch API
- the `typescript` npm package no longer exports the classic
  Compiler API from its main entry (moved to unstable/ast subpaths);
  apps/sim's Function-block route used it at runtime to strip
  import statements from user code, so that one call site now uses
  Microsoft's official transition package, @typescript/typescript6
- Next.js 16.2.6's own TypeScript-detection heuristic hardcodes a
  path TS7 no longer ships, and its auto-install fallback assumes
  npm/pnpm; added @typescript/native-preview as a devDependency to
  apps/sim and apps/docs so Next detects a valid native compiler
  instead of trying (and failing) to auto-install one

Not merging yet: TS 7.0.2 published today and is still inside this
repo's bunfig.toml minimumReleaseAge (7-day) supply-chain gate, so
`bun install` will fail for everyone until 2026-07-15. Opening this
now to get it through review; hold the actual merge until then.

* fix(typescript): address Greptile review findings on TS7 upgrade

- packages/logger: 'window' in globalThis treats a shim that leaves
  globalThis.window explicitly undefined as browser-only, silently
  dropping production server logs. Restore the original
  typeof !== 'undefined' semantics via an inline cast instead, so it
  stays correct without requiring DOM lib in every consumer.
- packages/ts-sdk, packages/cli: both are tsc-built, published as
  Node ESM (package.json "type": "module" with an "exports" map).
  "moduleResolution": "bundler" is too permissive for that target -
  it accepts import patterns (e.g. extensionless relative imports)
  that Node's actual ESM resolver rejects at runtime. Switch both to
  "module"/"moduleResolution": "nodenext", the correct pairing for a
  published Node ESM package. Verified real tsc builds (not just
  --noEmit) still succeed for both.

* chore(bunfig): temporarily disable minimumReleaseAge gate for TS7 install

TS 7.0.2 published today, still inside the 7-day gate. Lowering to 0
to unblock this merge; will restore to 604800 in an immediate follow-up
commit right after merging.
2026-07-08 16:41:23 -07:00
..

Sim TypeScript SDK

The official TypeScript/JavaScript SDK for Sim, allowing you to execute workflows programmatically from your applications.

Installation

npm install simstudio-ts-sdk
# or 
yarn add simstudio-ts-sdk
# or
bun add simstudio-ts-sdk

Quick Start

import { SimStudioClient } from 'simstudio-ts-sdk';

// Initialize the client
const client = new SimStudioClient({
  apiKey: 'your-api-key-here',
  baseUrl: 'https://sim.ai' // optional, defaults to https://sim.ai
});

// Execute a workflow
try {
  const result = await client.executeWorkflow('workflow-id');
  console.log('Workflow executed successfully:', result);
} catch (error) {
  console.error('Workflow execution failed:', error);
}

API Reference

SimStudioClient

Constructor

new SimStudioClient(config: SimStudioConfig)
  • config.apiKey (string): Your Sim API key
  • config.baseUrl (string, optional): Base URL for the Sim API (defaults to https://sim.ai)

Methods

executeWorkflow(workflowId, input?, options?)

Execute a workflow with optional input data.

// With object input (spread at root level of request body)
const result = await client.executeWorkflow('workflow-id', {
  message: 'Hello, world!'
});

// With primitive input (wrapped as { input: value })
const result = await client.executeWorkflow('workflow-id', 'NVDA');

// With options
const result = await client.executeWorkflow('workflow-id', { message: 'Hello' }, {
  timeout: 60000
});

Parameters:

  • workflowId (string): The ID of the workflow to execute
  • input (any, optional): Input data to pass to the workflow. Objects are spread at the root level, primitives/arrays are wrapped in { input: value }. File objects are automatically converted to base64.
  • options (ExecutionOptions, optional):
    • timeout (number): Timeout in milliseconds (default: 30000)
    • stream (boolean): Enable streaming responses
    • selectedOutputs (string[]): Block outputs to stream (e.g., ["agent1.content"])
    • async (boolean): Execute asynchronously and return execution ID

Returns: Promise<WorkflowExecutionResult | AsyncExecutionResult>

getWorkflowStatus(workflowId)

Get the status of a workflow (deployment status, etc.).

const status = await client.getWorkflowStatus('workflow-id');
console.log('Is deployed:', status.isDeployed);

Parameters:

  • workflowId (string): The ID of the workflow

Returns: Promise<WorkflowStatus>

validateWorkflow(workflowId)

Validate that a workflow is ready for execution.

const isReady = await client.validateWorkflow('workflow-id');
if (isReady) {
  // Workflow is deployed and ready
}

Parameters:

  • workflowId (string): The ID of the workflow

Returns: Promise<boolean>

executeWorkflowSync(workflowId, input?, options?)

Execute a workflow and poll for completion (useful for long-running workflows).

const result = await client.executeWorkflowSync('workflow-id', { data: 'some input' }, {
  timeout: 60000
});

Parameters:

  • workflowId (string): The ID of the workflow to execute
  • input (any, optional): Input data to pass to the workflow
  • options (ExecutionOptions, optional):
    • timeout (number): Timeout for the initial request in milliseconds

Returns: Promise<WorkflowExecutionResult>

getJobStatus(jobId)

Get the status of an async job.

const status = await client.getJobStatus('job-id-from-async-execution');
console.log('Job status:', status);

Parameters:

  • jobId (string): The job ID returned from async execution

Returns: Promise<any>

executeWithRetry(workflowId, input?, options?, retryOptions?)

Execute a workflow with automatic retry on rate limit errors.

const result = await client.executeWithRetry('workflow-id', { message: 'Hello' }, {
  timeout: 30000
}, {
  maxRetries: 3,
  initialDelay: 1000,
  maxDelay: 30000,
  backoffMultiplier: 2
});

Parameters:

  • workflowId (string): The ID of the workflow to execute
  • input (any, optional): Input data to pass to the workflow
  • options (ExecutionOptions, optional): Execution options
  • retryOptions (RetryOptions, optional):
    • maxRetries (number): Maximum retry attempts (default: 3)
    • initialDelay (number): Initial delay in ms (default: 1000)
    • maxDelay (number): Maximum delay in ms (default: 30000)
    • backoffMultiplier (number): Backoff multiplier (default: 2)

Returns: Promise<WorkflowExecutionResult | AsyncExecutionResult>

getRateLimitInfo()

Get current rate limit information from the last API response.

const rateInfo = client.getRateLimitInfo();
if (rateInfo) {
  console.log('Remaining requests:', rateInfo.remaining);
}

Returns: RateLimitInfo | null

getUsageLimits()

Get current usage limits and quota information.

const limits = await client.getUsageLimits();
console.log('Current usage:', limits.usage);

Returns: Promise<UsageLimits>

setApiKey(apiKey)

Update the API key.

client.setApiKey('new-api-key');
setBaseUrl(baseUrl)

Update the base URL.

client.setBaseUrl('https://my-custom-domain.com');

Types

WorkflowExecutionResult

interface WorkflowExecutionResult {
  success: boolean;
  output?: any;
  error?: string;
  logs?: any[];
  metadata?: {
    duration?: number;
    executionId?: string;
    [key: string]: any;
  };
  traceSpans?: any[];
  totalDuration?: number;
}

LargeValueRef

Oversized execution values may be returned as a versioned reference inside output, logs, streaming events, or async job status responses. The key field is an opaque execution-scoped server storage pointer, not a client-readable download URL.

interface LargeValueRef {
  __simLargeValueRef: true;
  version: 1;
  id: string;
  kind: 'array' | 'object' | 'string' | 'json';
  size: number;
  key?: string;
  executionId?: string;
  preview?: unknown;
}

WorkflowStatus

interface WorkflowStatus {
  isDeployed: boolean;
  deployedAt?: string;
  needsRedeployment: boolean;
}

SimStudioError

class SimStudioError extends Error {
  code?: string;
  status?: number;
}

AsyncExecutionResult

interface AsyncExecutionResult {
  success: boolean;
  jobId: string;
  statusUrl: string;
  executionId?: string;
  message: string;
  async: true;
}

RateLimitInfo

interface RateLimitInfo {
  limit: number;
  remaining: number;
  reset: number;
  retryAfter?: number;
}

UsageLimits

interface UsageLimits {
  success: boolean;
  rateLimit: {
    sync: {
      isLimited: boolean;
      limit: number;
      remaining: number;
      resetAt: string;
    };
    async: {
      isLimited: boolean;
      limit: number;
      remaining: number;
      resetAt: string;
    };
    authType: string;
  };
  usage: {
    currentPeriodCost: number;
    limit: number;
    plan: string;
  };
}

ExecutionOptions

interface ExecutionOptions {
  timeout?: number;
  stream?: boolean;
  selectedOutputs?: string[];
  async?: boolean;
}

RetryOptions

interface RetryOptions {
  maxRetries?: number;
  initialDelay?: number;
  maxDelay?: number;
  backoffMultiplier?: number;
}

Examples

Basic Workflow Execution

import { SimStudioClient } from 'simstudio-ts-sdk';

const client = new SimStudioClient({
  apiKey: process.env.SIM_API_KEY!
});

async function runWorkflow() {
  try {
    // Check if workflow is ready
    const isReady = await client.validateWorkflow('my-workflow-id');
    if (!isReady) {
      throw new Error('Workflow is not deployed or ready');
    }

    // Execute the workflow
    const result = await client.executeWorkflow('my-workflow-id', {
      message: 'Process this data',
      userId: '12345'
    });

    if (result.success) {
      console.log('Output:', result.output);
      console.log('Duration:', result.metadata?.duration);
    } else {
      console.error('Workflow failed:', result.error);
    }
  } catch (error) {
    console.error('Error:', error);
  }
}

runWorkflow();

Error Handling

import { SimStudioClient, SimStudioError } from 'simstudio-ts-sdk';

const client = new SimStudioClient({
  apiKey: process.env.SIM_API_KEY!
});

async function executeWithErrorHandling() {
  try {
    const result = await client.executeWorkflow('workflow-id');
    return result;
  } catch (error) {
    if (error instanceof SimStudioError) {
      switch (error.code) {
        case 'UNAUTHORIZED':
          console.error('Invalid API key');
          break;
        case 'TIMEOUT':
          console.error('Workflow execution timed out');
          break;
        case 'USAGE_LIMIT_EXCEEDED':
          console.error('Usage limit exceeded');
          break;
        case 'INVALID_JSON':
          console.error('Invalid JSON in request body');
          break;
        default:
          console.error('Workflow error:', error.message);
      }
    } else {
      console.error('Unexpected error:', error);
    }
    throw error;
  }
}

Environment Configuration

// Using environment variables
const client = new SimStudioClient({
  apiKey: process.env.SIM_API_KEY!,
  baseUrl: process.env.SIM_BASE_URL // optional
});

File Upload

File objects are automatically detected and converted to base64 format. Include them in your input under the field name matching your workflow's API trigger input format:

The SDK converts File objects to this format:

{
  type: 'file',
  data: 'data:mime/type;base64,base64data',
  name: 'filename',
  mime: 'mime/type'
}

Alternatively, you can manually provide files using the URL format:

{
  type: 'url',
  data: 'https://example.com/file.pdf',
  name: 'file.pdf',
  mime: 'application/pdf'
}
import { SimStudioClient } from 'simstudio-ts-sdk';
import fs from 'fs';

const client = new SimStudioClient({
  apiKey: process.env.SIM_API_KEY!
});

// Node.js: Read file and create File object
const fileBuffer = fs.readFileSync('./document.pdf');
const file = new File([fileBuffer], 'document.pdf', { type: 'application/pdf' });

// Include files under the field name from your API trigger's input format
const result = await client.executeWorkflow('workflow-id', {
  documents: [file],  // Field name must match your API trigger's file input field
  instructions: 'Process this document'
});

// Browser: From file input
const handleFileUpload = async (event: Event) => {
  const inputEl = event.target as HTMLInputElement;
  const files = Array.from(inputEl.files || []);

  const result = await client.executeWorkflow('workflow-id', {
    attachments: files,  // Field name must match your API trigger's file input field
    query: 'Analyze these files'
  });
};

Getting Your API Key

  1. Log in to your Sim account
  2. Navigate to your workflow
  3. Click on "Deploy" to deploy your workflow
  4. Select or create an API key during the deployment process
  5. Copy the API key to use in your application

Development

Running Tests

To run the tests locally:

  1. Clone the repository and navigate to the TypeScript SDK directory:

    cd packages/ts-sdk
    
  2. Install dependencies:

    bun install
    
  3. Run the tests:

    bun run test
    

Building

Build the TypeScript SDK:

bun run build

This will compile TypeScript files to JavaScript and generate type declarations in the dist/ directory.

Development Mode

For development with auto-rebuild:

bun run dev

Requirements

  • Node.js 18+
  • TypeScript 5.0+ (for TypeScript projects)

License

Apache-2.0