vibe-cms-sdk
v0.2.1
Published
Framework-agnostic TypeScript SDK for Vibe CMS - AI-powered content management system
Maintainers
Readme
Vibe CMS TypeScript SDK
Framework-agnostic TypeScript SDK for Vibe CMS - AI-powered content management system with instant rollback, one-click translation, and automated SEO optimization.
Features
- 🔗 Chainable API: Intuitive, fluent interface for content queries
- 🎯 Framework Agnostic: Works with Vue, React, Angular, and vanilla TypeScript
- ⚡ Intelligent Caching: Browser localStorage/sessionStorage with TTL
- 📦 Zero Dependencies: Native Fetch API only
- 🔒 Type Safe: Full TypeScript support with IntelliSense
- 📱 Dual Module Support: Both CommonJS and ESM builds
Installation
Install from public NPM registry:
npm install vibe-cms-sdkQuick Start
import { createVibeCMS } from 'vibe-cms-sdk'
// Initialize the CMS client
const cms = createVibeCMS({
projectId: 'your-project-id',
baseUrl: 'https://api.vibe-cms.com', // optional, defaults to this
locale: 'en-US', // optional, defaults to 'en-US'
cache: {
enabled: true, // optional, defaults to true
ttl: 300000, // optional, 5 minutes default
storage: 'localStorage' // optional, 'localStorage' | 'sessionStorage'
}
})
// Use the chainable API with enhanced field extraction
const firstPost = await cms.collection('blog_posts').first()
const title = firstPost.field('title') // Extract field directly
const imageUrl = firstPost.asset_url('featured_image') // Generate asset URL
const allPosts = await cms.collection('blog_posts').many({ limit: 10 })
const titles = allPosts.field('title') // ['Title 1', 'Title 2', ...]
const imageUrls = allPosts.asset_url('featured_image') // Bulk asset URLsAPI Reference
createVibeCMS(config)
Creates a new CMS client instance.
Parameters:
config.projectId(string, required): Your Vibe CMS project IDconfig.baseUrl(string, optional): API base URL, defaults tohttps://api.vibe-cms.comconfig.locale(string, optional): Default locale for content requests, defaults to'en-US'config.cache(object, optional): Caching configuration
Cache Configuration:
enabled(boolean): Enable/disable caching, defaults totruettl(number): Time to live in milliseconds, defaults to300000(5 minutes)storage(string): Storage type,'localStorage'or'sessionStorage', defaults to'localStorage'
Collection Methods
.collection(slug)
Creates a collection query for the specified collection slug.
const posts = cms.collection('blog_posts').first()
Returns the first item from the collection, or null if empty.
const firstPost = await cms.collection('blog_posts').first().many(options?)
Returns an array of items with optional limit.
const recentPosts = await cms.collection('blog_posts').many({ limit: 10 })
const defaultMany = await cms.collection('blog_posts').many() // defaults to 50.all()
Returns all items from the collection.
const allPosts = await cms.collection('blog_posts').all().item(itemId)
Returns a specific item by ID, or null if not found.
const post = await cms.collection('blog_posts').item('item-123')Localization Methods
.setLocale(locale)
Sets the current locale for content requests. This affects all subsequent content queries and uses separate cache per locale.
cms.setLocale('fr-FR') // Set to French (France)
cms.setLocale('es') // Set to Spanish.getLocale()
Gets the current locale.
const currentLocale = cms.getLocale() // Returns current locale, e.g., 'en-US'.clearLocaleCache(locale?)
Clears cached data for a specific locale, or current locale if not specified.
await cms.clearLocaleCache('fr-FR') // Clear French cache
await cms.clearLocaleCache() // Clear current locale cacheCaching Methods
.clearCache()
Clears cached data for the collection.
await cms.collection('blog_posts').clearCache()🎯 Enhanced Field Extraction & Asset Handling
The SDK now includes powerful field extraction and asset handling capabilities that make working with content much more efficient.
Field Extraction
Extract field values directly without accessing .data every time:
// Single items
const post = await cms.collection('blog_posts').first()
const title = post.field('title') // Instead of post.raw.data.title
const author = post.field('author') // Clean and simple
const tags = post.field('tags') // Works with any data type
// Multiple items - get arrays of values
const posts = await cms.collection('blog_posts').many({ limit: 10 })
const allTitles = posts.field('title') // ['Post 1', 'Post 2', ...]
const allAuthors = posts.field('author') // ['John', 'Jane', ...]
const allTags = posts.field('tags') // [['tech'], ['design', 'ui'], ...]Asset Handling
Generate asset URLs and download assets directly from field values:
// Single asset URLs
const post = await cms.collection('blog_posts').first()
const imageUrl = post.asset_url('featured_image')
const thumbnailUrl = post.asset_url('featured_image', { width: 300, height: 200 })
// Multiple asset URLs
const posts = await cms.collection('blog_posts').many()
const allImageUrls = posts.asset_url('featured_image') // Bulk generation!
// Asset arrays (galleries)
const galleryUrls = post.asset_url('gallery') // ['url1', 'url2', ...]
// Download assets
const imageData = await post.download_asset('featured_image')
console.log(imageData.contentType, imageData.contentLength)Collection Result Methods
Enhanced results provide utility methods for easier data manipulation:
const posts = await cms.collection('blog_posts').many()
// Utility properties
console.log(posts.count) // Number of items
console.log(posts.isEmpty) // Boolean
console.log(posts.isArray) // true for .many()/.all()
console.log(posts.isSingle) // true for .first()/.item()
// Array-like operations
posts.map(post => post.data.title)
posts.filter(post => post.data.featured)
posts.find(post => post.data.slug === 'target')
// Iteration
for (const post of posts) {
console.log(post.data.title)
}
// First/last access
const firstPost = posts.first()
const lastPost = posts.last()Backward Compatibility
Existing code continues to work unchanged via the .raw property:
const result = await cms.collection('blog_posts').first()
// Old way (still works)
const oldTitle = result.raw?.data.title
// New way (recommended)
const newTitle = result.field('title')🌍 Internationalization & Localization
The SDK provides comprehensive locale support for internationalized content with automatic cache separation and asset URL localization.
Basic Locale Management
const cms = createVibeCMS({
projectId: 'your-project-id',
locale: 'en-US' // Set default locale
})
// Switch locales dynamically
cms.setLocale('fr-FR')
const frenchPosts = await cms.collection('blog_posts').many()
cms.setLocale('es-ES')
const spanishPosts = await cms.collection('blog_posts').many()
// Check current locale
console.log(cms.getLocale()) // 'es-ES'Locale-Aware Asset URLs
Asset URLs automatically include the current locale parameter:
cms.setLocale('fr-FR')
const post = await cms.collection('blog_posts').first()
const imageUrl = post.asset_url('featured_image')
// URL will include: ...&locale=fr-FR
// Bulk asset URLs maintain locale consistency
const posts = await cms.collection('blog_posts').many()
const allImageUrls = posts.asset_url('featured_image')
// All URLs include the French locale parameterAutomatic Cache Separation
Each locale maintains its own cache to ensure content consistency:
// English content cached separately
cms.setLocale('en-US')
const englishPosts = await cms.collection('blog_posts').many()
// French content gets its own cache
cms.setLocale('fr-FR')
const frenchPosts = await cms.collection('blog_posts').many()
// Clear cache for specific locale
await cms.clearLocaleCache('fr-FR') // Only clears French cache
await cms.clearLocaleCache() // Clears current locale (French)Practical Multi-Language Example
class BlogManager {
private cms = createVibeCMS({ projectId: 'blog-project' })
async getPostsByLocale(locale: string) {
this.cms.setLocale(locale)
const posts = await this.cms.collection('blog_posts').many()
return posts.map(post => ({
title: post.field('title'),
content: post.field('content'),
imageUrl: post.asset_url('featured_image'),
locale: this.cms.getLocale()
}))
}
async getAllLocalizedPosts() {
const locales = ['en-US', 'fr-FR', 'es-ES', 'de-DE']
const results = {}
for (const locale of locales) {
results[locale] = await this.getPostsByLocale(locale)
}
return results
}
}
// Usage
const blog = new BlogManager()
const allPosts = await blog.getAllLocalizedPosts()
// Returns: { 'en-US': [...], 'fr-FR': [...], 'es-ES': [...], 'de-DE': [...] }Supported Locale Formats
The SDK validates locales using BCP 47 standards:
// Valid formats
cms.setLocale('en') // Language only
cms.setLocale('en-US') // Language-Country
cms.setLocale('fr-FR') // Language-Country
cms.setLocale('zh-CN') // Language-Country
cms.setLocale('es-419') // Language-Region
// Invalid formats (will throw errors)
cms.setLocale('EN-US') // Uppercase not allowed
cms.setLocale('invalid-locale-format-too-long') // Too long
cms.setLocale('') // Empty stringTypeScript Support
The SDK is built with TypeScript and provides full type safety:
// Generic type support
interface BlogPost {
title: string
content: string
published_at: string
}
const post = await cms.collection<BlogPost>('blog_posts').first()
// post is typed as BlogPost | nullFramework Examples
Vue 3
<template>
<div>
<article v-for="post in posts" :key="post.id">
<h2>{{ post.data.title }}</h2>
<p>{{ post.data.excerpt }}</p>
</article>
</div>
</template>
<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { createVibeCMS } from 'vibe-cms-sdk'
const posts = ref([])
const cms = createVibeCMS({
projectId: 'your-project-id'
})
onMounted(async () => {
posts.value = await cms.collection('blog_posts').many({ limit: 10 })
})
</script>React
import { useState, useEffect } from 'react'
import { createVibeCMS } from 'vibe-cms-sdk'
const cms = createVibeCMS({
projectId: 'your-project-id'
})
function BlogPosts() {
const [posts, setPosts] = useState([])
useEffect(() => {
cms.collection('blog_posts').many({ limit: 10 })
.then(setPosts)
}, [])
return (
<div>
{posts.map(post => (
<article key={post.id}>
<h2>{post.data.title}</h2>
<p>{post.data.excerpt}</p>
</article>
))}
</div>
)
}Angular
import { Component, OnInit } from '@angular/core'
import { createVibeCMS } from 'vibe-cms-sdk'
@Component({
selector: 'app-blog',
template: `
<article *ngFor="let post of posts">
<h2>{{ post.data.title }}</h2>
<p>{{ post.data.excerpt }}</p>
</article>
`
})
export class BlogComponent implements OnInit {
posts: any[] = []
private cms = createVibeCMS({
projectId: 'your-project-id'
})
async ngOnInit() {
this.posts = await this.cms.collection('blog_posts').many({ limit: 10 })
}
}Error Handling
The SDK provides comprehensive error handling:
import { VibeCMSError } from 'vibe-cms-sdk'
try {
const posts = await cms.collection('blog_posts').all()
} catch (error) {
if (error instanceof VibeCMSError) {
console.log('API Error:', error.message)
console.log('Status:', error.status)
console.log('Details:', error.details)
} else {
console.log('Network Error:', error.message)
}
}Caching Behavior
The SDK intelligently caches responses to reduce API calls:
- Cache Keys: Unique per project, collection, and query parameters
- TTL: Configurable time-to-live, defaults to 5 minutes
- Storage: Uses localStorage with sessionStorage and memory fallbacks
- Invalidation: Automatic expiration and manual clearing
Migration from GitHub Packages
If you were using the private GitHub Packages version:
# Remove old package
npm uninstall vibe-cms-sdk
# Install from public NPM
npm install vibe-cms-sdk
# No code changes needed - imports remain the same!Development
# Install dependencies
npm install
# Build the package
npm run build
# Run tests
npm test
# Type check
npm run type-check
# Watch mode for development
npm run devContributing
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature) - Commit your changes (
git commit -m 'Add some amazing feature') - Push to the branch (
git push origin feature/amazing-feature) - Open a Pull Request
License
This project is licensed under the MIT License - see the LICENSE file for details.
Support
Made with ❤️ for the Vibe CMS community
