promptcanvas-sdk
v1.1.0
Published
High-performance SDK for fetching prompts from PromptCanvas with CLI support
Maintainers
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/sdkQuick 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 initThis 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 listUse 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:
- Open PromptCanvas UI
- Navigate to your prompt
- Promote a version to Production stage
Performance Tips
- Prefetch critical prompts on app initialization
- Use batch fetching (
getMany) instead of multiplegetcalls - Enable stale-while-revalidate for the best user experience
- Monitor cache stats to tune TTL values
- Use abort signals for user-initiated cancellations
TypeScript
Full type definitions are included:
import type {
Prompt,
PromptCanvasConfig,
CacheStats,
SlugSuggestion,
} from '@promptcanvas/sdk';License
MIT
