npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2026 – Pkg Stats / Ryan Hefner

@printmadehq/mockup-generator

v1.0.5

Published

Serverless-optimized TypeScript SDK for generating high-quality product mockups from PSD templates

Downloads

37

Readme

Mockup Generator SDK

A powerful, serverless-optimized TypeScript SDK for generating high-quality product mockups from PSD templates. Built on ag-psd and Photopea, designed for modern cloud environments.

🚀 Features

  • 🌩️ Serverless Ready: Optimized for AWS Lambda, Vercel, Cloudflare Workers
  • 🎨 Smart Object Replacement: Replace any smart object with images from URLs or Buffers
  • 📸 Multi-format Export: Export to PNG, JPG, WebP via HeadlessPhotopea with parallel processing
  • ☁️ Cloud Storage: Built-in R2/S3 integration for asset management
  • 🔧 TypeScript: Full type safety and IntelliSense support
  • 🎯 Simple API: Clean, developer-friendly interface
  • ⚡ Performance: ~11s for 49MB PSD + 3 exports (53% faster with parallel exports)
  • 🛡️ Error Handling: Comprehensive error types and retry mechanisms

📦 Installation

NPM (Recommended for production)

# Install from NPM registry
npm install @printmadehq/mockup-generator

# For TypeScript projects, types are included automatically

Development with Bun

# For development with Bun
bun add @printmadehq/mockup-generator

Prerequisites

This package requires Node.js 18+ and has native dependencies.

Important: You must install canvas separately:

# Install the package
npm install @printmadehq/mockup-generator

# Install canvas peer dependency
npm install canvas

System Requirements for Canvas:

  • macOS: brew install pkg-config cairo pango libpng jpeg giflib librsvg pixman
  • Ubuntu/Debian: sudo apt-get install build-essential libcairo2-dev libpango1.0-dev libjpeg-dev libgif-dev librsvg2-dev
  • CentOS/RHEL: sudo yum install gcc-c++ cairo-devel pango-devel libjpeg-turbo-devel giflib-devel

Most cloud platforms (AWS Lambda, Vercel, etc.) handle canvas automatically.

🏃‍♂️ Quick Start

Basic Usage

import { MockupSDK } from '@printmadehq/mockup-generator';

// Create SDK instance with serverless optimizations
const sdk = new MockupSDK({
  mode: 'serverless',  // Automatic serverless optimizations
  storage: {
    endpoint: 'https://your-r2-endpoint.com',
    accessKeyId: 'your-access-key',
    secretAccessKey: 'your-secret-key',
    bucket: 'your-bucket'
  }
});

// Generate mockup
const result = await sdk.generate({
  psd: 'https://your-bucket.com/templates/shirt.psd', // or Buffer
  replacements: [
    {
      name: 'Design: front',
      image: 'https://your-bucket.com/designs/logo.png', // or Buffer
      fillMode: 'fit'
    }
  ],
  exports: [
    { format: 'png', quality: 90 },
    { format: 'jpg', quality: 85 }
  ]
});

console.log(`Generated PSD: ${result.psd.length} bytes`);
console.log(`Exports: ${result.exports.length} files`);

// Cleanup
await sdk.cleanup();

Environment Variables

Set these environment variables for automatic configuration:

R2_ENDPOINT=https://your-account.r2.cloudflarestorage.com
R2_ACCESS_KEY_ID=your-access-key
R2_SECRET_ACCESS_KEY=your-secret-key
R2_BUCKET=your-bucket
R2_REGION=auto

Then use the factory method:

import { MockupSDK } from '@printmadehq/mockup-generator';

// Auto mode detects environment and loads storage from env vars
const sdk = new MockupSDK({ mode: 'auto' });

// Or use convenience helper
import { createServerlessSDK } from 'mockup-generator-sdk';
const sdk2 = createServerlessSDK(); // Same as { mode: 'serverless' }

⚡ Performance

Benchmark Results

The SDK leverages HeadlessPhotopea for blazing-fast parallel exports:

| Export Type | Original SDK | Optimized SDK | Improvement | |-------------|-------------|---------------|-------------| | Single Format | ~8s | ~8s | - | | 3 Formats | ~24s | ~11s | 53% faster | | 5 Formats | ~40s | ~15s | 63% faster |

Performance Breakdown (49MB PSD, 3 exports)

  • PSD Generation: ~5s (ag-psd processing)
  • Photopea Init: ~2s (one-time setup)
  • Parallel Export: ~4s (PNG + JPG + WebP simultaneously)
  • Total: ~11s

Key Optimizations

  • Parallel Processing: All formats export simultaneously using Promise.all()
  • Single Document: PSD loaded once, all exports from same document
  • Direct API: HeadlessPhotopea provides direct Photopea API access
  • Efficient Transfer: Optimized buffer handling without conversions

🏗️ API Reference

Operation Modes

The SDK uses operation modes for easy configuration:

// Serverless optimized (headless, fast timeout, minimal logging)
const sdk = new MockupSDK({ mode: 'serverless' });

// Development mode (visible browser, verbose logging, longer timeout)
const sdk = new MockupSDK({ mode: 'development' });

// Production mode (balanced settings for production servers)
const sdk = new MockupSDK({ mode: 'production' });

// Auto mode (detects environment, loads storage from env vars)
const sdk = new MockupSDK({ mode: 'auto' });

// Custom mode (override any preset settings)
const sdk = new MockupSDK({ 
  mode: 'serverless', 
  timeout: 30000,  // Override preset
  verbose: true    // Override preset
});

Core Methods

  • generate(config) - Single mockup generation with config object
  • generateBatch(config) - Batch processing for multiple variations
  • upload(result, options) - Upload results to storage (separate from generation)
  • analyze(psd) - Inspect PSD structure without generation

Configuration Types

interface MockupGenerationConfig {
  psd: string | Buffer;              // URL or Buffer
  replacements: SmartObjectReplacement[];
  exports?: ExportOptions[];
}

interface SmartObjectReplacement {
  name: string;                      // Smart object name
  image: string | Buffer;            // Image URL or Buffer
  fillMode?: 'fit' | 'fill' | 'stretch';
  printArea?: {                      // Custom placement area
    x: number; y: number;
    width: number; height: number;
  };
}

🚀 Serverless Examples

AWS Lambda

import { MockupSDK } from '@printmadehq/mockup-generator';

export async function handler(event) {
  // Mode automatically optimizes for serverless
  const sdk = new MockupSDK({ mode: 'serverless' });
  
  try {
    const result = await sdk.generate({
      psd: event.psdUrl,
      replacements: event.replacements,
      exports: event.exports
    });
    
    return {
      statusCode: 200,
      body: JSON.stringify({
        success: true,
        psdSize: result.psd.length,
        exportsCount: result.exports.length
      })
    };
  } finally {
    await sdk.cleanup();
  }
}

Batch Processing

const batchResult = await sdk.generateBatch({
  template: 'https://your-bucket.com/templates/shirt.psd',
  variations: [
    {
      id: 'customer-1',
      replacements: [
        { name: 'Design: front', image: 'https://example.com/logo1.png' }
      ],
      exports: [{ format: 'png' }],
      metadata: { customerId: 'cust_123' }
    },
    {
      id: 'customer-2', 
      replacements: [
        { name: 'Design: front', image: 'https://example.com/logo2.png' }
      ],
      exports: [{ format: 'png' }, { format: 'jpg' }]
    }
  ]
});

console.log(`Processed ${batchResult.results.length} variations`);

📚 Documentation

🛠️ Development

# Install dependencies
bun install

# Build SDK
bun run build

# Run examples
bun examples/new-api-demo.ts

# Legacy CLI (still available)
bun src/cli.ts --help

📦 Publishing to NPM

This package is configured for public NPM publishing:

# Build the package
bun run build

# Login to NPM (one time setup)
npm login

# Publish as public scoped package
npm publish

# Note: Scoped packages default to private, but this package is configured for public access

Package Structure

  • dist/index.js - Main entry point (Node.js compatible)
  • dist/index.d.ts - TypeScript definitions
  • src/sdk/index.ts - Development entry point
  • Uses ESM module system with Node.js 18+ compatibility

🔧 Troubleshooting

Canvas Installation Issues

Error: Library not loaded: libpixman-1.0.dylib This error occurs when canvas native dependencies aren't properly installed.

Solution:

  1. Install system dependencies first (see Prerequisites section)
  2. Reinstall canvas:
    npm uninstall canvas
    npm install canvas
  3. For macOS with Homebrew issues:
    # Ensure Homebrew packages are linked
    brew install pixman cairo pango
    brew link --force pixman

Error: canvas.node related errors

  • Ensure canvas is installed in your project's node_modules (not bundled)
  • The package now uses canvas as a peer dependency to avoid bundling issues
  • Make sure you're running npm install canvas in your consumer project

Serverless Deployment Issues:

  • Most platforms provide canvas pre-compiled
  • For custom environments, ensure build tools are available during deployment
  • Consider using platform-specific canvas binaries

📄 License

MIT License - see LICENSE file for details.