0.2.2 • Published 5 months ago

@genwave/svgmaker-sdk v0.2.2

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

SVGMaker SDK for Node.js

Official Node.js SDK for the SVGMaker API, providing a clean, type-safe interface for generating, editing, and converting SVG graphics using AI.

npm version License

Features

  • šŸŽØ Complete API Coverage: Generate, edit, and convert SVGs with AI
  • 🧰 TypeScript Native: Full type safety with comprehensive type definitions
  • āš™ļø Configuration-Based: Clean, object-based parameter configuration
  • šŸ”„ Automatic Retries: Built-in retry logic with exponential backoff
  • 🌊 Streaming Support: Real-time progress updates via Server-Sent Events
  • āœ… Input Validation: Zod-based schema validation for all requests
  • šŸ“¦ Dual Package: ESM and CommonJS support with proper exports
  • šŸ”Œ Extensible: Request/response interceptors for customization

Installation

npm install @genwave/svgmaker-sdk

Quick Start

import { SVGMakerClient } from '@genwave/svgmaker-sdk';

// Initialize client
const client = new SVGMakerClient('your-api-key');

// Generate an SVG
const result = await client.generate
  .configure({
    prompt: 'A minimalist mountain landscape',
    quality: 'high',
    styleParams: {
      style: 'minimalist',
    },
    svgText: true, // Get SVG source code
  })
  .execute();

console.log('SVG URL:', result.svgUrl);
console.log('Credits used:', result.creditCost);

Core API

Client Initialization

// Basic client
const client = new SVGMakerClient('your-api-key');

// Client with custom configuration
const client = new SVGMakerClient('your-api-key', {
  timeout: 60000,
  maxRetries: 5,
  logging: true,
});

Generate SVG

Create SVGs from text descriptions using AI.

const result = await client.generate
  .configure({
    prompt: 'A geometric mountain landscape with sun',
    quality: 'high',
    aspectRatio: 'landscape',
    styleParams: {
      style: 'minimalist',
      color_mode: 'monochrome',
      composition: 'center-object',
      advanced: {
        stroke_weight: 'thin',
        corner_style: 'rounded',
        shadow_effect: 'none'
      }
    },
    base64Png: true, // Include PNG preview
    svgText: true,   // Include SVG source
  })
  .execute();

// Access results
console.log('SVG URL:', result.svgUrl);
console.log('Credits used:', result.creditCost);
console.log('Revised prompt:', result.revisedPrompt);

if (result.pngImageData) {
  // PNG preview as Buffer
  console.log('PNG size:', result.pngImageData.length, 'bytes');
}

if (result.svgText) {
  // SVG source code
  console.log('SVG content:', result.svgText);
}

Generation Parameters

ParameterTypeDefaultDescription
promptstring-Required. Description of the SVG to generate
quality'low' \| 'medium' \| 'high''medium'Generation quality level
aspectRatio'auto' \| 'portrait' \| 'landscape' \| 'square' \| 'wide' \| 'tall''auto' for low/medium, 'square' for highOutput aspect ratio. Note: Low and medium quality only support 'auto', 'portrait', 'landscape', 'square'. High quality supports all options except 'auto'
background'auto' \| 'transparent' \| 'opaque''auto'Background type
styleParamsStyleParams{}Style parameters object (see StyleParams table below)
base64PngbooleanfalseInclude PNG preview in response
svgTextbooleanfalseInclude SVG source code in response

StyleParams Object

ParameterTypeDefaultDescription
style'minimalist' \| 'cartoon' \| 'realistic' \| 'abstract' \| 'flat' \| 'isometric'noneArt style preference
color_mode'monochrome' \| '2-colors' \| '3-colors' \| 'full-color'noneColor scheme preference
image_complexity'simple' \| 'detailed'noneComplexity level
category'icon' \| 'illustration' \| 'pattern' \| 'logo' \| 'scene'noneContent category
composition'center-object' \| 'full-scene'noneLayout composition
advancedAdvancedStyleParams{}Advanced styling parameters (see AdvancedStyleParams table below)

AdvancedStyleParams Object

ParameterTypeDefaultDescription
stroke_weight'thin' \| 'medium' \| 'thick'noneStroke weight for lines and shapes
corner_style'none' \| 'rounded' \| 'sharp'noneCorner style for shapes
shadow_effect'none' \| 'soft' \| 'hard'noneShadow effect type

Edit SVG/Image

Modify existing images or SVGs using AI-powered editing.

// Basic editing
const result = await client.edit
  .configure({
    image: './input.png',
    prompt: 'Add a red border and make it more vibrant',
    quality: 'medium',
    base64Png: true,
    svgText: true,
  })
  .execute();

// Advanced editing with style parameters
const result = await client.edit
  .configure({
    image: fs.readFileSync('./input.svg'),
    prompt: 'Make this more cartoonish',
    styleParams: {
      style: 'cartoon',
      color_mode: '3-colors',
      advanced: {
        stroke_weight: 'medium',
        corner_style: 'rounded'
      }
    },
    mask: './mask.png', // Optional mask for targeted editing
  })
  .execute();

Edit Parameters

ParameterTypeDefaultDescription
imagestring \| Buffer \| Readable-Required. Image file to edit (file path, Buffer, or Readable stream)
promptstring-Required. Edit instructions as a simple text string
styleParamsStyleParams{}Style parameters object (see StyleParams table above)
maskstring \| Buffer \| ReadablenoneOptional mask for targeted editing (file path, Buffer, or Readable stream)
quality'low' \| 'medium' \| 'high''medium'Processing quality
aspectRatio'auto' \| 'portrait' \| 'landscape' \| 'square' \| 'wide' \| 'tall''auto' for low/medium, 'square' for highOutput aspect ratio. Note: Low and medium quality only support 'auto', 'portrait', 'landscape', 'square'. High quality supports all options except 'auto'
background'auto' \| 'transparent' \| 'opaque''auto'Background handling
base64PngbooleanfalseInclude PNG preview in response
svgTextbooleanfalseInclude SVG source code in response

Convert Image to SVG

Convert raster images to vector SVG format.

const result = await client.convert
  .configure({
    file: './photo.jpg',
    svgText: true,
  })
  .execute();

console.log('Original:', result.originalImageUrl);
console.log('SVG:', result.svgUrl);
console.log('SVG source:', result.svgText);

Streaming Responses

All operations support real-time progress updates via streaming.

const stream = client.generate
  .configure({
    prompt: 'A detailed cityscape illustration',
    quality: 'high',
  })
  .stream();

for await (const event of stream) {
  switch (event.status) {
    case 'processing':
      console.log(`Progress: ${event.message}`);
      break;
    case 'complete':
      console.log(`Complete! SVG: ${event.svgUrl}`);
      break;
    case 'error':
      console.error(`Error: ${event.error}`);
      break;
  }
}

Configuration

Client Configuration

interface SVGMakerConfig {
  apiKey: string;                    // API authentication key
  baseUrl: string;                   // API base URL (default: "https://svgmaker.io/api")
  timeout: number;                   // Request timeout ms (default: 30000)
  maxRetries: number;                // Max retry attempts (default: 3)
  retryBackoffFactor: number;        // Retry delay factor ms (default: 300)
  retryStatusCodes: number[];        // Status codes to retry (default: [408, 429, 500, 502, 503, 504])
  logging: boolean;                  // Enable request logging (default: false)
  logLevel: 'debug' | 'info' | 'warn' | 'error'; // Log level (default: "info")
  caching: boolean;                  // Enable response caching (default: false)
  cacheTTL: number;                  // Cache TTL ms (default: 300000)
  rateLimit: number;                 // Requests per minute (default: 60)
}

Example Configuration

const client = new SVGMakerClient('your-api-key', {
  timeout: 60000,
  maxRetries: 5,
  logging: true,
  logLevel: 'debug',
  caching: true,
  cacheTTL: 600000, // 10 minutes
});

Logging

The SDK includes built-in logging functionality for debugging and monitoring API requests.

Enable Logging

// Basic logging
const client = new SVGMakerClient('your-api-key', {
  logging: true,
  logLevel: 'info', // 'debug' | 'info' | 'warn' | 'error'
});

// Development (verbose)
const client = new SVGMakerClient('your-api-key', {
  logging: true,
  logLevel: 'debug',
});

// Production (errors only)
const client = new SVGMakerClient('your-api-key', {
  logging: true,
  logLevel: 'error',
});

Log Output

[SVGMaker SDK][2024-01-15T10:30:45.123Z][INFO] SVGMaker SDK initialized
[SVGMaker SDK][2024-01-15T10:30:46.250Z][DEBUG] Making API request to /generate

Runtime Configuration

// Change log level during runtime
client.setConfig({
  logging: true,
  logLevel: 'warn',
});

Error Handling

The SDK provides comprehensive error handling with custom error types.

import { SVGMakerClient, Errors } from '@genwave/svgmaker-sdk';

try {
  const result = await client.generate
    .configure({ prompt: 'A landscape' })
    .execute();
} catch (error) {
  if (error instanceof Errors.ValidationError) {
    console.error('Invalid parameters:', error.message);
  } else if (error instanceof Errors.APIError) {
    console.error('API error:', error.message, error.statusCode);
  } else if (error instanceof Errors.RateLimitError) {
    console.error('Rate limited. Retry after:', error.retryAfter, 'seconds');
  } else if (error instanceof Errors.AuthError) {
    console.error('Authentication failed:', error.message);
  } else if (error instanceof Errors.TimeoutError) {
    console.error('Request timed out after:', error.timeout, 'ms');
  } else if (error instanceof Errors.NetworkError) {
    console.error('Network error:', error.message);
  } else if (error instanceof Errors.InsufficientCreditsError) {
    console.error('Insufficient credits. Required:', error.creditsRequired);
  } else if (error instanceof Errors.ContentSafetyError) {
    console.error('Content safety violation:', error.message);
  } else if (error instanceof Errors.FileSizeError) {
    console.error('File too large:', error.message);
  } else if (error instanceof Errors.FileFormatError) {
    console.error('Unsupported file format:', error.message);
  }
}

Advanced Features

Request/Response Interceptors

Customize requests and responses with interceptors.

// Add request interceptor
client.addRequestInterceptor(async (request) => {
  console.log('Making request:', request.url);
  return request;
});

// Add response interceptor
client.addResponseInterceptor(async (response) => {
  console.log('Received response:', response);
  return response;
});

Dynamic Configuration

Update client configuration at runtime.

// Update configuration
client.setConfig({
  timeout: 120000,
  maxRetries: 2,
});

// Get current configuration
const config = client.getConfig();
console.log('Current timeout:', config.timeout);

TypeScript Support

Full TypeScript support with comprehensive type definitions.

import { SVGMakerClient, Types } from '@genwave/svgmaker-sdk';

// Typed parameters
const generateParams: Types.GenerateParams = {
  prompt: 'A minimalist logo',
  quality: 'high',
  style: 'minimalist',
  color_mode: 'monochrome',
};

// Typed responses
const result: Types.GenerateResponse = await client.generate
  .configure(generateParams)
  .execute();

// Type-safe access
console.log(result.svgUrl);      // string
console.log(result.creditCost);  // number
console.log(result.pngImageData); // Buffer | undefined

Package Structure

@genwave/svgmaker-sdk/
ā”œā”€ā”€ dist/
│   ā”œā”€ā”€ cjs/         # CommonJS build
│   ā”œā”€ā”€ esm/         # ES Module build
│   └── types/       # TypeScript declarations
ā”œā”€ā”€ src/
│   ā”œā”€ā”€ core/        # Core client implementation
│   ā”œā”€ā”€ clients/     # API-specific clients
│   ā”œā”€ā”€ types/       # TypeScript definitions
│   ā”œā”€ā”€ errors/      # Custom error classes
│   └── utils/       # Utility functions
└── examples/        # Usage examples

Browser Compatibility

The SDK is designed for Node.js environments and requires Node.js 16.0.0 or higher. For browser usage, consider the potential limitations with file system operations and ensure proper bundling configuration.

Contributing

We welcome contributions! Please see CONTRIBUTING.md for guidelines.

License

MIT License - see the LICENSE file for details.

Support

0.2.2

5 months ago