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

@synet/http

v1.0.5

Published

Modern, HTTP client with proxy support and events

Downloads

9

Readme

@synet/http

 __  __  ______  ______  ____            __  __              __      
/\ \/\ \/\__  _\/\__  _\/\  _`\         /\ \/\ \          __/\ \__   
\ \ \_\ \/_/\ \/\/_/\ \/\ \ \L\ \       \ \ \ \ \    ___ /\_\ \ ,_\  
 \ \  _  \ \ \ \   \ \ \ \ \ ,__/        \ \ \ \ \ /' _ `\/\ \ \ \/  
  \ \ \ \ \ \ \ \   \ \ \ \ \ \/          \ \ \_\ \/\ \/\ \ \ \ \ \_ 
   \ \_\ \_\ \ \_\   \ \_\ \ \_\           \ \_____\ \_\ \_\ \_\ \__\
    \/_/\/_/  \/_/    \/_/  \/_/            \/_____/\/_/\/_/\/_/\/__/
                                                                                  
version: 1.0.4                                                   

Modern, Unit Architecture-compliant HTTP client for TypeScript applications. Built for both Unit-based composition and serverless deployment.

Features

  • Unit Architecture Compliant - Teaching/learning contracts with capability composition
  • Cross-Platform - Browser, Node.js, Cloudflare Workers, Vercel Edge
  • Type-Safe - Full TypeScript support with comprehensive types
  • Result Pattern - Explicit error handling for complex operations
  • Pure Functions - Serverless-ready stateless operations
  • Built-in Retry - Exponential backoff retry logic
  • Proxy Support - HTTP/SOCKS5 proxy via axios (Node.js)
  • Multiple Patterns - Unit Architecture + Pure Functions

Quick Start

Unit Architecture Pattern

import { Http } from '@synet/http';

// Create HTTP unit
const http = Http.create({
  baseUrl: 'https://api.example.com',
  headers: { 'Authorization': 'Bearer your-token' },
  timeout: 10000
});

// Basic GET request
const result = await http.get('/users');
if (result.isSuccess()) {
  console.log(result.getValue().body);
}

// POST with data
const createResult = await http.post('/users', { 
  name: 'Alice', 
  email: '[email protected]' 
});

if (createResult.isFailure()) {
  console.error(createResult.getError());
}

Pure Functions Pattern

import { get, post, buildUrl, parseJson } from '@synet/http';

// Direct HTTP calls
const response = await get('https://api.example.com/users');
console.log(response.status, response.body);

// Parse JSON from response
const data = parseJson(response);
console.log(data);

// Build URLs with query parameters
const url = buildUrl('https://api.example.com', '/users', { 
  page: '1', 
  limit: '10' 
});

Installation

npm install @synet/http

Basic Usage

HTTP Methods

// GET request
const users = await http.get('/users');

// POST with JSON data
const created = await http.post('/users', {
  name: 'Bob',
  email: '[email protected]'
});

// PUT request
const updated = await http.put('/users/123', { name: 'Robert' });

// DELETE request
const deleted = await http.delete('/users/123');

// PATCH request
const patched = await http.patch('/users/123', { email: '[email protected]' });

Query Parameters

// Using buildUrl helper
const url = buildUrl('https://api.example.com', '/search', {
  q: 'javascript',
  page: '1',
  sort: 'date'
});

// Direct with HTTP unit
const results = await http.get('/search', {
  query: { q: 'javascript', page: '1' }
});

Authentication

import { createBearerAuth, createBasicAuth } from '@synet/http';

// Bearer token
const http = Http.create({
  baseUrl: 'https://api.example.com',
  headers: createBearerAuth('your-jwt-token')
});

// Basic auth
const httpBasic = Http.create({
  baseUrl: 'https://api.example.com',
  headers: createBasicAuth('username', 'password')
});

Error Handling

// Result pattern (recommended for complex operations)
const result = await http.get('/users');

result.match({
  success: (response) => {
    console.log('Success:', response.status);
    const data = parseJson(response);
    return data;
  },
  failure: (error) => {
    console.error('Failed:', error.message);
    return null;
  }
});

// Direct response handling
const response = await get('https://api.example.com/users');
if (response.ok) {
  console.log('Success!');
} else {
  console.error(`Error: ${response.status} ${response.statusText}`);
}

Status Code Helpers

import { 
  isSuccessStatus, 
  isClientError, 
  isServerError, 
  getStatusCategory 
} from '@synet/http';

const response = await get('/api/data');

if (isSuccessStatus(response.status)) {
  console.log('Success!');
} else if (isClientError(response.status)) {
  console.log('Client error - check your request');
} else if (isServerError(response.status)) {
  console.log('Server error - try again later');
}

console.log('Category:', getStatusCategory(response.status));

Retry Logic

import { retryRequest, get } from '@synet/http';

// Retry with exponential backoff
const response = await retryRequest(
  () => get('https://unreliable-api.com/data'),
  3, // max retries
  1000 // base delay (ms)
);

Proxy Support

New in v1.0.2 - Full HTTP/SOCKS5 proxy support via axios integration.

Basic Proxy Usage

import { Http, type ProxyConnection } from '@synet/http';

// Create HTTP unit
const http = Http.create({
  baseUrl: 'https://api.example.com'
});

// Define proxy connection
const proxy: ProxyConnection = {
  id: 'my-proxy',
  host: 'proxy.example.com',
  port: 8080,
  username: 'user123',
  password: 'pass456',
  protocol: 'http',
  country: 'us'
};

// Request with proxy
const result = await http.request({
  url: '/data',
  method: 'GET',
  proxy
});

if (result.isSuccess) {
  console.log('Response via proxy:', result.value.parsed);
}

Proxy Configuration

interface ProxyConnection {
  readonly id: string;           // Unique proxy identifier
  readonly host: string;         // Proxy hostname
  readonly port: number;         // Proxy port
  readonly username?: string;    // Proxy username (optional)
  readonly password?: string;    // Proxy password (optional)
  readonly protocol: 'http' | 'socks5'; // Proxy protocol
  readonly country?: string;     // Proxy country code (optional)
}

Integration with @synet/proxy

import { Http } from '@synet/http';
import { ProxyUnit } from '@synet/proxy';

// Create proxy unit with pool management
const proxyUnit = ProxyUnit.create({
  sources: [/* your proxy sources */]
});

await proxyUnit.init();

// Get proxy from pool
const proxy = await proxyUnit.get();

// Use with HTTP unit
const http = Http.create({ baseUrl: 'https://api.target.com' });
const result = await http.request({
  url: '/sensitive-data',
  method: 'GET',
  proxy  // Automatically handled by axios
});

Platform Support

  • Node.js: Full proxy support via axios (HTTP/SOCKS5)
  • Browser: Proxy handled by browser/OS settings
  • Serverless: Works with axios-compatible environments

Error Handling

const result = await http.request({
  url: '/api/data',
  proxy: myProxy
});

if (result.isFailure) {
  const error = result.error;
  
  // Check for proxy-specific errors
  if (error.message.includes('407')) {
    console.log('Proxy authentication failed');
  } else if (error.message.includes('ECONNREFUSED')) {
    console.log('Proxy connection refused');
  }
}

Unit Architecture Integration

Teaching Capabilities

const http = Http.create({ baseUrl: 'https://api.example.com' });

// Teach HTTP capabilities to other units
const contract = http.teach();
// contract.capabilities includes: get, post, put, delete, patch, request

Learning from Other Units

// Learn capabilities from other units
const enhancedHttp = http.learn([
  cryptoUnit.teach(), // Adds crypto.encrypt, crypto.decrypt
  authUnit.teach()    // Adds auth.sign, auth.verify
]);

// Now can use learned capabilities
if (enhancedHttp.can('crypto.encrypt')) {
  const encrypted = await enhancedHttp.execute('crypto.encrypt', sensitiveData);
}

Unit Information

// Get unit identity and capabilities
console.log(http.whoami()); // Unit identity
console.log(http.capabilities()); // Available capabilities
console.log(http.help()); // Usage documentation

Configuration Options

interface HttpConfig {
  baseUrl?: string;           // Base URL for requests
  headers?: Record<string, string>; // Default headers
  timeout?: number;           // Request timeout (ms)
  retries?: number;           // Max retry attempts
  retryDelay?: number;        // Base retry delay (ms)
}

const http = Http.create({
  baseUrl: 'https://api.example.com',
  headers: { 
    'User-Agent': 'MyApp/1.0',
    'Accept': 'application/json'
  },
  timeout: 30000,
  retries: 3,
  retryDelay: 1000
});

Response Format

interface HttpResponse {
  url: string;           // Request URL
  status: number;        // HTTP status code
  statusText: string;    // HTTP status text
  headers: Record<string, string>; // Response headers
  body: string;          // Response body
  ok: boolean;           // true if status 200-299
  timestamp: Date;       // Request timestamp
  duration: number;      // Request duration (ms)
}

Serverless Deployment

Perfect for serverless environments:

// Cloudflare Workers
export default {
  async fetch(request) {
    const response = await get('https://api.external.com/data');
    return new Response(response.body);
  }
};

// Vercel Edge Function
import { get } from '@synet/http';

export default async function handler(req) {
  const data = await get('https://api.example.com/users');
  return Response.json(parseJson(data));
}

TypeScript Support

Full type safety with intelligent autocompletion:

import type { HttpResponse, HttpConfig, TeachingContract } from '@synet/http';

// All functions and methods are fully typed
const response: HttpResponse = await get('/users');
const config: HttpConfig = { baseUrl: 'https://api.example.com' };

Browser Support

Works in all modern browsers with native fetch:

<script type="module">
  import { get } from 'https://unpkg.com/@synet/http';
  
  const response = await get('/api/users');
  console.log(response);
</script>

Next Steps

License

MIT - See LICENSE file for details