npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2025 – Pkg Stats / Ryan Hefner

hikvision-isapi-client

v0.1.52

Published

Enhanced TypeScript version of hikvision-isapi-client with modern features, type safety, and video decoding

Readme

hikvision-isapi-client

A modern TypeScript toolkit for connecting and controlling Hikvision equipment with enhanced error handling, dependency injection, and type safety.

npm version License: MIT TypeScript

Note: This is an enhanced TypeScript version with additional features. For the original JavaScript implementation, see hikvision-isapi-client.

Features

Enhanced Features (vs. original hikvision-api)

  • 🔒 Type Safety - Full TypeScript support with strict typing
  • 🛡️ Error Handling - Comprehensive error handling with custom error types
  • 🔧 Dependency Injection - Configurable HTTP client, logger, and validator
  • 📦 Modern Architecture - Clean barrel exports and modular design
  • Testing - Comprehensive test coverage with Jest
  • 🚀 Performance - Optimized build with tree shaking
  • 🎥 Video Decoding - WebAssembly-based video decoder for real-time streaming
  • 🌐 Cross-Platform - Works in Node.js and browsers
  • 🔄 Retry Logic - Built-in retry mechanism for network failures
  • 📊 Better Logging - Structured logging with configurable levels

Installation

npm install hikvision-isapi-client
yarn add hikvision-isapi-client
pnpm add hikvision-isapi-client

Why This Fork?

This project builds upon the excellent work from hikvision-isapi-client with the following enhancements:

| Feature | Original | This Version | | -------------- | ---------- | ---------------------------------- | | Language | JavaScript | TypeScript | | Type Safety | ❌ | ✅ Full TypeScript support | | Error Handling | Basic | ✅ Custom error types & retry logic | | Testing | Limited | ✅ Comprehensive test suite | | Architecture | Monolithic | ✅ Dependency injection | | Video Decoding | ❌ | ✅ WebAssembly decoder | | Documentation | Basic | ✅ Comprehensive API docs | | Build System | Webpack | ✅ ESBuild (faster) | | Package Size | Larger | ✅ Tree-shakable |

Migration from Original

If you're migrating from hikvision-isapi-client, the API is largely compatible:

// Original
const { Nvr } = require('hikvision-isapi-client');

// This version
import { Nvr } from 'hikvision-isapi-client';

// Same API, enhanced with TypeScript
const nvr = new Nvr(config);

Quick Start

Basic Usage

import { Nvr, Camera } from 'hikvision-isapi-client';

// Create NVR instance
const nvr = new Nvr({
  ip: '192.168.1.64',
  user: 'admin',
  password: 'your-password',
  version: 2
});

// Connect and use
await nvr.connect();
const channels = await nvr.fetchChannels();
const users = await nvr.fetchUsers();

Advanced Usage with Dependency Injection

import { 
  Nvr, 
  AxiosHttpClient, 
  ConsoleLogger, 
  DefaultConfigValidator 
} from 'hikvision-isapi-client';
import axios from 'axios';

// Create custom HTTP client with timeout
const httpClient = new AxiosHttpClient(
  axios.create({ timeout: 15000 })
);

// Create custom logger
const logger = new ConsoleLogger();

// Create NVR with custom dependencies
const nvr = new Nvr(
  {
    ip: '192.168.1.64',
    user: 'admin',
    password: 'your-password',
    version: 2
  },
  httpClient,
  logger,
  new DefaultConfigValidator()
);

Error Handling

import { 
  Nvr, 
  ConnectionError, 
  AuthenticationError, 
  ApiError 
} from 'hikvision-isapi-client';

try {
  const nvr = new Nvr(config);
  await nvr.connect();
  const deviceInfo = await nvr.deviceInfo();
} catch (error) {
  if (error instanceof ConnectionError) {
    console.error('Network connection failed:', error.message);
  } else if (error instanceof AuthenticationError) {
    console.error('Invalid credentials:', error.message);
  } else if (error instanceof ApiError) {
    console.error('API error:', error.message, 'Status:', error._statusCode);
  }
}

Camera Control

import { Camera } from 'hikvision-isapi-client';

const camera = new Camera({
  ip: '192.168.1.100',
  user: 'admin',
  password: 'your-password'
});

await camera.connect();

// PTZ Control
await camera.direction(1, 0); // Move right
await camera.zoom(1); // Zoom in
await camera.focus(1); // Focus

// Auxiliary controls
await camera.light(true); // Turn on light
await camera.wiper(true); // Turn on wiper

Video Decoding

The library includes a WebAssembly-based video decoder for real-time streaming:

import { getDecodeWorker } from 'hikvision-isapi-client';

// Create decoder worker
const isBrowser = typeof window !== 'undefined';
const wasmUrl = '/path/to/decoder.wasm';
const workerCode = getDecodeWorker(isBrowser, wasmUrl);

// Create worker
const worker = new Worker(URL.createObjectURL(new Blob([workerCode])));

// Handle decoded frames
worker.onmessage = (event) => {
  const { function: func, type, data, frameInfo } = event.data;
  
  if (func === 'GetFrameData') {
    if (type === 'videoType') {
      // Handle YUV video frame
      const yuvData = new Uint8Array(data);
      renderFrame(yuvData, frameInfo.width, frameInfo.height);
    } else if (type === 'audioType') {
      // Handle PCM audio frame
      const pcmData = new Uint8Array(data);
      playAudio(pcmData);
    }
  }
};

// Initialize decoder
worker.postMessage({
  command: 'SetStreamOpenMode',
  data: 0 // Stream mode
});

// Open stream
worker.postMessage({
  command: 'OpenStream',
  data: streamHeader,
  dataSize: streamHeader.length,
  bufPoolSize: 1024 * 1024
});

// Input stream data
worker.postMessage({
  command: 'InputData',
  data: streamData,
  dataSize: streamData.length
});

API Reference

NVR Methods

// Connection
await nvr.connect();
await nvr.disconnect();

// Device Information
const info = await nvr.deviceInfo();
await nvr.updateDeviceInfo(newInfo);

// Channel Management
const channels = await nvr.fetchChannels();
const channelId = await nvr.addChannel(channelData);
await nvr.editChannel(channelId, newData);
await nvr.deleteChannel(channelId);

// User Management
const users = await nvr.fetchUsers();
await nvr.addUser(userData);
await nvr.updateUser(userData);
await nvr.deleteUser(userId);

// Storage
const storages = await nvr.getStorages();
await nvr.formatHdd(hddId, progressCallback);

// Recording
const records = await nvr.searchRecords(channelId, streamType, startTime, endTime, pageNo, pageSize);
const allRecords = await nvr.searchAllRecords(channelId, streamType, startTime, endTime);

Configuration Options

interface BaseConfig {
  ip: string;           // Device IP address
  port?: number;        // Port (default: 80)
  user: string;         // Username
  password: string;     // Password
  timeout?: number;     // Request timeout (default: 10000ms)
  proxy?: string;       // Proxy URL for CORS
  version?: number;     // API version (1 or 2, default: 1)
  userPassword?: string; // Default password for new users
}

interface NvrConfig extends BaseConfig {
  wsPort?: number;      // WebSocket port (default: 7681)
  wasmUrl?: string;     // WASM decoder URL
  channelOffset?: number; // Channel offset (default: 32)
}

Error Types

  • ConnectionError - Network connection issues
  • AuthenticationError - Invalid credentials
  • ValidationError - Configuration validation errors
  • ApiError - API request failures
  • TimeoutError - Request timeouts
  • DeviceNotFoundError - Device not reachable

Migration Guide

From v0.1.x to v0.2.x

The library now uses dependency injection for better testability and flexibility:

// Old way
const nvr = new Nvr(config);

// New way (backward compatible)
const nvr = new Nvr(config);

// New way with custom dependencies
const nvr = new Nvr(config, httpClient, logger, validator);

Error handling is now more structured:

// Old way
try {
  await nvr.connect();
} catch (error) {
  console.error('Error:', error.message);
}

// New way
try {
  await nvr.connect();
} catch (error) {
  if (error instanceof AuthenticationError) {
    // Handle auth error specifically
  }
}

Troubleshooting

Common Issues

Connection Timeout

// Increase timeout for slow networks
const nvr = new Nvr({
  ...config,
  timeout: 30000 // 30 seconds
});

CORS Issues in Browser

// Use proxy for browser environments
const nvr = new Nvr({
  ...config,
  proxy: 'http://localhost:8080/proxy'
});

Authentication Errors

// Ensure correct API version
const nvr = new Nvr({
  ...config,
  version: 2 // Try version 1 if version 2 fails
});

Memory Issues with Video Decoder

// Limit buffer pool size
worker.postMessage({
  command: 'OpenStream',
  data: streamHeader,
  dataSize: streamHeader.length,
  bufPoolSize: 512 * 1024 // Reduce buffer size
});

Development

# Install dependencies
npm install

# Run tests
npm test
npm run test:watch
npm run test:coverage

# Build
npm run build

# Lint and format
npm run lint
npm run lint:fix
npm run format

# Type check
npm run type-check

# Quality check (all checks)
npm run quality:check

Changelog

v0.1.51

  • ✨ Added scoped package name hikvision-isapi-client
  • 🔧 Improved TypeScript types and error handling
  • 📦 Updated .npmignore for cleaner package
  • 🎥 Enhanced video decoder with better memory management
  • ✅ Comprehensive test coverage improvements

v0.1.x

  • 🚀 Initial release with basic NVR and Camera support
  • 🔒 TypeScript support and type safety
  • 🛡️ Custom error handling system
  • 🔧 Dependency injection architecture

Contributing

We welcome contributions! Please follow these steps:

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Make your changes with proper tests
  4. Run quality checks (npm run quality:check)
  5. Commit your changes (git commit -m 'Add some amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

Development Guidelines

  • Write tests for new features
  • Follow TypeScript best practices
  • Use conventional commit messages
  • Update documentation for API changes
  • Ensure all quality checks pass

Support

Acknowledgments

This project is built upon the foundation of hikvision-isapi-client by itskamol. We extend our gratitude for the original implementation and continue to build upon that excellent work.

Related Projects

License

MIT License - see the LICENSE file for details.


Made with ❤️ by ChenLuo | Built upon itskamol's hikvision-isapi-client