@narrative.io/data-collaboration-sdk-ts
v2.105.0
Published
[](https://www.npmjs.com/package/@narrative.io/data-collaboration-sdk-ts)
Readme
Narrative.io Data Collaboration SDK for TypeScript
The official TypeScript SDK for the Narrative.io Data Collaboration Platform. This SDK provides a simple and intuitive interface for interacting with Narrative's APIs, allowing you to manage datasets, subscriptions, data streams, and more.
Table of Contents
- Installation
- Quick Start
- API Overview
- Usage Examples
- Configuration
- TypeScript Support
- Error Handling
- API Reference
- Contributing
- License
Installation
Install the SDK using npm:
npm install @narrative.io/data-collaboration-sdk-tsOr using yarn:
yarn add @narrative.io/data-collaboration-sdk-tsOr using bun:
bun add @narrative.io/data-collaboration-sdk-tsQuick Start
import { NarrativeApi } from '@narrative.io/data-collaboration-sdk-ts';
// Initialize the SDK with your API key
const narrative = new NarrativeApi({
apiKey: 'your-api-key-here',
environment: 'prod' // 'prod' or 'dev'
});
// Make your first API call
async function getMyCompanyInfo() {
try {
const companyInfo = await narrative.getCompanyInfo();
console.log('Company:', companyInfo);
} catch (error) {
console.error('Error:', error);
}
}
getMyCompanyInfo();API Overview
The SDK provides access to the following Narrative.io API modules:
Core APIs
- Authentication - Manage API authentication
- Company Info - Retrieve company information
- Health Check - Check API health status
- Who Am I - Get current user information
Data Management
- Datasets - Create and manage datasets
- Data Streams - Configure real-time data streams
- Data Planes - Manage data plane configurations
- Subscriptions - Handle data subscriptions
- Uploads - Upload data files
Data Operations
- Queries - Execute data queries
- Forecast - Generate data forecasts
- NQL (Narrative Query Language) - Build and execute NQL queries
- Views - Create and manage data views
Marketplace & Collaboration
- Products - Browse and manage data products
- Contracts - Handle data contracts
- Connections - Manage data connections
- Installations - Track app installations
Advanced Features
- Attributes - Define data attributes
- Mappings - Configure data mappings
- Models - Work with ML models
- Model Training - Train custom models
- Rosetta Stone - Data transformation tools
- Access Rules - Set data access permissions
- Access Tokens - Manage API tokens
- Encryption Materials - Handle encryption keys
Usage Examples
Working with Datasets
// List all datasets
const datasets = await narrative.getDatasets();
console.log(`Found ${datasets.length} datasets`);
// Get a specific dataset
const datasetId = 'your-dataset-id';
const dataset = await narrative.getDataset(datasetId);
console.log('Dataset name:', dataset.name);
// Create a new dataset
const newDataset = await narrative.createDataset({
name: 'My New Dataset',
description: 'A dataset created via SDK',
schema: {
// Your schema definition
}
});Managing Subscriptions
// List active subscriptions
const subscriptions = await narrative.getSubscriptions();
subscriptions.forEach(sub => {
console.log(`Subscription: ${sub.name} - Status: ${sub.status}`);
});
// Create a subscription
const subscription = await narrative.createSubscription({
name: 'Daily Data Feed',
datasetId: 'dataset-id',
frequency: 'daily'
});Executing NQL Queries
// Build and execute an NQL query
const nqlQuery = `
SELECT *
FROM narrative.datasets
WHERE created_date >= '2024-01-01'
LIMIT 100
`;
const results = await narrative.executeNql(nqlQuery);
console.log('Query returned', results.rows.length, 'rows');Uploading Data
// Upload a file to a dataset
const upload = await narrative.createUpload({
datasetId: 'your-dataset-id',
fileName: 'data.csv',
fileSize: 1024000 // Size in bytes
});
// Get the upload URL and upload your file
console.log('Upload URL:', upload.uploadUrl);
// Use the uploadUrl to PUT your file dataConfiguration
Environment Configuration
The SDK supports multiple environments:
// Production environment (default)
const narrativeProd = new NarrativeApi({
apiKey: 'your-api-key'
});
// Development environment
const narrativeDev = new NarrativeApi({
apiKey: 'your-api-key',
environment: 'dev'
});Custom Headers
Add custom headers to all requests:
const narrative = new NarrativeApi({
apiKey: 'your-api-key',
headers: {
'X-Custom-Header': 'custom-value'
}
});API Key Management
Store your API key securely using environment variables:
// .env file
NARRATIVE_API_KEY=your-api-key-here
// Your code
import { NarrativeApi } from '@narrative.io/data-collaboration-sdk-ts';
const narrative = new NarrativeApi({
apiKey: process.env.NARRATIVE_API_KEY!
});TypeScript Support
The SDK is written in TypeScript and provides comprehensive type definitions:
import {
NarrativeApi,
Dataset,
Subscription,
DataStream,
NqlQuery
} from '@narrative.io/data-collaboration-sdk-ts';
// Type-safe API calls
const narrative = new NarrativeApi({
apiKey: 'your-api-key'
});
// TypeScript will provide intellisense and type checking
const dataset: Dataset = await narrative.getDataset('dataset-id');
const subscriptions: Subscription[] = await narrative.getSubscriptions();Working with Types
import type {
Config,
PaginationOptions,
Dataset,
CreateDatasetRequest
} from '@narrative.io/data-collaboration-sdk-ts';
// Use types for better code organization
const config: Config = {
apiKey: process.env.NARRATIVE_API_KEY!,
environment: 'prod'
};
const paginationOptions: PaginationOptions = {
limit: 100,
offset: 0
};Error Handling
The SDK provides detailed error information:
import { NarrativeApi } from '@narrative.io/data-collaboration-sdk-ts';
const narrative = new NarrativeApi({
apiKey: 'your-api-key'
});
try {
const dataset = await narrative.getDataset('non-existent-id');
} catch (error) {
if (error.response) {
// API returned an error response
console.error('API Error:', error.response.status);
console.error('Error Message:', error.response.data.message);
} else if (error.request) {
// Request was made but no response received
console.error('Network Error:', error.message);
} else {
// Something else happened
console.error('Error:', error.message);
}
}Common Error Patterns
// Handle specific error codes
try {
const result = await narrative.someApiCall();
} catch (error) {
if (error.response?.status === 401) {
console.error('Authentication failed. Check your API key.');
} else if (error.response?.status === 404) {
console.error('Resource not found.');
} else if (error.response?.status === 429) {
console.error('Rate limit exceeded. Please retry later.');
} else {
console.error('Unexpected error:', error);
}
}API Reference
For detailed API documentation, please visit the Narrative.io API Documentation.
Local Development: Use This SDK Locally in a Consumer App (No Publish Needed)
You can link this SDK into another repo (e.g., a Nuxt 3 app) and iterate without publishing to npm each time. Two supported flows:
- Linked mode (fastest) — symlink your local SDK into the app
- Tarball mode (exact publish parity) — install from a local
npm packtarball
Both approaches use the SDK’s built output in build/, exactly like the published package.
Prerequisites
- Bun (this project uses bun as its package manager)
- This repo builds TypeScript to
build/ - This repo includes
scripts/ensureBuild.jsto verify artifacts exist
# In the SDK repo (this one)
bun install
bun run build # one-time; emits build/**
node scripts/ensureBuild.jsOption A — Linked Mode (Fastest Dev Feedback)
Keep the SDK building on save In the SDK repo (leave this running):
bun run dev # tsc -w → continuously updates build/**Register the SDK globally In the SDK repo (new terminal):
bun run link:global # runs ensureBuild + bun linkLink into your consumer app In your app repo (e.g., Nuxt project):
# link the globally-registered SDK into this app's node_modules bun link @narrative.io/data-collaboration-sdk-tsVerify the app resolves to your local SDK
node -e "console.log(require.resolve('@narrative.io/data-collaboration-sdk-ts/package.json'))"You should see a path inside your SDK repo (not a versioned folder under the app's
node_modules).Run your app
bun run devEdit files under
SDK/src/**→ the watcher writes tobuild/**→ your app hot-reloads.
Revert to the registry version (in the app):
bun remove @narrative.io/data-collaboration-sdk-ts
bun add @narrative.io/data-collaboration-sdk-tsOption B — Tarball Mode (Exact Publish Parity)
Pack the SDK (same artifact you would publish)
# in the SDK repo bun run build bun run pack:dist # creates ./<name>-<version>.tgzInstall the tarball in the app
# in the app repo bun add /ABS/PATH/TO/<name>-<version>.tgz bun run dev
Revert to a registry version (in the app):
bun add @narrative.io/data-collaboration-sdk-ts@<semver>Troubleshooting (Nuxt 3 / Vite / SSR)
“Cannot use import statement outside a module” (SSR): Inline the SDK so Nitro bundles it.
// nuxt.config.ts export default defineNuxtConfig({ nitro: { externals: { inline: ['@narrative.io/data-collaboration-sdk-ts'] } } })Build artifacts not updating: Ensure
npm run devis running in the SDK repo (TypeScript watch), and that the app is linked (or reinstalled from a fresh tarball).Accidental imports from
src/*: Consumers should import from the package root only. This SDK publishesbuild/**and definesmain/types(and may include anexportsmap) to preventsrc/*imports.Type/version drift (e.g., Zod): If your app and the SDK use different major versions of a library whose types appear in public APIs, align versions or declare that library as a
peerDependencyin the SDK.
Quick Reference
# SDK (this repo)
bun install
bun run build
bun run dev
bun run link:global
# App (consumer repo)
bun link @narrative.io/data-collaboration-sdk-ts
bun run devAlternative (publish-parity):
# SDK
bun run build
bun run pack:dist
# App
bun add /ABS/PATH/TO/*.tgz
bun run dev