JavaScript SDK

npm version npm bundle size JSR JSR Score TypeScript Node.js License: MIT

Per-endpoint request and response samples are in the API reference.

Installation

Install the package using npm:

npm install neuwo-api

Requirements

Browser Compatibility:

Quick Start

Usage in Different Environments

Node.js (CommonJS):

const { NeuwoRestClient, NeuwoEdgeClient } = require("neuwo-api");

Node.js (ESM):

import { NeuwoRestClient, NeuwoEdgeClient } from "neuwo-api";

Browser (ESM):

<script type="module">
  import {
    NeuwoRestClient,
    NeuwoEdgeClient,
  } from "https://cdn.jsdelivr.net/npm/neuwo-api/+esm";
</script>

REST API Client

import { NeuwoRestClient } from "neuwo-api";

// Initialize client
const client = new NeuwoRestClient({
  token: "your-rest-api-token",
  baseUrl: "https://custom.api.com",
});

// Analyze text content
const response = await client.getAiTopics({
  content: "Cats make wonderful pets for modern households.",
  documentId: "article-123",
  headline: "Why Cats Make Great Pets",
});

// Access results
console.log(`Tags: ${response.tags.length}`);
response.tags.forEach((tag) => {
  console.log(`  - ${tag.value} (score: ${tag.score})`);
});

console.log(`Brand Safe: ${response.brandSafety.isSafe}`);
console.log(`IAB Categories: ${response.marketingCategories.iabTier1.length}`);

EDGE API Client

import { NeuwoEdgeClient } from "neuwo-api";

// Initialize client
const client = new NeuwoEdgeClient({
  token: "your-edge-api-token",
  baseUrl: "https://custom.api.com",
  defaultOrigin: "https://yourwebsite.com", // Optional: default origin for requests
});

// Analyze article by URL
const response = await client.getAiTopics({
  url: "https://example.com/article",
});

// Or wait for analysis to complete (with automatic retry)
const responseWithWait = await client.getAiTopicsWait({
  url: "https://example.com/article",
  maxRetries: 10,
  retryInterval: 6,
});

console.log(`Found ${responseWithWait.tags.length} tags for the article`);

Configuration

REST Client Parameters

Parameter Type Default Description
token string Required REST API authentication token
baseUrl string Required Base URL for the API
timeout number 60 Request timeout in seconds

Example:

const client = new NeuwoRestClient({
  token: "your-token",
  baseUrl: "https://custom.api.com",
  timeout: 120,
});

EDGE Client Parameters

Parameter Type Default Description
token string Required EDGE API authentication token
baseUrl string Required Base URL for the API
timeout number 60 Request timeout in seconds
defaultOrigin string undefined Default Origin header for requests

Example:

const client = new NeuwoEdgeClient({
  token: "your-token",
  baseUrl: "https://custom.api.com",
  defaultOrigin: "https://yoursite.com",
  timeout: 90,
});

API Methods

REST API

Get AI Topics

const response = await client.getAiTopics({
  content: "Text to analyze", // Required
  documentId: "doc123", // Optional: save to database
  lang: "en", // Optional: ISO 639-1 code
  publicationId: "pub1", // Optional
  headline: "Article Headline", // Optional
  tagLimit: 15, // Optional: max tags (default: 15)
  tagMinScore: 0.1, // Optional: min score (default: 0.1)
  marketingLimit: undefined, // Optional
  marketingMinScore: 0.3, // Optional (default: 0.3)
  includeInSim: true, // Optional (default: true)
  articleUrl: "https://example.com", // Optional
});

Get Similar Articles

const articles = await client.getSimilar({
  documentId: "doc123", // Required
  maxRows: 10, // Optional: limit results
  pastDays: 30, // Optional: limit by date
  publicationIds: ["pub1", "pub2"], // Optional: filter by publication
});

Update Article

const article = await client.updateArticle({
  documentId: "doc123", // Required
  published: new Date("2024-01-15"), // Optional
  headline: "Updated Headline", // Optional
  writer: "Author Name", // Optional
  category: "News", // Optional
  content: "Updated content", // Optional
  summary: "Summary", // Optional
  publicationId: "pub1", // Optional
  articleUrl: "https://example.com", // Optional
  includeInSim: true, // Optional
});

Train AI Topics

const trainingTags = await client.trainAiTopics({
  documentId: "doc123", // Required
  tags: ["tag1", "tag2", "tag3"], // Required
});

EDGE API

Get AI Topics (Single URL)

const response = await client.getAiTopics({
  url: "https://example.com/article", // Required
  origin: "https://yoursite.com", // Optional: override default origin
});

Get AI Topics with Auto-Retry

const response = await client.getAiTopicsWait({
  url: "https://example.com/article", // Required
  origin: "https://yoursite.com", // Optional
  maxRetries: 10, // Optional (default: 10)
  retryInterval: 6, // Optional (default: 6s)
  initialDelay: 2, // Optional (default: 2s)
});

Raw Response Methods

All methods have *Raw variants that return the raw Response object:

// REST
const rawResponse = await client.getAiTopicsRaw({
  content: "Text",
});
console.log(rawResponse.status);
console.log(await rawResponse.text());

// EDGE
const rawResponse = await client.getAiTopicsRaw({
  url: "https://example.com",
});
console.log(await rawResponse.json());

Error Handling

The SDK provides specific exceptions for different error scenarios:

import {
  NeuwoRestClient,
  ValidationError,
  AuthenticationError,
  NoDataAvailableError,
  ContentNotAvailableError,
  NetworkError,
} from "neuwo-api";

const client = new NeuwoRestClient({
  token: "your-token",
  baseUrl: "https://custom.api.com",
});

try {
  const response = await client.getAiTopics({
    content: "Your content here",
  });
} catch (error) {
  if (error instanceof ValidationError) {
    console.error(`Invalid input: ${error.message}`);
  } else if (error instanceof AuthenticationError) {
    console.error(`Authentication failed: ${error.message}`);
  } else if (error instanceof NoDataAvailableError) {
    console.error(`Data not yet available: ${error.message}`);
  } else if (error instanceof ContentNotAvailableError) {
    console.error(`Content could not be analyzed: ${error.message}`);
  } else if (error instanceof NetworkError) {
    console.error(`Network error: ${error.message}`);
  } else {
    console.error(`Unexpected error: ${error.message}`);
  }
}

Exception Hierarchy

Logging

The SDK provides configurable logging for debugging and monitoring:

import { setupLogger, disableLogger, LogLevel } from "neuwo-api";

// Enable debug logging
setupLogger(LogLevel.DEBUG);

// Only show warnings and errors (default)
setupLogger(LogLevel.WARNING);

// Disable logging
disableLogger();

Available log levels:

Note: Sensitive information like tokens are automatically sanitized in log output.