npm package: @respectify/client
Description: TypeScript client library for the Respectify API
Author: Respectify
Latest version: 0.3.2

# Respectify TypeScript Client

[![npm version](https://badge.fury.io/js/respectify.svg)](https://badge.fury.io/js/respectify)
[![License: MIT](https://img.shields.io/badge/License-MIT-yellow.svg)](https://opensource.org/licenses/MIT)

A TypeScript client library for the [Respectify API](https://respectify.ai), providing comment moderation, spam detection, toxicity analysis, and dogwhistle detection.

Respectify aims to be more than comment moderation: it tries to teach and edify users when a comment is rejected.

For bloggers, companies with articles, etc it provides a way to keep discourse civil and on-topic without censorship.

## Installation

```bash
npm install respectify
```

Requires Node.js 18 or later.

## Quick Start

```typescript
import { RespectifyClient } from "respectify";

const client = new RespectifyClient({
  email: "your-email@example.com",
  apiKey: "your-api-key",
});

// Initialize a topic — comments are evaluated in the context of an article/post
const topic = await client.initTopicFromText("This is my article content...");
const articleId = topic.article_id;

// Evaluate comment quality and toxicity
const score = await client.evaluateComment("This is a thoughtful comment", articleId);
console.log(`Quality: ${score.overall_score}/5, Toxicity: ${score.toxicity_score.toFixed(2)}`);

// Check if a comment is spam
const spam = await client.checkSpam("Great post!", articleId);
console.log(`Is spam: ${spam.is_spam}`);
```

### Megacall for Efficiency

Perform multiple analyses in a single API call:

```typescript
const result = await client.megacall({
  comment: "Test comment",
  articleId, // from initTopicFromText() or initTopicFromUrl()
  includeSpam: true,
  includeRelevance: true,
  includeCommentScore: true,
  includeDogwhistle: true,
  bannedTopics: ["politics"],
});

console.log(`Spam: ${result.spam_check?.is_spam}`);
console.log(`Quality: ${result.comment_score?.overall_score}/5`);
console.log(`On topic: ${result.relevance_check?.on_topic.on_topic}`);
console.log(`Dogwhistles: ${result.dogwhistle_check?.detection.dogwhistles_detected}`);
```

## API Reference

### Client Options

```typescript
const client = new RespectifyClient({
  email: "your-email@example.com", // Required
  apiKey: "your-api-key",          // Required
  baseUrl: "https://...",          // Optional, defaults to production
  version: "0.2",                  // Optional, defaults to "0.2"
  timeout: 30000,                  // Optional, milliseconds, defaults to 30000
  website: "myblog.com",           // Optional, for license tracking
});
```

### Methods

**Topic Management:**
- `initTopicFromText(text, topicDescription?)` — Initialize a topic from text content
- `initTopicFromUrl(url, topicDescription?)` — Initialize a topic from a URL

**Comment Analysis:**
- `evaluateComment(comment, articleId, replyToComment?)` — Quality and toxicity scoring
- `checkSpam(comment, articleId?)` — Spam detection (articleId optional)
- `checkRelevance(comment, articleId, bannedTopics?)` — Relevance and banned topic detection
- `checkDogwhistle(comment, articleId, sensitiveTopics?, dogwhistleExamples?)` — Dogwhistle detection

**Batch Operations:**
- `megacall(options)` — Multiple analyses in a single API call

**Authentication:**
- `checkUserCredentials()` — Verify API credentials and subscription status

### Error Handling

```typescript
import {
  RespectifyError,           // Base error
  AuthenticationError,       // Invalid credentials (401)
  BadRequestError,           // Invalid parameters (400)
  PaymentRequiredError,      // Subscription required (402)
  UnsupportedMediaTypeError, // Wrong content type (415)
  ServerError,               // Server issues (500+)
  ResponseParseError,        // Malformed API response
} from "respectify";

try {
  const result = await client.checkSpam("test", articleId);
} catch (error) {
  if (error instanceof AuthenticationError) {
    console.error("Check your API credentials");
  } else if (error instanceof PaymentRequiredError) {
    console.error("This feature requires a paid plan");
  } else if (error instanceof BadRequestError) {
    console.error(`Invalid request: ${error.message}`);
  }
}
```

All errors include `statusCode` and `responseData` properties for debugging.

### Response Sanitization

All string values in API responses are automatically HTML-encoded to prevent XSS. API responses echo back user-submitted comment text (in quoted fallacies, objectionable phrases, etc.) so this encoding is applied by default to make responses safe to render in HTML.

## Development

### Running Tests

Create a `tests/.env` file with your credentials (see `.env.example`):

```bash
RESPECTIFY_EMAIL=your-email@example.com
RESPECTIFY_API_KEY=your-api-key
```

```bash
npm install
npm test              # Run all tests (unit + integration)
npm run test:watch    # Watch mode
npm run typecheck     # Type checking only
npm run build         # Build for distribution
```

## Requirements

- Node.js >= 18 (uses native `fetch`)
- One runtime dependency: [`escape-html`](https://www.npmjs.com/package/escape-html) for response sanitization

## License

MIT — see [LICENSE](LICENSE) for details.

## Links

- [Respectify](https://respectify.ai)
- [API Documentation](https://docs.respectify.org)
- [GitHub Issues](https://github.com/respectify/respectify-ts/issues)