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

promptcanvas-sdk

v1.1.0

Published

High-performance SDK for fetching prompts from PromptCanvas with CLI support

Readme

@promptcanvas/sdk

High-performance SDK for fetching prompts from PromptCanvas with built-in caching, prefetching, and variable resolution.

Features

  • Ultra-fast caching - LRU cache with TTL and stale-while-revalidate
  • Prefetching - Warm up cache on initialization
  • Variable resolution - Template interpolation with {{ variable }} syntax
  • Autocomplete - Slug suggestions for IDE integration
  • Batch fetching - Single network request for multiple prompts
  • Type-safe - Full TypeScript support
  • Production-only - Only fetches production-stage prompts for safety
  • CLI Support - Pull prompts to local files with npx promptcanvas pull
  • Local Mode - Load prompts from local files for offline/fast access

Installation

npm install @promptcanvas/sdk
# or
yarn add @promptcanvas/sdk
# or
pnpm add @promptcanvas/sdk

Quick Start

import { PromptCanvas } from '@promptcanvas/sdk';

// Initialize the client
const pc = new PromptCanvas({
  apiKey: process.env.PROMPTCANVAS_API_KEY!,
  prefetch: ['system-prompt', 'welcome-message'], // Optional: warm cache
});

// Fetch a prompt
const prompt = await pc.get('system-prompt');
console.log(prompt.content);

// Fetch with variables
const message = await pc.get('welcome-message', {
  variables: { userName: 'John', companyName: 'Acme' }
});
// Template: "Hello {{ userName }}, welcome to {{ companyName }}!"
// Result: "Hello John, welcome to Acme!"

CLI - Pull Prompts Locally

Pull production prompts from PromptCanvas and store them as local files. Perfect for:

  • Offline development - No network dependency
  • Version control - Track prompt changes in git
  • Fast access - Zero latency, no API calls
  • CI/CD - Include prompts in your build process

Setup

# Initialize config file
npx promptcanvas init

This creates a promptcanvas.json file:

{
  "apiKey": "${PROMPTCANVAS_API_KEY}",
  "outputDir": "prompts",
  "format": "json",
  "includeMetadata": true
}

Pull Prompts

# Pull a specific prompt
npx promptcanvas pull system-prompt

# Pull all production prompts
npx promptcanvas pull --all

# List available prompts
npx promptcanvas list

Use Local Prompts

import { LocalPrompts } from '@promptcanvas/sdk';

// Load prompts from local files
const prompts = new LocalPrompts({ dir: './prompts' });

// Get a prompt
const systemPrompt = prompts.get('system-prompt');
console.log(systemPrompt.content);

// With variables
const welcome = prompts.get('welcome-message', { userName: 'John' });

Or use the simple getter:

import { createLocalGetter } from '@promptcanvas/sdk';

const getPrompt = createLocalGetter('./prompts');

// Returns just the content string
const content = getPrompt('system-prompt');
const withVars = getPrompt('welcome', { name: 'John' });

Configuration

const pc = new PromptCanvas({
  // Required
  apiKey: 'pc_live_xxxxx',

  // Optional
  baseUrl: 'https://your-instance.supabase.co/functions/v1/sdk',
  timeout: 10000, // Request timeout in ms
  debug: false,   // Enable debug logging

  // Cache configuration
  cache: {
    maxEntries: 1000,           // Max cached prompts
    ttlMs: 300000,              // 5 minutes
    staleWhileRevalidate: true, // Return stale, refresh in background
  },

  // Retry configuration
  retry: {
    maxRetries: 3,
    baseDelayMs: 100,
    maxDelayMs: 5000,
  },

  // Prefetch on init
  prefetch: ['critical-prompt-1', 'critical-prompt-2'],
});

API Reference

pc.get(slug, options?)

Fetch a single prompt by slug.

const prompt = await pc.get('my-prompt');

// With options
const prompt = await pc.get('my-prompt', {
  variables: { name: 'World' },  // Interpolate variables
  skipCache: false,              // Force fresh fetch
  signal: abortController.signal // Cancellation
});

pc.getMany(slugs, options?)

Batch fetch multiple prompts in a single request.

const { prompts, errors } = await pc.getMany([
  'prompt-1',
  'prompt-2',
  'prompt-3'
]);

// Handle partial failures
for (const error of errors) {
  console.warn(`Failed to fetch ${error.slug}: ${error.error}`);
}

pc.suggest(query, options?)

Get autocomplete suggestions for slug input. Perfect for IDE/editor integration.

const suggestions = await pc.suggest('sys');
// [
//   { slug: 'system-prompt', name: 'System Prompt', hasProduction: true },
//   { slug: 'system-error', name: 'System Error', hasProduction: true },
// ]

// With limit
const suggestions = await pc.suggest('user', { limit: 5 });

pc.list(options?)

List all available prompts with pagination.

const { prompts, total } = await pc.list();

// With filters
const { prompts } = await pc.list({
  category: 'system',
  limit: 50,
  offset: 0,
});

pc.warmup(slugs)

Pre-populate the cache with specific prompts.

await pc.warmup(['critical-prompt-1', 'critical-prompt-2']);

pc.invalidate(slug)

Remove a specific prompt from cache.

await pc.invalidate('outdated-prompt');

pc.clearCache()

Clear all cached prompts.

await pc.clearCache();

pc.getCacheStats()

Get cache performance statistics.

const stats = pc.getCacheStats();
// { hits: 1000, misses: 50, hitRate: 0.952, size: 150, maxSize: 1000 }

pc.on(listener)

Subscribe to SDK events.

const unsubscribe = pc.on((event) => {
  switch (event.type) {
    case 'cache:hit':
      console.log(`Cache hit: ${event.slug}`);
      break;
    case 'cache:miss':
      console.log(`Cache miss: ${event.slug}`);
      break;
    case 'fetch:success':
      console.log(`Fetched ${event.slug} in ${event.latencyMs}ms`);
      break;
    case 'ratelimit:warning':
      console.warn(`Rate limit warning: ${event.remaining} remaining`);
      break;
  }
});

// Cleanup
unsubscribe();

Variable Resolution

Templates use {{ variable }} syntax:

// Template in PromptCanvas:
// "Hello {{ userName }}, welcome to {{ productName }}!"

const prompt = await pc.get('welcome', {
  variables: {
    userName: 'John',
    productName: 'Acme'
  }
});

console.log(prompt.content);
// "Hello John, welcome to Acme!"

Extract Variables

const template = "Hello {{ name }}, your order {{ orderId }} is ready.";
const variables = pc.extractVariables(template);
// ['name', 'orderId']

Error Handling

import {
  PromptNotFoundError,
  NoProductionVersionError,
  AuthenticationError,
  RateLimitError,
} from '@promptcanvas/sdk';

try {
  const prompt = await pc.get('my-prompt');
} catch (error) {
  if (error instanceof PromptNotFoundError) {
    console.error(`Prompt not found: ${error.slug}`);
  } else if (error instanceof NoProductionVersionError) {
    console.error(`No production version for: ${error.slug}`);
    // Prompt exists but hasn't been promoted to production
  } else if (error instanceof RateLimitError) {
    console.error(`Rate limited. Retry after ${error.retryAfterMs}ms`);
  } else if (error instanceof AuthenticationError) {
    console.error('Invalid API key');
  }
}

Production-Only Access

Important: The SDK only returns prompts that have been promoted to the production stage. This is by design for safety.

If you try to fetch a prompt that exists but isn't in production, you'll receive a NoProductionVersionError with a helpful message:

Prompt 'my-prompt' has no production version. Only production prompts are available via SDK.

To make a prompt available:

  1. Open PromptCanvas UI
  2. Navigate to your prompt
  3. Promote a version to Production stage

Performance Tips

  1. Prefetch critical prompts on app initialization
  2. Use batch fetching (getMany) instead of multiple get calls
  3. Enable stale-while-revalidate for the best user experience
  4. Monitor cache stats to tune TTL values
  5. Use abort signals for user-initiated cancellations

TypeScript

Full type definitions are included:

import type {
  Prompt,
  PromptCanvasConfig,
  CacheStats,
  SlugSuggestion,
} from '@promptcanvas/sdk';

License

MIT