Skip to content

Latest commit

History

265 Commits

Folders and files

NameName
Last commit message
Last commit date

Repository files navigation

Bytekit

EN: A lean, high-performance TypeScript toolkit focused on Isomorphic HTTP Networking and Advanced Async Utilities . Deep-zero dependencies.
ES: Un toolkit TypeScript ligero y de alto rendimiento enfocado en Networking HTTP Isomórfico y Utilidades Asíncronas Avanzadas . Cero dependencias.

📊 Status / Estado

CICoverageCodeQLnpm versionnpm downloadsBundle SizeLicense: MIT


✨ Highlights / Características

  • 🌐 Isomorphic ApiClient: Works on Node.js 18+ and modern browsers (native fetch).
  • 🛡️ Schema Validation: Built-in adapters for Zod and Valibot. Fully typed responses.
  • 🔁 HTTP Resilience: Retries, Circuit Breaker, Rate Limiting, Request Cache, and Deduplication out of the box.
  • Async Toolkit: A powerful set of tools for concurrency (parallel, race), timing (sleep, timeout), and execution control (retry, debounce, throttle).
  • 📦 Deep-Zero Dependencies: No external runtime packages added to your bundle.
  • 🪵 Observability: Structured logging and performance profiling modules.
  • 🎯 95%+ Test Coverage: Rigorously tested core.

🚀 Quick Start / Inicio Rápido

Installation / Instalación

npm install bytekit
# or / o
pnpm add bytekit
# or / o
yarn add bytekit

1. HTTP Client with Schema Validation (Zod)

import{ApiClient}from"bytekit/api-client";import{zodAdapter}from"bytekit/schema-adapter";import{z}from"zod";constUserSchema=z.object({id: z.number(),name: z.string(),});consthttp=newApiClient({baseUrl: "https://api.my-service.com",retryPolicy: {maxAttempts: 3},// Automatic retriescircuitBreaker: {failureThreshold: 5}// Prevent cascading failures});// The response is safely validated and typed as { id: number, name: string }constuser=awaithttp.get("/users/1",{validateResponse: zodAdapter(UserSchema)});

2. Async Toolkit

import{parallel,retry,sleep,debounceAsync}from"bytekit/async";// Retry an async operation automaticallyconstdata=awaitretry(fetchDataFromUnstableAPI,{maxAttempts: 5,delayMs: 1000,backoff: "exponential"});// Run tasks in parallel with a concurrency limitconstresults=awaitparallel(tasks,{concurrency: 3});// Debounce an async functionconstfetchSuggestions=debounceAsync(api.getSuggestions,{waitMs: 300});

3. Modular Imports / Importaciones Modulares

Bytekit is fully tree-shakeable. You can import exactly what you need:

import{ApiClient}from"bytekit/api-client";import{Logger}from"bytekit/logger";import{retry,timeout}from"bytekit/async";import{StringUtils}from"bytekit/string-utils";

🛠️ CLI

Bytekit includes a command-line tool for rapid scaffolding directly from your terminal.

Security Notes for v3

  • Remote CLI fetches now require https:// unless you are targeting localhost or another loopback address.
  • Generated type names and property keys are sanitized before being written to disk.
  • ApiClient and ApiError are now safe-by-default for logging and serialization; sensitive payload fields are redacted unless you explicitly opt into risky logging.
  • StorageManager is not appropriate for secrets such as session tokens or API keys.
  • Migration details: see docs/guides/MIGRATION_v3_SECURITY.md.

Type Generation from an API Endpoint

# Generates src/types/users.ts with a typed interface inferred from the JSON response
bytekit --type https://api.example.com/users

Type Generation from Swagger / OpenAPI

# Generates src/types/api-docs.ts with all DTOs from the spec
bytekit --swagger https://api.example.com/swagger.json

Plain http:// is now reserved for local development only, for example http://localhost:3000/swagger.json .

DDD Bounded-Context Scaffolding

Generate a full Domain-Driven Design folder structure with hexagonal ports, entity, repository interface, use cases, and an HTTP adapter that uses ApiClient :

# Minimal: creates the DDD directory tree + hexagonal port stubs
bytekit --ddd --domain=Product --port=ProductRepository
# Full: also generates entity, repository interface, use cases & HTTP adapter
bytekit --ddd --domain=Product --port=ProductRepository --actions=create,findById,update,delete

The generated HTTP infrastructure repository always imports ApiClient from bytekit/api-client , keeping your data layer consistent with the rest of the toolkit.

Generated file tree (with --actions)
product/
├── domain/
│ ├── entities/ → ProductEntity.ts
│ ├── value-objects/
│ ├── aggregates/
│ ├── events/
│ ├── repositories/ → IProductRepository.ts
│ └── services/
├── application/
│ ├── use-cases/ → CreateProductUseCase.ts, FindByIdProductUseCase.ts, …
│ ├── dto/
│ └── ports/
│ ├── inbound/ → product-primary.port.ts
│ └── outbound/ → product-repository.port.ts
├── infrastructure/
│ ├── persistence/ → HttpProductRepository.ts (uses ApiClient)
│ └── config/
└── presentation/
└── http/
├── routes/
└── controllers/

📚 Core Modules

🔧 Networking & Resilience

  • ApiClient - Typed HTTP client with interceptors, retries, and schema validation support.
  • SchemaAdapter - Generic adapter to plug your favorite validation library (Zod, Valibot).
  • RetryPolicy & CircuitBreaker - Prevent failures and handle flaky endpoints.
  • RequestCache & RequestDeduplicator - Optimize your network bandwidth.
  • RateLimiter - Throttle your outbound requests.

⚡ Async Toolkit

  • Concurrency: parallel, race, allSettled, sequential .
  • Execution: retry, debounceAsync, throttleAsync .
  • Timing: sleep, timeout .

🛠️ Key Helpers

  • Logger & Profiler - Structured logs and performance monitoring.
  • UrlHelper - SEO-friendly slugify() and object-to-query-string stringify() serialization.
  • FileUploadHelper, StreamingHelper, WebSocketHelper - Specialized network tasks.
  • EventEmitter, DiffUtils, CacheManager, CryptoUtils .

🧩 Functional & Data Utilities

  • StringUtils - camelCase, pascalCase, snakeCase, truncate, slugify.
  • ObjectUtils - pick, omit, deepMerge, deepClone, flattenObject.
  • CollectionUtils - chunk, groupBy, uniqueBy, flatten, zip.
  • FnUtils - memoize, once, partial, noop, identity.
  • pipe / compose - Type-safe functional composition of up to 10 functions.

🤝 Contributing / Contribuir

EN: Contributions are welcome! Please read our contributing guidelines and our Code of Conduct, and feel free to submit issues and pull requests.
ES: ¡Las contribuciones son bienvenidas! Lee nuestras guías de contribución y nuestro Código de Conducta, y no dudes en enviar issues y pull requests.

📄 License / Licencia

MIT © Sebastián Martinez

About

ByteKit is a lean TypeScript toolkit for resilient HTTP workflows and async control

Topics

Resources

Code of conduct

Contributing

Stars

1 star

Watchers

0 watching

Forks

Releases

Packages

Used by

Contributors

Languages