Movatterモバイル変換


[0]ホーム

URL:


@cosmicjs/sdk
TypeScript icon, indicating that this package has built-in type declarations

1.5.1 • Public • Published
Cosmic dashboard darkmode

Cosmic JavaScript SDK

Cosmic is aheadless CMS (content management system) that provides a web dashboard to create content and an API toolkit to deliver content to any website or application. Nearly any type of content can be built using the dashboard and delivered using this SDK.

Get started free →

Install

Install the Cosmic JavaScript SDK. We recommend using thebun package manager.

bun add @cosmicjs/sdk# ORyarn add @cosmicjs/sdk# ORnpm install @cosmicjs/sdk

Import

Import Cosmic into your app using thecreateBucketClient method.

import{createBucketClient}from'@cosmicjs/sdk';

Authentication

In theCosmic admin dashboard go toBucket > Settings > API Access and get your Bucket slug and read key then set the variables in your app to connect to your Bucket.

constcosmic=createBucketClient({bucketSlug:'BUCKET_SLUG',readKey:'BUCKET_READ_KEY',});

Get Objects

Objects are the basic building blocks of content in Cosmic.

Get multiple Objects [see docs]

Use theobjects.find() method to fetch Objects.

constposts=awaitcosmic.objects.find({type:'posts',}).props(['title','slug','metadata']).limit(10);

The above example fetches Objects in theposts Object type returning thetitle,slug, andmetadata properties, limiting the response to10 Objects.

Get single Object by slug [see docs]

Use theobjects.findOne() method withtype andslug to fetch a single Object.

constpost=awaitcosmic.objects.findOne({type:'pages',slug:'home',}).props(['title','slug','metadata']);

Create, update, and delete Objects

To write to the Cosmic API, you will need to set the Bucket write key found inBucket > Settings > API Access. (NOTE: never expose your write key in any client-side code)

constcosmic=createBucketClient({bucketSlug:'BUCKET_SLUG',readKey:'BUCKET_READ_KEY',writeKey:'BUCKET_WRITE_KEY',});

Create Object [see docs]

Use theobjects.insertOne() method to create an Object.

awaitcosmic.objects.insertOne({title:'Blog Post Title',type:'posts',metadata:{content:'Here is the blog post content... still learning',seo_description:'This is the blog post SEO description.',featured_post:true,tags:['javascript','cms'],},});

Update Object [see docs]

Use theobjects.updateOne() method to update an Object by specifying the Objectid and include properties that you want to update.

awaitcosmic.objects.updateOne('5ff75368c2dfa81a91695cec',{metadata:{content:'This is the updated blog post content... I got it now!',featured_post:false,},});

Delete Object [see docs]

Use theobjects.deleteOne() method to delete an Object by specifying the Objectid.

awaitcosmic.objects.deleteOne('5ff75368c2dfa81a91695cec');

AI Capabilities

Cosmic provides AI-powered text and image generation capabilities through the SDK.

Generate Text [see docs]

Use theai.generateText() method to generate text content using AI models. You must provide either aprompt ormessages parameter.

Using a simple prompt:

consttextResponse=awaitcosmic.ai.generateText({prompt:'Write a product description for a coffee mug',max_tokens:500,// optional});console.log(textResponse.text);console.log(textResponse.usage);// { input_tokens: 10, output_tokens: 150 }

Using messages for chat-based models:

constchatResponse=awaitcosmic.ai.generateText({messages:[{role:'user',content:'Tell me about coffee mugs'},{role:'assistant',content:'Coffee mugs are vessels designed to hold hot beverages...',},{role:'user',content:'What materials are they typically made from?'},],max_tokens:500,// optional});console.log(chatResponse.text);console.log(chatResponse.usage);

Using streaming for real-time responses:

import{TextStreamingResponse}from'@cosmicjs/sdk';// Enable streaming with the stream: true parameterconstresult=awaitcosmic.ai.generateText({prompt:'Tell me about coffee mugs',// or use messages array formatmax_tokens:500,stream:true// Enable streaming});// Cast the result to TextStreamingResponseconststream=resultasTextStreamingResponse;// Option 1: Event-based approachletfullResponse='';stream.on('text',(text)=>{fullResponse+=text;process.stdout.write(text);// Display text as it arrives});stream.on('usage',(usage)=>console.log('Usage:',usage));stream.on('end',(data)=>console.log('Complete:',fullResponse));stream.on('error',(error)=>console.error('Error:',error));// Option 2: For-await loop approachasyncfunctionprocessStream(){letfullResponse='';try{forawait(constchunkofstream){if(chunk.text){fullResponse+=chunk.text;process.stdout.write(chunk.text);}}console.log('\nComplete text:',fullResponse);}catch(error){console.error('Error:',error);}}

Using the simplified stream method

// Simplified streaming methodconststream=awaitcosmic.ai.stream({prompt:'Tell me about coffee mugs',max_tokens:500,});// Process stream using events or for-await loop as shown above

TheTextStreamingResponse supports two usage patterns:

  1. Event-based: Extends EventEmitter with these events:

    • text: New text fragments
    • usage: Token usage information
    • end: Final data when stream completes
    • error: Stream errors
  2. AsyncIterator: For for-await loops, with chunk objects containing:

    • text: Text fragments
    • usage: Token usage information
    • end: Set to true for the final chunk
    • error: Error information

Analyze Images and Files

The AI model can analyze images and files when generating text responses. This feature works with both theprompt andmessages approaches.

consttextWithImageResponse=awaitcosmic.ai.generateText({prompt:'Describe this coffee mug and suggest improvements to its design',media_url:'https://imgix.cosmicjs.com/your-image-url.jpg',max_tokens:500,});console.log(textWithImageResponse.text);console.log(textWithImageResponse.usage);

Generate Image [see docs]

Use theai.generateImage() method to create AI-generated images based on text prompts.

constimageResponse=awaitcosmic.ai.generateImage({prompt:'A serene mountain landscape at sunset',// Optional parametersmetadata:{tags:['landscape','mountains','sunset']},folder:'ai-generated-images',alt_text:'A beautiful mountain landscape with a colorful sunset',});// Access the generated image propertiesconsole.log(imageResponse.media.url);// Direct URL to the generated imageconsole.log(imageResponse.media.imgix_url);// Imgix-enhanced URL for additional transformationsconsole.log(imageResponse.media.width);// Image widthconsole.log(imageResponse.media.height);// Image heightconsole.log(imageResponse.media.alt_text);// Alt text for the imageconsole.log(imageResponse.revised_prompt);// Potentially revised prompt used by the AI

Learn more

Go to theCosmic docs to learn more capabilities.

Community support

For additional help, you can use one of these channels to ask a question:

Cosmic support

  • Contact us for help with any service questions and custom plan inquiries.

Contributing

This project useschangeset to manage releases. Follow the following steps to add a changeset:

  • Runnpm run changeset command and select type of release with description of changes.
  • When PR with changeset is merged intomain branch, Github will create a new PR with correct version change and changelog edits.
  • Whencodeowner merges the generated PR, it will publish the package and create a Github release.

License

This project is published under theMIT license.

Package Sidebar

Install

npm i @cosmicjs/sdk

Weekly Downloads

1,800

Version

1.5.1

License

MIT

Unpacked Size

47 kB

Total Files

7

Last publish

Collaborators

  • tonyspiro
  • rajatkaush1k
  • jazibsawar

[8]ページ先頭

©2009-2025 Movatter.jp