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

sudomock

v2.18.1

Published

Official Node.js/TypeScript SDK for the SudoMock API - mockup generation from ready-made mockups, PSD files and product photos

Readme

SudoMock Node.js SDK

Official Node.js/TypeScript SDK for the SudoMock API. Start from a free library of 6,800+ ready-made mockups, or bring your own Photoshop file or product photo, and get the finished image back.

Installation

npm install sudomock

Requirements: Node.js 20+ (uses native fetch)

Quick Start

import SudoMock from 'sudomock'

const client = new SudoMock('sm_your_api_key')
// or set SUDOMOCK_API_KEY env var and call: new SudoMock()

// List your mockups
const { mockups, total } = await client.psdMockups.list({ limit: 10 })
console.log(`Found ${total} mockups`)

// Render a mockup with artwork
const render = await client.renders.create({
  mockupId: mockups[0].uuid,
  smartObjects: [{
    uuid: mockups[0].smartObjects[0].uuid,
    asset: { url: 'https://example.com/design.png' },
  }],
  exportOptions: { imageFormat: 'webp', imageSize: 1080 },
})
console.log(render.url) // https://cdn.sudomock.com/renders/...

API Reference

Client

import SudoMock from 'sudomock'

const client = new SudoMock('sm_xxx', {
  baseUrl: 'https://api.sudomock.com', // default
  timeout: 30_000,                      // default (ms)
  maxRetries: 2,                        // default
})

The API key can be passed as the first argument or via the SUDOMOCK_API_KEY environment variable.

Every request identifies itself with X-SudoMock-Client: node-sdk/<version> (and the same value as User-Agent where the runtime allows it), so you can pick the SDK's traffic out of your own logs and proxy rules.

client.ai and client.mockups are the earlier names of client.photoMockups and client.psdMockups. Each stays on the endpoint it was published on, so an async job you open through an earlier name comes back under the 2d_* kind it always did, and each warns once per process. Switch to client.photoMockups / client.psdMockups to move to the family paths and the photo_mockup_* kinds. Both earlier names accept assignment, so a test double can replace them.

PSD Mockups (client.psdMockups)

// List mockups with pagination and filtering
const result = await client.psdMockups.list({
  limit: 20,
  offset: 0,
  name: 'shirt',        // case-insensitive contains
  sort: 'created_at',   // 'name' | 'created_at' | 'updated_at'
  order: 'desc',        // 'asc' | 'desc'
  folderUuid: 'uuid',   // one folder, or 'root' for the top of the library
})

// Get a single mockup
const mockup = await client.psdMockups.get('uuid')
console.log(mockup.smartObjects)

// List every layer, nested as in Photoshop's Layers panel
const { layers } = await client.psdMockups.layers('uuid')

// Rename a mockup, or move it to another folder
const updated = await client.psdMockups.update('uuid', { name: 'New Name' })
await client.psdMockups.update('uuid', { folderUuid: 'folder-uuid' })
await client.psdMockups.update('uuid', { folderUuid: null })  // top of library

// Delete a mockup
await client.psdMockups.delete('uuid')

Bulk delete all mockups (DELETE /api/v1/psd-mockups/all) requires a dashboard Bearer token and is not callable with an API key (the API returns 403). It is therefore intentionally not exposed by this SDK -- use the dashboard.

Renders

const render = await client.renders.create({
  mockupId: 'mockup-uuid',
  smartObjects: [{
    uuid: 'smart-object-uuid',
    asset: {
      url: 'https://example.com/artwork.png',
      fit: 'fill',           // 'fill' | 'contain' | 'cover'
      rotate: 0,
      flipHorizontal: false,
      flipVertical: false,
    },
    color: {
      hex: '#ff0000',
      blendingMode: 'multiply',
    },
  }],
  exportOptions: {
    imageFormat: 'webp',  // 'png' | 'jpg' | 'webp' (default 'webp')
    imageSize: 2048,      // width in px, 100-10000 (default 2048), or 'original'
    quality: 90,          // 1-100 (default 90)
    dpi: 300,             // optional, 72-2400: print resolution metadata (opt-in)
  },
  exportLabel: 'my-render',
})

console.log(render.url)        // convenience: first file URL
console.log(render.printFiles) // full array

Repeat the artwork as a pattern

Set tile: true on an asset to repeat the artwork across the whole smart object. size is then one tile, fit places the artwork inside each tile, and position sets where the grid starts. A tile needs a size; without one the API answers 422. tileSpacing leaves a gap between the tiles: a percentage of the tile size, 0 to 100, so the horizontal gap is that percent of the tile width and the vertical gap that percent of the tile height. It is used only when tile is true.

const render = await client.renders.create({
  mockupId: 'mockup-uuid',
  smartObjects: [{
    uuid: 'smart-object-uuid',
    asset: {
      url: 'https://example.com/pattern.png',
      fit: 'fill',
      size: { width: 600, height: 600 },
      tile: true,
      tileSpacing: 25,
    },
  }],
})

The render mode of renders.createVideo takes the same two fields on its smart objects.

Batch text personalization

Use an editable text layer from the mockup response to create personalized outputs. smartObjects is optional for text-only renders, and fit defaults to 'overflow'.

const mockup = await client.psdMockups.get('mockup-uuid')
const nameLayer = mockup.textLayers.find((layer) => layer.name === 'Customer Name')
if (!nameLayer?.isEditable) throw new Error('Customer Name is not editable')

const names = ['Aylin', 'Deniz', 'Mert']
const renders = await Promise.all(names.map((name) => client.renders.create({
  mockupId: mockup.uuid,
  textLayers: [{
    uuid: nameLayer.uuid,
    text: name,
    font: 'Montserrat-Bold',
    color: '#FFFFFF',
    fit: 'overflow',
  }],
})))

for (const render of renders) {
  console.log(render.url)
  for (const warning of render.warnings ?? []) console.warn(warning.code, warning.message)
}

Hide layers for one render

hiddenLayers leaves up to 50 layers out of a single render; the template itself does not change. client.psdMockups.layers() lists every layer of the template with its UUID, including the layers inside a smart object's contents. Hiding a group hides every layer inside it, a layer hidden inside a smart object is hidden in every copy of it, and hiddenLayers works on its own.

const { layers } = await client.psdMockups.layers('mockup-uuid')
const badge = layers.find((layer) => layer.name === 'Sleeve badge')
if (!badge) throw new Error('Sleeve badge not found')

const render = await client.renders.create({
  mockupId: 'mockup-uuid',
  hiddenLayers: [badge.uuid],
})

Async Renders & Jobs

Pass isAsync: true to enqueue a render instead of blocking. The API responds with 202 Accepted and renders.create resolves with a Job (TypeScript narrows the return type via overload). Poll it with client.jobs:

const job = await client.renders.create({
  mockupId: 'mockup-uuid',
  smartObjects: [{ uuid: 'so-uuid', asset: { url: 'https://example.com/art.png' } }],
  isAsync: true,
})
console.log(job.jobId, job.status) // 'queued'

// Poll a single time:
const status = await client.jobs.retrieve(job.jobId)

// ...or wait until it finishes (succeeded | failed):
const done = await client.jobs.waitForJob(job.jobId, {
  intervalMs: 2000,   // default
  timeoutMs: 300_000, // default; throws TimeoutError if exceeded
})
if (done.status === 'failed') throw new Error(done.error ?? 'render failed')
console.log(done.resultUrl)

waitForJob does NOT throw on a failed job -- inspect status and error. It throws TimeoutError only when the job is still running past timeoutMs.

List and page your jobs (keyset pagination, newest first). Filter by kind (render | video | upload | 2d_create | 2d_render | photo_mockup_create | photo_mockup_render | seam_fix) and/or mockupUuid. A photo-mockup job is spelled photo_mockup_* when submitted on /api/v1/photo-mockups (where client.photoMockups posts since 2.7.0) and 2d_* when submitted on the earlier /api/v1/sudoai/2d-mockups path; filtering by either spelling returns both:

const { jobs, nextCursor } = await client.jobs.list({ kind: 'video', limit: 50 })
if (nextCursor) {
  const next = await client.jobs.list({ cursor: nextCursor })
}

Video Renders

renders.createVideo animates a mockup. It is always asynchronous and returns a Job of kind 'video'. Credit cost scales with duration, audio, and the automatically selected quality tier. Every account gets one video at no charge, once, for the lifetime of the account. Unsupported durationSeconds values return a 400.

const job = await client.renders.createVideo({
  mockupId: 'mockup-uuid',
  smartObjects: [{ uuid: 'so-uuid', asset: { url: 'https://example.com/art.png' } }],
  video: { durationSeconds: 4, audio: false },
})
const done = await client.jobs.waitForJob(job.jobId)
console.log(done.resultUrl) // mp4 URL

video.motion ('ambient' | 'showcase', default 'ambient') controls the camera movement. You can also animate a raw image directly (no mockup) and attach a per-call webhook:

const job = await client.renders.createVideo({
  imageUrl: 'https://example.com/art.png', // raw-image mode
  video: { durationSeconds: 4, motion: 'showcase' },
  webhook: { url: 'https://example.com/hooks/sudomock' },
})

Ready-Made Mockups (client.readyMadeMockups)

SudoMock's free library of ready-made mockups is a catalogue of product scenes that needs no file of your own. Reading it is free, and every scene in it is free to start from. A mockup is one view of a scene (front, folded, flat lay, lifestyle, close-up) and a template is the set of views of that scene, so a search answers with templates and each one carries its views with the address to render from.

This is SudoMock's catalogue, not your account's own mockups: those are client.psdMockups, client.photoMockups and client.folders.

The four steps, in the order the guide uses them:

// 1. Search the catalogue.
const { templates, totalMockups } = await client.readyMadeMockups.search({
  search: 'coffee mug',
  category: 'drinkware',
  limit: 5,
})

// 2. Read one template for its long-form copy and every facet.
const template = await client.readyMadeMockups.getTemplate(templates[0]!.slug)

// 3. Hand the view you picked to photo mockup creation.
const view = template.mockups![0]!
const mockup = await client.photoMockups.create({ sourceUrl: view.sourceUrl })

// 4. Render your own artwork onto it.
const surface = mockup.surfaces[0]
if (!surface) throw new Error('No surface available')

const result = await client.photoMockups.render({
  mockupId: mockup.mockupId,
  printAreas: [{
    surfaceUuid: surface.surfaceUuid,
    artworkUrl: 'https://example.com/artwork.png',
    placement: { coverage: 60 },
  }],
})
console.log(result.url)

Steps 1 and 2 cost nothing. Step 3 makes the view a reusable mockup on your account, and step 4 renders it; both are priced in Pricing in one paragraph.

Filters on search(): search (free text over title and description), category, subcategory, productType, tags, platforms, industries, useCases, isFeatured, plus page, limit, sortBy and sortOrder. An array filter is sent as one comma-separated value; leave a filter out and it is not sent at all. The page carries totalTemplates, totalMockups, page, limit and pages.

Photo Mockups (client.photoMockups)

Render artwork onto an existing 2D mockup (no PSD template) and manage your 2D mockup catalog. client.photoMockups.render posts to /api/v1/photo-mockups/{mockupId}/render (the mockup id lives in the path) and costs 5 credits per call. Each print area must supply artworkUrl OR color. Use uuid for a saved print area (a bounded zone drawn on the product) or surfaceUuid for a surface (a printable product in the photo, or the main wall of a room photo), both returned by client.photoMockups.get(). A product can have both, and they are separate targets. Placement follows the target, and sizing has one answer per request: a surface takes a coverage percentage or an explicit width + height, a print area takes a fit or an explicit width + height. Anchoring -- position, offsetX, offsetY, rotation -- belongs to both. The types enforce it, so handing one the other's dial does not compile.

tile: true on a placement repeats the artwork as a pattern across the whole target. The sizing answer (coverage, fit, or width and height) is one tile, and position with offsetX and offsetY sets where the grid starts. tileSpacing sets the gap between tiles, as on a PSD asset. Each entry in mockup.surfaces carries a label, what the surface is, such as pillow or wall, so you can tell surfaces apart before you pick one.

Render an existing 2D mockup

const result = await client.photoMockups.render({
  mockupId: 'mockup-uuid',
  printAreas: [{
    uuid: 'print-area-uuid',
    artworkUrl: 'https://example.com/design.png',
    adjustments: { opacity: 90, vibrance: 10, blur: 0 },
  }],
  exportOptions: { imageFormat: 'webp', imageSize: 2048, quality: 90 },
})

console.log(result.url)                        // first rendered file
console.log(result.renderUuid)                 // correlate with webhooks
console.log(result.printFiles[0].durationMs)   // 2340
console.log(result.printFiles[0].exportFormat) // 'webp'

Prefer to render in the background? Pass isAsync: true and render() resolves with a Job of kind 'photo_mockup_render' (202 Accepted) you await with jobs.waitForJob. A photo_mockup_render.succeeded / photo_mockup_render.failed webhook also fires (2d_render.succeeded / 2d_render.failed on an endpoint that keeps the legacy event names).

const job = await client.photoMockups.render({
  mockupId: 'mockup-uuid',
  printAreas: [{
    uuid: 'print-area-uuid',
    artworkUrl: 'https://example.com/design.png',
  }],
  isAsync: true,
})

const done = await client.jobs.waitForJob(job.jobId)
if (done.status === 'failed') throw new Error(done.error ?? 'render failed')
console.log(done.resultUrl) // rendered file URL

2D mockups: create via API

Create a reusable 2D mockup, then render artwork. By default creation is synchronous: create() resolves with the ready mockup (including its quads). Creation costs 25 credits. If the source image is unsuitable, the 25 credits are refunded automatically.

const mockup = await client.photoMockups.create({
  sourceUrl: 'https://example.com/product.jpg',
  name: 'Front view',
  idempotencyKey: 'front-view-v1',
  folderUuid: 'folder-uuid',      // optional, where it lands
})

const printArea = mockup.quads[0]
if (!printArea) throw new Error('No print area available')

const result = await client.photoMockups.render({
  mockupId: mockup.mockupId,
  printAreas: [{
    uuid: printArea.printAreaId,
    artworkUrl: 'https://example.com/design.png',
  }],
})
console.log(result.url)

const fullSurface = mockup.surfaces[0]
if (fullSurface) {
  await client.photoMockups.render({
    mockupId: mockup.mockupId,
    printAreas: [{
      surfaceUuid: fullSurface.surfaceUuid,
      artworkUrl: 'https://example.com/design.png',
    }],
  })
}

Prefer to create in the background? Pass isAsync: true and create() resolves with a Job you await with waitForReady:

const job = await client.photoMockups.create({
  sourceUrl: 'https://example.com/product.jpg',
  isAsync: true,
})
const mockup = await client.photoMockups.waitForReady(job, { intervalMs: 2_000 })

Update all print areas on a ready mockup with up to 8 four-point quads (each with an optional name, 0 credits). An empty array is accepted only when the API has verified every surface as printable; each of those is then a render target in its own right. An area sent with the printAreaId of one of the mockup's print areas keeps that id; an area without one gets a new id:

const updated = await client.photoMockups.updatePrintAreas('mockup-uuid', [{
  points: [[100, 100], [900, 100], [900, 900], [100, 900]],
  name: 'Front',
  printAreaId: 'existing-print-area-uuid',
}])
console.log(updated.printAreas)

Manage the 2D-mockup catalog:

const { mockups, total } = await client.photoMockups.list({
  limit: 50,
  customizableOnly: true,
  folderUuid: 'root',             // one folder, or the top of the library
})
console.log(mockups[0]?.customizable)
const mockup = await client.photoMockups.get('mockup-uuid')
await client.photoMockups.delete('mockup-uuid')

Background Removal (client.images)

Remove the background from an image; returns a public transparent-PNG cutout URL that stays available for 7 days and that you can pass straight back as render artwork. Supply exactly one of url or base64. Costs 5 credits per image; credits are refunded automatically if processing fails.

const cutout = await client.images.removeBackground({
  url: 'https://example.com/product-photo.jpg',
})

console.log(cutout.url)            // public transparent-PNG URL
console.log(cutout.width, cutout.height)
console.log(cutout.creditsCharged) // 5

// Reuse the cutout URL across renders for 7 days
const render = await client.renders.create({
  mockupId: 'mockup-uuid',
  smartObjects: [{ uuid: 'so-uuid', asset: { url: cutout.url } }],
})

To clean artwork inline during a render instead, set removeBackground: true on the render asset or 2D print area. It adds 5 credits per unique artwork to the render (the same artwork reused across several smart objects or print areas is charged once).

// PSD render
await client.renders.create({
  mockupId: 'mockup-uuid',
  smartObjects: [{
    uuid: 'so-uuid',
    asset: { url: 'https://example.com/photo.jpg', removeBackground: true },
  }],
})

// 2D render
await client.photoMockups.render({
  mockupId: 'mockup-uuid',
  printAreas: [{
    uuid: 'print-area-uuid',
    artworkUrl: 'https://example.com/photo.jpg',
    removeBackground: true,
  }],
})

Seam Check and Fix (client.images)

Before you repeat an artwork as a pattern (tile: true), check that copies of the tile meet without a visible line. Seam check: free. Seam fix: 60 credits, refunded if the fix fails.

checkSeams takes exactly one of url or base64. Pass cropAspect (width divided by height) when the render places the tile with fit: 'crop', so the check sees exactly the tile the render shows.

const check = await client.images.checkSeams({
  url: 'https://example.com/pattern-tile.png',
})

console.log(check.status)  // 'seamless' | 'faint_seam' | 'visible_seam'
console.log(check.seams)   // [{ side: 'left_right', status: 'visible_seam', ranges: [[0, 412]] }]
console.log(check.fixable, check.unfixableReason) // true, null
console.log(check.previousFix) // your latest fix of this same tile, or null

fixSeams takes the same fields and runs as a job of kind 'seam_fix'. The fixed tile keeps its width and height. A tile with transparent edges, or one larger than a fix takes, is refused with a ValidationError and nothing is charged.

const job = await client.images.fixSeams({
  url: 'https://example.com/pattern-tile.png',
})
const done = await client.jobs.waitForJob(job.jobId)

if (done.status === 'succeeded') {
  console.log(done.resultUrl)      // the fixed tile
  console.log(done.alternativeUrl) // a second fixed version, or null
  console.log(done.resultStatus)   // the fixed tile, checked again at no cost
  console.log(done.changes)        // 'edges' | 'whole_tile' | 'rearranged'
  console.log(done.fineDetail)     // 'unchanged' | 'softer'
  console.log(done.changedArea)    // 'part' | 'whole'
} else if (done.errorCode === 'TILE_NOT_FIXABLE') {
  console.log(done.errorDetails?.reason) // 'not_a_pattern_tile' | 'no_clean_result'
}

A fix that cannot make the tile repeat cleanly fails with errorCode 'TILE_NOT_FIXABLE' and is refunded. errorDetails.reason says why: not_a_pattern_tile when the image is not a repeating pattern tile, no_clean_result when no fixed version of the tile repeated cleanly.

While the job runs, client.jobs.retrieve(job.jobId) reports stage: queued, fixing or finishing. Each call sends a fresh Idempotency-Key; pass idempotencyKey to retry the same fix without paying twice. A later check of the same tile hands the result back in previousFix at no cost. To be told when a fix ends instead of polling, subscribe a webhook endpoint to seam_fix.succeeded and seam_fix.failed; their payload carries result_url and alternative_url.

Once a seam check has found a visible seam in a tile, a PSD or photo mockup render that repeats that tile with no gap between copies still completes, and its warnings carry the code TILE_SEAM_VISIBLE.

const render = await client.photoMockups.render({
  mockupId: 'mockup-uuid',
  printAreas: [{
    uuid: 'print-area-uuid',
    artworkUrl: 'https://example.com/pattern-tile.png',
    placement: { fit: 'fit', tile: true },
  }],
})

for (const warning of render.warnings ?? []) {
  if (warning.code === 'TILE_SEAM_VISIBLE') console.log(warning.message)
}

Uploads

const mockup = await client.uploads.create({
  psdFileUrl: 'https://example.com/mockup.psd',
  psdName: 'My T-Shirt Mockup',  // optional
  folderUuid: 'folder-uuid',     // optional, where it lands
})

console.log(mockup.uuid)
console.log(mockup.smartObjects)
console.log(mockup.thumbnails)

PSD upload is FREE (0 credits). Pass isAsync: true to process in the background -- the call returns a Job (202) you poll via client.jobs:

const job = await client.uploads.create({
  psdFileUrl: 'https://example.com/mockup.psd',
  isAsync: true,
})
const done = await client.jobs.waitForJob(job.jobId)
console.log(done.mockupUuid)

Folders (client.folders)

Folders keep a large library in a tree. PSD mockups and photo mockups share that tree, every mockup sits in exactly one folder or at the top of the library, and folders nest. Moving never changes a mockup's uuid, so renders, webhooks and integrations keep working against the uuid they already hold. Every call here is free.

// List folders, by name. 'root' lists the ones at the top of the library,
// a uuid lists the ones inside that folder, and leaving it out lists them all
const { folders, total } = await client.folders.list({ parentUuid: 'root' })

// Create one, at the top of the library or inside another folder
const folder = await client.folders.create({ name: 'Frames' })
const child = await client.folders.create({
  name: '8x10',
  parentUuid: folder.uuid,
})

// Read the trail above a folder and what it holds at any depth
const detail = await client.folders.get(folder.uuid)
console.log(detail.path, detail.totalPsdMockupCount)

// Rename it, move it, or both. parentUuid null is the top of the library,
// and a field left out is left alone
await client.folders.update(child.uuid, { name: 'Frames 8x10' })
await client.folders.update(child.uuid, { parentUuid: null })

// Move any mix of mockups and folders in one call. All of it moves or none
await client.folders.move({
  targetFolderUuid: folder.uuid,
  psdMockupUuids: ['mockup-uuid'],
  photoMockupUuids: [],
  folderUuids: [],
})

// Delete. An empty folder goes on its own; a full one needs recursive,
// which also deletes the mockups inside it and cannot be undone
const gone = await client.folders.delete(folder.uuid, { recursive: true })
console.log(gone.deletedFolders, gone.deletedPsdMockups)

A name has to be unique among the folders beside it, whatever the capitalisation, so the same create call can safely be made twice. Read the folder first to tell someone what a recursive delete would remove: the total counts on get are exactly those numbers.

Account

const account = await client.account.get()

console.log(account.account.email)
console.log(account.subscription.plan)          // plan slug
console.log(account.subscription.tier)          // plan tier
console.log(account.subscription.billingChannel) // 'shopify' | 'stripe' | 'none'
console.log(account.usage.creditsRemaining)     // 4750
console.log(account.usage.creditsLimit)         // 5000  (Starter 5K)
console.log(account.usage.prepaidBalance)       // 12.5
console.log(account.usage.prepaidBalanceCurrency) // 'USD'
console.log(account.apiKey.totalRequests)       // 1234
console.log(account.organization?.name)         // 'Acme Prints'

An account is funded either by a subscription allowance or by a prepaid balance, and the two are independent. creditsLimit is the allowance; prepaidBalance is money the account holds and spends per render. An account paying as it goes has no allowance, so it reports creditsLimit: 0 and creditsRemaining: 0 while being perfectly able to pay. Show only those two and a funded customer reads as 0 / 0.

const { usage } = await client.account.get()

if (usage.creditsLimit > 0) {
  console.log(`${usage.creditsRemaining} of ${usage.creditsLimit} credits left`)
}
if (usage.prepaidBalance > 0) {
  console.log(`${usage.prepaidBalance.toFixed(2)} ${usage.prepaidBalanceCurrency} balance`)
}
if (usage.creditsRemaining === 0 && usage.prepaidBalance === 0) {
  console.log('No credits or balance. Add a credit card.')
}

Draw a progress bar from creditsLimit only. A balance is an amount, not a fraction, so it has no denominator to be a percentage of.

Pricing in one paragraph

Subscriptions from $0.002 per render. Without one, $0.05 per render, the same rate standalone mockup APIs charge on a paid plan. The first payment into the balance is at least $5. 2D Mockups and video are priced by what they cost to produce, not at the flat render rate. A new account gets 500 credits once and no card is required to spend them, but until a card is verified its renders are watermarked and capped at 1,024 px, it can keep 5 PSD templates, and one render runs at a time. Funding the $5 minimum lifts every one of those: the watermark and the width cap come off, the stored-template limit goes to 150, and renders run 25 at a time alongside 10 concurrent uploads. There is no separate "free plan": that account is on the pay-as-you-go tier, unfunded.

Studio

Create customization sessions for the Studio iframe (print-on-demand integrations).

const session = await client.studio.createSession({
  mockupType: '2d',
  sessionKind: 'customize',
  mockupUuid: 'uuid',
  allowedOrigin: 'https://store.example.com',
  productId: 'product-123',          // optional
  variantId: 'variant-456',          // optional
  actionId: 'add-to-cart',           // optional
  ui: {
    primaryActionLabel: 'Add to cart',
    secondaryActionLabel: 'Preview',
    accentColor: '#3366FF',
  },
})

// Open Studio iframe:
// studio.sudomock.com/editor?session=<session.session>
console.log(session.session)    // 'sess_xxx...'
console.log(session.expiresIn)  // 900 (seconds)
console.log(session.messageSessionId)
console.log(session.bootstrapSecret) // keep secret; never put it in the iframe URL

Use sessionKind: 'setup' to create or edit a 2D mockup with setup controls. Use customize for a shopper working on a prepared mockup. Setup emits studio.mockup-saved; customize emits studio.design-submitted. The browser message is a wire payload, so its stable fields remain snake case. Every result has mockup_uuid, render_uuid, and the optional action_id. Treat render_uuid as the opaque confirmation handle; the parent page does not receive editor revision state.

On your server, confirm that browser message before saving the mockup or adding anything to a cart:

const receipt = await client.studio.consumeAction(event, {
  productId: 'product-123',
  variantId: 'variant-456',
})

The productId and variantId must exactly match the values used to create the session. The typed receipt is bound to the session, render, API key owner, and commerce context, and can be consumed only once.

Webhooks

Manage webhook endpoints (and verify inbound deliveries) so you can react to async job completion without polling.

// Create an endpoint -- the secret is returned in full on create; store it.
const endpoint = await client.webhooks.create({
  url: 'https://example.com/hooks/sudomock',
  eventTypes: ['render.succeeded', 'render.failed', 'video.succeeded'],
})

await client.webhooks.list()
await client.webhooks.update(endpoint.id, { enabled: false })
await client.webhooks.rotateSecret(endpoint.id) // returns the new secret
await client.webhooks.test(endpoint.id)         // send a test delivery
await client.webhooks.delete(endpoint.id)

// Per-endpoint delivery log (optional status / event_type / limit filters):
await client.webhooks.listDeliveries(endpoint.id, { status: 'failed', limit: 50 })
await client.webhooks.replayDelivery(endpoint.id, deliveryId) // replay one
await client.webhooks.replayFailed(endpoint.id)               // bulk replay all failed/dead

// Cross-endpoint Events feed (recent deliveries across every endpoint):
const events = await client.webhooks.listEvents({ status: 'failed', limit: 100 })

Photo-mockup events are photo_mockup.ready / photo_mockup.rejected / photo_mockup.failed and photo_mockup_render.succeeded / photo_mockup_render.failed. Each endpoint is pinned to one spelling (eventNaming). Pin a new endpoint yourself on create, or leave eventNaming out and the pin follows the spelling you subscribed in: a list in these names pins the endpoint to current, a list in the earlier 2d_mockup.* / 2d_render.* names pins it to legacy, and an empty or mixed list pins it to legacy. An endpoint created before these names existed keeps receiving 2d_mockup.* / 2d_render.* until you re-pin it. Subscribe with either spelling and the delivery carries the endpoint's own.

// A handler that still expects the legacy names:
await client.webhooks.create({
  url: 'https://example.com/hooks/sudomock',
  eventTypes: ['2d_render.succeeded'],
  eventNaming: 'legacy',
})
// Move an older endpoint to the current names once its handler is ready:
await client.webhooks.update(endpoint.id, { eventNaming: 'current' })

Verifying signatures

Every delivery carries TWO headers -- X-SudoMock-Signature (hex HMAC-SHA256 digest) and X-SudoMock-Timestamp (unix seconds). The signed payload is `${timestamp}.${rawBody}`. Verify it with the exact raw request body -- re-serialized JSON will not match:

import { verifyWebhookSignature } from 'sudomock'

// Express example -- capture the raw body (e.g. express.raw())
app.post('/hooks/sudomock', (req, res) => {
  const valid = verifyWebhookSignature(
    req.body.toString('utf8'),            // raw payload string
    req.header('X-SudoMock-Signature') ?? '',
    req.header('X-SudoMock-Timestamp') ?? '',
    process.env.SUDOMOCK_WEBHOOK_SECRET!,
    { toleranceSeconds: 300 },            // default; rejects replays
  )
  if (!valid) return res.status(400).end()
  // ...handle the event
  res.status(204).end()
})

The check is constant-time and rejects deliveries whose timestamp drifts more than the tolerance from now.

Error Handling

All errors extend SudoMockError and include status (HTTP code) and code (machine-readable string).

import SudoMock, {
  SudoMockError,
  AuthenticationError,
  CreditError,
  RateLimitError,
  NotFoundError,
  ValidationError,
  TimeoutError,
  JobFailedError,
  ConnectionError,
} from 'sudomock'

try {
  await client.renders.create({ ... })
} catch (err) {
  if (err instanceof CreditError) {
    console.log('Not enough credits, upgrade at https://sudomock.com/pricing')
  } else if (err instanceof RateLimitError) {
    console.log(`Rate limited, retry after ${err.retryAfter} seconds`)
  } else if (err instanceof AuthenticationError) {
    console.log('Invalid API key')
  } else if (err instanceof NotFoundError) {
    console.log('Mockup not found')
  } else if (err instanceof TimeoutError) {
    console.log('Request timed out')
  } else if (err instanceof SudoMockError) {
    console.log(`API error ${err.status} (${err.code}): ${err.message}`)
  }
}

Error Classes

| Error | HTTP Status | Description | |---|---|---| | AuthenticationError | 401 | Invalid or missing API key | | CreditError | 402 | Insufficient credits | | ValidationError | 400/422 | Invalid request parameters | | NotFoundError | 404 | Resource not found | | RateLimitError | 429 | Too many requests (check .retryAfter) | | InternalError | 500+ | Server error (auto-retried) | | TimeoutError | -- | Request timed out | | JobFailedError | N/A | Async job failed: .jobId identifies the job | | ConnectionError | -- | Network/DNS failure |

Retry Behavior

The SDK automatically retries on transient errors (HTTP 408, 429, 500, 502, 503, 504) with exponential backoff. Client errors (4xx except 408/429) are never retried.

// Configure retries
const client = new SudoMock('sm_xxx', {
  maxRetries: 3,  // default: 2
  timeout: 60_000, // default: 30s (renders use 120s automatically)
})

TypeScript

The SDK is written in TypeScript with full type definitions for all methods and responses.

import SudoMock, {
  type Mockup,
  type UpdateMockupParams,
  type Folder,
  type FolderDetail,
  type FolderListResult,
  type MoveToFolderParams,
  type MoveToFolderResult,
  type SmartObject,
  type TextLayer,
  type TextLayerInput,
  type RenderResult,
  type AccountResult,
  type CreateRenderParams,
  type AIRenderParams,
  type RemoveBackgroundParams,
  type RemoveBackgroundResult,
  type CheckSeamsParams,
  type FixSeamsParams,
  type SeamCheckResult,
  type Job,
  type JobErrorDetails,
  type JobStatus,
  type CreateVideoParams,
  type WebhookEndpoint,
  type WebhookDelivery,
} from 'sudomock'

Note: Webhook management methods (client.webhooks.*) authenticate with your API key, the same as every other resource.

MCP Server

SudoMock also offers an official Model Context Protocol (MCP) server, enabling AI assistants like Claude, Cursor, and VS Code Copilot to generate mockups directly.

Links

License

MIT