Skip to content

Repository files navigation

Carbon HTTP (v3.0.1)

Carbon HTTP Mascot

CI BuildNPM PublishLicense: BSD 3-ClauseNode.js VersionZero Dependencies

Carbon HTTP is a zero-dependency, ultrasonic HTTP(S) client engineered specifically for enterprise Node.js microservices and financial infrastructure. Built with TypeScript targeting ES2022, it leverages native Node.js core modules (node:http, node:https, node:url, node:zlib) to deliver bulletproof resilience, low latency, and zero supply-chain risk.


🛡️ Key Enterprise Architectural Guarantees

Architectural DimensionCarbon HTTP ImplementationRisk Mitigated
Memory ProtectionBounded streaming payload limit (maxBodyLength, default 10MB)Prevents Out-of-Memory (OOM) process crashes from malicious/large responses
Timeout ModelAbsolute wall-clock timer with active socket destructionEliminates Slowloris idle socket deadline evasion attacks
Connection PoolingNative HTTP/HTTPS Keep-Alive agents (defaultHttpAgent, defaultHttpsAgent)Eliminates TCP/TLS handshake round-trip latency overhead
CompressionAutomatic Accept-Encoding: gzip, deflate, br with native zlib stream pipingMinimizes network bandwidth utilization by up to 85%
Observability & ErrorsStandard ES2022 Error.cause taxonomy (CarbonHttpError hierarchy)Enables APMs (Datadog, New Relic, Sentry) and loggers (Pino, Winston) to trace origin causes
Supply Chain Security0 External DependenciesEliminates transitive dependency vulnerability vectors

🚀 Quickstart

Installation

# NPM
npm install carbon-http
# Yarn
yarn add carbon-http
# pnpm
pnpm add carbon-http

💡 API Reference & Examples

1. High-Throughput Service-to-Service Request (GET)

import{Request,CarbonHttpTimeoutError,CarbonHttpMaxBodyLengthError,CarbonHttpNetworkError,}from'carbon-http';interfacePaymentAccount{accountId: string;balance: number;currency: string;}asyncfunctionfetchAccount(accountId: string): Promise<PaymentAccount>{try{constres=awaitRequest(`https://api.hsbc.internal/v1/accounts/${accountId}`,{timeoutMs: 3000,// 3s absolute wall-clock deadlinemaxBodyLength: 2*1024*1024,// 2MB max memory buffer thresholddecompress: true,// Transparent gzip/brotli decompression});// Safely parse JSON with explicit runtime validation callbackreturnres.json((raw: unknown)=>{constdata=rawasPaymentAccount;if(!data.accountId||typeofdata.balance!=='number'){thrownewError('Invalid schema payload returned from upstream service');}returndata;});}catch(err){if(errinstanceofCarbonHttpTimeoutError){console.error(`[TIMEOUT] Request to ${err.url} exceeded ${err.timeoutMs}ms deadline`);}elseif(errinstanceofCarbonHttpMaxBodyLengthError){console.error(`[OOM-GUARD] Payload exceeded ${err.maxBodyLength} bytes`);}elseif(errinstanceofCarbonHttpNetworkError){console.error(`[NETWORK] Socket failure: ${err.cause.message}`);}throwerr;}}

2. Request Cancellation with AbortSignal (POST)

import{Request,HttpMethod,CarbonHttpAbortError}from'carbon-http';constcontroller=newAbortController();// Cancel request if processing takes longer than expected externallyconsttimeoutId=setTimeout(()=>controller.abort(),2000);try{constres=awaitRequest('https://api.syniol.com/v2/transactions',{method: HttpMethod.POST,headers: {'Content-Type': 'application/json',},body: JSON.stringify({amount: 500.0,recipient: 'GB1234567890',}),signal: controller.signal,});clearTimeout(timeoutId);console.log(`Status: ${res.status}`);}catch(err){if(errinstanceofCarbonHttpAbortError){console.warn(`[ABORTED] Request to ${err.url} was cancelled via AbortSignal`);}}

🚨 Error Taxonomy

All exceptions thrown by carbon-http extend CarbonHttpError and propagate standard Error.cause objects:

CarbonHttpError (Base Error Class)
├── CarbonHttpNetworkError (DNS, TCP connection refused, socket drops)
├── CarbonHttpTimeoutError (Absolute wall-clock deadline exceeded)
├── CarbonHttpAbortError (Request cancelled via AbortSignal)
├── CarbonHttpJsonParseError (JSON syntax error with HTTP status & 200-char body preview)
└── CarbonHttpMaxBodyLengthError (Response payload exceeded maxBodyLength limit)

⚙️ Public Configuration & Types

CarbonHttpRequestOption

  • headers?: Record<string, string> — Custom request header map.
  • method?: HttpMethod — HTTP verb (HttpMethod.GET, HttpMethod.POST, etc.).
  • body?: string | Uint8Array | Buffer — Payload content.
  • port?: number — Override port.
  • timeoutMs?: number — Absolute wall-clock timeout in milliseconds (default: 30,000ms).
  • signal?: AbortSignal — Standard AbortSignal instance for cancellation.
  • maxBodyLength?: number — Maximum response memory buffer threshold in bytes (default: 10MB).
  • decompress?: boolean — Enable automatic Accept-Encoding and native zlib stream decompression (default: true).
  • agent?: HttpAgent | HttpsAgent | boolean — Custom Node.js HTTP/HTTPS Agent or false to disable pooling.

CarbonHttpResponse

  • status: number — Numerical HTTP status code.
  • headers: HttpHeaders — Normalized response header object.
  • incomingMessage: IncomingMessage — Raw Node.js stream reference.
  • text(): string — Returns body as UTF-8 string.
  • json<T>(parser?: (raw: unknown) => T): T — Parses response body as JSON with optional runtime parser callback.

📜 Governance & License

Copyright © 2022-2026 Syniol Limited.
Distributed under the BSD 3-Clause License.

About

Carbon HTTP is a zero-dependency, ultrasonic HTTP(S) client for Node.js (TypeScript & JavaScript)

Topics

Resources

Contributing

Stars

2 stars

Watchers

1 watching

Forks

Releases

Packages

Used by

Contributors

Languages