===============
LIBRARY RULES
===============
From library maintainers:
- You must use StreamingHelper.streamJsonLines(endpoint, { onChunk }) to process large datasets without loading everything into memory. This is the only memory-efficient way to handle NDJSON.
- To handle real-time Server-Sent Events, you must use StreamingHelper.streamSSE(endpoint).subscribe(callback). It handles persistent connections and JSON parsing automatically.
- You must set ApiClient baseUrl dynamically by checking the environment: const isBrowser = typeof window !== 'undefined'; baseUrl: isBrowser ? '/api' : 'http://localhost:3000/api'.
- Always handle API failures by catching the exported ApiError class. The error.message property is automatically localized based on the client's locale and errorMessages config.
- To achieve full resilience, you must combine retryPolicy and circuitBreaker in the ApiClient config, and then inject a RateLimiter instance via a global request interceptor.
- You must prevent duplicate requests using the dedupe: true option and cache successful responses using cache: true with a defined cacheTTL in request options.
- To enable structured logging for retries, you must pass a ByteKit Logger instance to the ApiClient constructor. It automatically logs every request and retry lifecycle event.
- Standardize all collection handling using api.getList(path, { pagination, filters, sort }). This method automatically constructs complex query strings and handles paginated JSON responses.
- Always ensure type-safe responses by passing a zodAdapter(schema) or valibotAdapter(schema) to the validateResponse option in any ApiClient request.
- Configure automatic retries for transient failures by defining retryPolicy: { maxAttempts: N, initialDelayMs: X, backoffMultiplier: 2 } in the ApiClient constructor configuration.
- Always prefer modular sub-path imports for better tree-shaking: 'bytekit/api-client', 'bytekit/async', 'bytekit/streaming', 'bytekit/logger', 'bytekit/schema-adapter'.
### Install and Start React App
Source: https://github.com/sebamar88/bytekit/blob/main/examples/codesandbox/react/README.md
Install project dependencies and start the development server.
```bash
npm install
npm start
```
--------------------------------
### Basic API Client Setup and Usage
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/README.md
This example demonstrates how to initialize and use the ApiClient for basic GET requests. It shows how to specify a base URL and fetch data from an endpoint.
```bash
# Open in CodeSandbox
https://codesandbox.io/s/new?template=typescript
```
```typescript
import { ApiClient } from "bytekit";
const api = new ApiClient({
baseUrl: "https://jsonplaceholder.typicode.com",
});
// Try it!
const users = await api.get("/users");
console.log(users);
```
--------------------------------
### Install and Run React App
Source: https://github.com/sebamar88/bytekit/blob/main/examples/react-app/README.md
Install dependencies and start the development server for the React application.
```bash
npm install
npm run dev
```
--------------------------------
### Install Dependencies and Run Dev Server
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/codesandbox/vue-basic/README.md
Standard npm commands for installing project dependencies and starting the Vite development server for local development.
```bash
# Install dependencies
npm install
# Start dev server
npm run dev
# Build for production
npm run build
```
--------------------------------
### start()
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/Profiler.md
Starts a profiling session for a given label.
```APIDOC
## start(label)
### Description
Starts a profiling session for a given label.
### Parameters
#### Parameters
- **label** (string) - Required - The label for the profiling session.
### Returns
- **void**
```
--------------------------------
### Local Development Commands
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/codesandbox/react-basic/README.md
Standard npm commands for installing dependencies, starting the development server, and building the project for production.
```bash
# Install dependencies
npm install
# Start dev server
npm start
# Build for production
npm run build
```
--------------------------------
### Install Bytekit with npm
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/react.md
Install the Bytekit package using npm. This is the first step to using Bytekit in your project.
```bash
npm install bytekit
```
--------------------------------
### Install bytekit CLI globally
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/GETTING_STARTED.md
Install the bytekit command-line interface globally for access to utilities like code generation. Verify the installation using `sutils --version`.
```bash
npm install -g bytekit
# Verify installation
sutils --version
```
--------------------------------
### Install and Run Vite App
Source: https://github.com/sebamar88/bytekit/blob/main/examples/README.md
Instructions for setting up and running the standalone Vite applications for each framework.
```bash
cd react-app # or vue-app, svelte-app
npm install
npm run dev
```
--------------------------------
### Project Directory Structure
Source: https://github.com/sebamar88/bytekit/blob/main/docs/README.md
Overview of the bytekit documentation directory structure, showing the organization of README files, guides, examples, and auto-generated API docs.
```tree
docs/
├── README.md (this file)
├── API.md (API overview)
├── guides/
│ ├── GETTING_STARTED.md (400+ lines)
│ ├── ADVANCED_USAGE.md (500+ lines)
│ └── BEST_PRACTICES.md (500+ lines)
├── examples/
│ ├── README.md (snippets & demos)
│ └── codesandbox/
│ ├── react-basic/
│ ├── vue-basic/
│ └── svelte-basic/
└── api/ (auto-generated by TypeDoc)
```
--------------------------------
### Install Bytekit with npm, pnpm, or yarn
Source: https://github.com/sebamar88/bytekit/blob/main/README.md
Use your preferred package manager to install the Bytekit library.
```bash
npm install bytekit
# or / o
pnpm add bytekit
# or / o
yarn add bytekit
```
--------------------------------
### Basic Bytekit Client Setup in Vue
Source: https://github.com/sebamar88/bytekit/blob/main/examples/vue-app/README.md
Create a basic Bytekit API client instance within a Vue 3 Composition API script setup.
```vue
```
--------------------------------
### Example Usage with Groq API
Source: https://github.com/sebamar88/bytekit/blob/main/docs/FIX_GROQ_API_COMPATIBILITY.md
Demonstrates how to initialize and use the `ApiClient` with Groq API, including setting base URL and default authorization headers.
```typescript
import { ApiClient } from "bytekit";
const client = new ApiClient({
baseURL: "https://api.groq.com/openai/v1",
defaultHeaders: {
Authorization: `Bearer ${GROQ_API_KEY}`,
"Content-Type": "application/json",
},
});
const response = await client.post("/chat/completions", {
model: "llama3-8b-8192",
messages: [{ role: "user", content: "Hello!" }],
});
console.log(response.choices[0].message.content);
```
--------------------------------
### Make a basic HTTP GET request with ApiClient
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/GETTING_STARTED.md
Create an ApiClient instance and make a simple GET request to fetch user data. Ensure the `bytekit` library is imported.
```typescript
import { ApiClient } from "bytekit";
// Create a client instance
const api = new ApiClient({
baseUrl: "https://jsonplaceholder.typicode.com",
locale: "en", // or 'es' for Spanish
});
// Make your first request
const users = await api.get("/users");
console.log("Users:", users);
```
--------------------------------
### Vue Composition API Data Fetching with ApiClient
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/README.md
This example shows how to use ByteKit's ApiClient within a Vue 3 Composition API setup. It demonstrates fetching user data when the component is mounted and managing reactive state for users and loading status.
```typescript
import { ref, onMounted } from "vue";
import { ApiClient } from "bytekit";
const api = new ApiClient({
baseUrl: "https://api.example.com",
});
export default {
setup() {
const users = ref([]);
const loading = ref(true);
onMounted(async () => {
try {
users.value = await api.get("/users");
} finally {
loading.value = false;
}
});
return { users, loading };
},
};
```
--------------------------------
### start() Method
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/PollingHelper.md
Starts the polling operation. This method initiates the repeated execution of the provided function until a condition is met or an error occurs.
```APIDOC
## Methods
### start()
Starts polling
#### Returns
- `Promise>`
```
--------------------------------
### Basic Bytekit API Client Setup in Svelte
Source: https://github.com/sebamar88/bytekit/blob/main/examples/svelte-app/README.md
Initialize a Bytekit API client with a base URL within a Svelte script block.
```svelte
```
--------------------------------
### Make HTTP Requests with Bytekit
Source: https://github.com/sebamar88/bytekit/blob/main/examples/README.md
Shows how to perform GET and POST requests, including adding custom headers for authentication.
```javascript
// GET request
const user = await client.get("/users/1");
// POST request
const newUser = await client.post("/users", {
name: "John Doe",
email: "john@example.com",
});
// With custom headers
const data = await client.get("/protected", {
headers: { Authorization: "Bearer token" },
});
```
--------------------------------
### Use ApiClient with Groq API
Source: https://github.com/sebamar88/bytekit/blob/main/docs/RELEASE_NOTES_v1.0.3.md
Example demonstrating how to instantiate and use the ApiClient with Groq API after updating bytekit. It shows setting up the base URL and default headers, including the Authorization token.
```javascript
import { ApiClient } from "bytekit";
const client = new ApiClient({
baseURL: "https://api.groq.com/openai/v1",
defaultHeaders: {
Authorization: `Bearer ${process.env.GROQ_API_KEY}`,
"Content-Type": "application/json",
},
});
const response = await client.post("/chat/completions", {
model: "llama3-8b-8192",
messages: [{ role: "user", content: "Hola, ¿cómo estás?" }],
max_tokens: 100,
});
console.log(response.choices[0].message.content);
```
--------------------------------
### Basic Bytekit API Client Setup in React
Source: https://github.com/sebamar88/bytekit/blob/main/examples/codesandbox/react/README.md
Initialize a Bytekit API client instance within a React component using `useState` for managing the client lifecycle.
```jsx
import { createApiClient } from "bytekit";
import { useState } from "react";
function App() {
const [client] = useState(() =>
createApiClient({
baseUrl: "https://api.example.com",
})
);
// Use client for requests
}
```
--------------------------------
### Modular Imports
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/README.md
Shows examples of importing specific modules from Bytekit, highlighting its tree-shakeable nature and allowing developers to import only the necessary functionalities.
```APIDOC
## Modular Imports
### Description
Bytekit is designed to be fully tree-shakeable. This means you can import only the specific modules or functions you need, which helps in reducing the final bundle size of your application.
### Usage
Import individual components or utilities directly from their respective paths within the `bytekit` package.
### Examples
```typescript
// Importing the ApiClient
import { ApiClient } from "bytekit/api-client";
// Importing the Logger
import { Logger } from "bytekit/logger";
// Importing multiple async utilities
import { retry, timeout } from "bytekit/async";
// Importing a specific helper
import { UrlSlugHelper } from "bytekit/url-slug-helper";
```
```
--------------------------------
### get()
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/ApiClient.md
Performs a GET request to the specified path.
```APIDOC
## get()
### Description
Performs a GET request to the specified path.
### Method
GET
### Endpoint
`/{path}`
### Parameters
#### Path Parameters
- **path** (`string`) - Required - The path for the GET request.
#### Query Parameters
- **options** (`RequestOptions`) - Optional - Options for the request, including headers and query parameters.
### Returns
`Promise` - A promise that resolves with the response data of type T.
```
--------------------------------
### ApiClient - Basic Request
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/README.md
Demonstrates basic GET and POST requests using the ApiClient. Ensure the ApiClient is initialized with a baseUrl.
```typescript
import { ApiClient } from "bytekit";
const api = new ApiClient({
baseUrl: "https://jsonplaceholder.typicode.com",
});
// GET request
const users = await api.get("/users");
console.log(users);
// POST request
const newUser = await api.post("/users", {
name: "John Doe",
email: "john@example.com",
});
```
--------------------------------
### HTTP Client with Schema Validation (Zod)
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/README.md
Demonstrates how to initialize the ApiClient with a base URL and retry policy, and how to make a GET request with response validation using Zod.
```APIDOC
## HTTP Client with Schema Validation (Zod)
### Description
Initialize the `ApiClient` with configuration options such as `baseUrl`, `retryPolicy`, and `circuitBreaker`. Then, make a GET request to a specified endpoint, providing a schema adapter (e.g., `zodAdapter`) to validate the response. The response will be safely typed according to the provided schema.
### Method
`ApiClient.get(url, options)`
### Endpoint
`/users/:id` (example path)
### Parameters
#### Path Parameters
- **id** (number) - Required - The ID of the user to retrieve.
#### Query Parameters
None explicitly documented for this example.
#### Request Body
None for GET request.
### Request Example
```typescript
import { ApiClient } from "bytekit/api-client";
import { zodAdapter } from "bytekit/schema-adapter";
import { z } from "zod";
const UserSchema = z.object({
id: z.number(),
name: z.string(),
});
const http = new ApiClient({
baseUrl: "https://api.my-service.com",
retryPolicy: { maxAttempts: 3 }, // Automatic retries
circuitBreaker: { failureThreshold: 5 } // Prevent cascading failures
});
// The response is safely validated and typed as { id: number, name: string }
const user = await http.get("/users/1", {
validateResponse: zodAdapter(UserSchema)
});
```
### Response
#### Success Response (200)
- **user** ({ id: number, name: string }) - The validated user data.
```
--------------------------------
### Pinia Integration with Bytekit
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/vue.md
Integrate Bytekit with Pinia stores for centralized API logic and state management in Vue applications. This example shows fetching and creating users.
```javascript
// stores/users.js
import { defineStore } from "pinia";
import { createApiClient } from "bytekit";
const client = createApiClient({
baseUrl: "https://api.example.com",
});
export const useUsersStore = defineStore("users", {
state: () => ({
users: [],
loading: false,
error: null,
}),
actions: {
async fetchUsers() {
this.loading = true;
try {
this.users = await client.get("/users");
this.error = null;
} catch (err) {
this.error = err.message;
} finally {
this.loading = false;
}
},
async createUser(userData) {
return await client.post("/users", userData);
},
},
});
```
--------------------------------
### Implement Signal-based Store
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/BEST_PRACTICES.md
Create a reactive store using ByteKit's `signal`, `computed`, and `effect` primitives for managing application state. This example demonstrates loading and displaying user data.
```typescript
import { signal, computed, effect } from "bytekit";
class UserStore {
private _users = signal([]);
private _loading = signal(false);
private _error = signal(null);
get users() {
return this._users.value;
}
get loading() {
return this._loading.value;
}
get error() {
return this._error.value;
}
activeUsers = computed(() =>
this._users.value.filter((u) => u.status === "active")
);
async loadUsers() {
this._loading.value = true;
this._error.value = null;
try {
const users = await api.get("/users");
this._users.value = users;
} catch (error) {
this._error.value = error.message;
} finally {
this._loading.value = false;
}
}
}
export const userStore = new UserStore();
// React to changes
effect(() => {
console.log("Active users:", userStore.activeUsers.length);
});
```
--------------------------------
### startWithAbort() Method
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/PollingHelper.md
Starts polling with the capability to abort the operation. This allows for controlled termination of the polling process.
```APIDOC
## Methods
### startWithAbort()
Start polling with abort capability
#### Returns
- `Promise>`
```
--------------------------------
### Generated DDD File Tree
Source: https://github.com/sebamar88/bytekit/blob/main/README.md
This is an example of the file tree generated by the bytekit --ddd command when using the --actions flag. It outlines the structure for domain, application, infrastructure, and presentation layers.
```text
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/
```
--------------------------------
### Configure ApiClient for Integration Tests
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/BEST_PRACTICES.md
Set up the ApiClient with a base URL and timeout for integration tests. This example demonstrates testing user creation and handling rate limiting scenarios.
```typescript
import { ApiClient, TimeUtils } from "bytekit";
describe("Users API", () => {
let api: ApiClient;
beforeEach(() => {
api = new ApiClient({
baseUrl: "http://localhost:3000",
timeoutMs: 5000,
});
});
it("should create a user", async () => {
const newUser = {
name: "John Doe",
email: "john@example.com",
};
const user = await api.post("/users", newUser);
expect(user.id).toBeDefined();
expect(user.name).toBe(newUser.name);
});
it("should handle rate limiting", async () => {
// Make many requests
const requests = Array.from({ length: 100 }, (_, i) =>
api.get(`/users/${i}`)
);
await expect(Promise.all(requests)).rejects.toThrow(/rate limit/i);
});
});
```
--------------------------------
### get()
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/CacheManager.md
Retrieves a value from the cache by its key.
```APIDOC
## get()
### Description
Retrieves a value from the cache.
### Signature
```typescript
get(key: string): T | null
```
### Parameters
#### key
- **key** (`string`) - The key of the value to retrieve.
### Returns
- `T | null` - The cached value if found, otherwise null.
```
--------------------------------
### React Data Fetching with ApiClient
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/README.md
Integrate ByteKit's ApiClient into React components for streamlined data fetching. This example demonstrates setting up the client, fetching user data within a useEffect hook, and managing loading states.
```typescript
import { useState, useEffect } from 'react';
import { ApiClient } from 'bytekit';
const api = new ApiClient({
baseUrl: 'https://api.example.com',
});
function UserList() {
const [users, setUsers] = useState([]);
const [loading, setLoading] = useState(true);
useEffect(() => {
async function loadUsers() {
try {
const data = await api.get('/users');
setUsers(data);
} finally {
setLoading(false);
}
}
loadUsers();
}, []);
if (loading) return
Loading...
;
return (
{users.map(user => (
{user.name}
))}
);
}
```
--------------------------------
### Integrate Bytekit with VueQuery for Data Fetching
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/vue.md
Use Bytekit with TanStack Query (VueQuery) for advanced data fetching, caching, and state management. This example shows fetching and creating users.
```vue
Loading...
Error: {{ error.message }}
{{ user.name }}
```
--------------------------------
### Create API Client in Vue 3
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/vue.md
Create a Bytekit API client instance within a Vue 3 script setup. Configure base URL, timeout, and retry options.
```vue
```
--------------------------------
### Vue 3 API Client Integration
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/GETTING_STARTED.md
Use ByteKit's `createApiClient` within a Vue 3 component's `setup` function to fetch data when the component is mounted.
```typescript
import { createApiClient } from "bytekit";
import { ref, onMounted } from "vue";
export default {
setup() {
const users = ref([]);
const api = createApiClient({
baseURL: "https://api.example.com",
});
onMounted(async () => {
users.value = await api.get("/users");
});
return { users };
},
};
```
--------------------------------
### Update package.json Version
Source: https://github.com/sebamar88/bytekit/blob/main/docs/RELEASE_NOTES_v1.0.3.md
Example of how to update the version number in the `package.json` file to reflect the new release.
```json
{
"version": "1.0.3" // o la que corresponda
}
```
--------------------------------
### Create Bytekit API Client
Source: https://github.com/sebamar88/bytekit/blob/main/examples/README.md
Demonstrates how to create a Bytekit API client with base URL, timeout, and retry configurations.
```javascript
import { createApiClient } from "bytekit";
const client = createApiClient({
baseUrl: "https://api.example.com",
timeout: 5000,
retry: { maxRetries: 3 },
});
```
--------------------------------
### Prepare for Bytekit v1.0.3 Release
Source: https://github.com/sebamar88/bytekit/blob/main/docs/RELEASE_NOTES_v1.0.3.md
Commands to clean and rebuild the project, run all tests, and check for linting errors before publishing the new version.
```bash
# Limpiar y reconstruir
rm -rf dist/
pnpm build
# Ejecutar todos los tests
pnpm test
# Verificar que no hay errores de linting
pnpm lint
```
--------------------------------
### connect()
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/WebSocketHelper.md
Establishes a connection to the WebSocket server.
```APIDOC
## connect()
### Description
Connect to WebSocket.
### Returns
- `Promise` - A promise that resolves when the connection is established.
```
--------------------------------
### Make Type-Safe GET Request
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/codesandbox/react-basic/README.md
Perform a type-safe GET request to fetch user data. Define an interface for the expected response structure to ensure type safety.
```typescript
interface User {
id: number;
name: string;
email: string;
}
const users = await api.get("/users");
```
--------------------------------
### getSize()
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/RequestCache.md
Gets the approximate size of the cache in bytes.
```APIDOC
## getSize()
### Description
Gets the approximate size of the cache in bytes.
### Returns
- **number**: The size of the cache in bytes.
```
--------------------------------
### getInFlightCount
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/RequestDeduplicator.md
Gets the number of currently in-flight requests.
```APIDOC
## getInFlightCount()
### Description
Get number of in-flight requests.
### Returns
- **number**: The count of in-flight requests.
```
--------------------------------
### get()
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/StorageManager.md
Retrieves a value from storage by its key. Returns null if the key does not exist or the item has expired.
```APIDOC
## get(key: string)
### Description
Retrieves a value from storage by its key. Returns null if the key does not exist or the item has expired.
### Type Parameters
#### T
Represents the type of the value expected to be retrieved.
### Parameters
#### Parameters
- **key** (string) - The key of the item to retrieve.
### Returns
`T` | `null` - The retrieved value or null if not found or expired.
```
--------------------------------
### Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/SlidingWindowRateLimiter.md
Initializes a new instance of the SlidingWindowRateLimiter with optional configuration.
```APIDOC
## Constructor
### Description
Initializes a new instance of the SlidingWindowRateLimiter.
### Signature
```typescript
new SlidingWindowRateLimiter(config?: RateLimiterConfig)
```
### Parameters
#### config
- **config** (`RateLimiterConfig`): Optional configuration object for the rate limiter. Defaults to `{}`.
```
--------------------------------
### get()
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/RequestCache.md
Retrieves cached data for a given URL. Returns the data if found and valid, otherwise null.
```APIDOC
## get(url, options?)
### Description
Retrieves cached data for a given URL.
### Type Parameters
#### T
- **T**: The expected type of the cached data.
### Parameters
#### url
- **url** (string) - The URL to retrieve cached data for.
#### options
- **options** (Record) - Optional - Additional options for retrieving data.
### Returns
- **T | null**: The cached data of type T, or null if not found or invalid.
```
--------------------------------
### Publish New Version
Source: https://github.com/sebamar88/bytekit/blob/main/docs/FIX_GROQ_API_COMPATIBILITY.md
Build the project and publish the new version to npm using pnpm build and npm publish.
```bash
pnpm build
npm publish
```
--------------------------------
### Generate DDD Bounded-Context Scaffolding
Source: https://github.com/sebamar88/bytekit/blob/main/README.md
Use the bytekit CLI to generate a Domain-Driven Design folder structure. The minimal command creates the directory tree and hexagonal port stubs. The full command also generates entity, repository interface, use cases, and an HTTP adapter.
```bash
# Minimal: creates the DDD directory tree + hexagonal port stubs
bytekit --ddd --domain=Product --port=ProductRepository
```
```bash
# Full: also generates entity, repository interface, use cases & HTTP adapter
bytekit --ddd --domain=Product --port=ProductRepository --actions=create,findById,update,delete
```
--------------------------------
### Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/WebSocketHelper.md
Initializes a new instance of the WebSocketHelper class.
```APIDOC
## new WebSocketHelper(url, options)
### Description
Initializes a new instance of the WebSocketHelper class.
### Parameters
#### url
- **url** (string) - The WebSocket server URL.
#### options
- **options** (WebSocketOptions) - Optional configuration settings for the WebSocket connection. Defaults to `{}`.
### Returns
- `WebSocketHelper` - A new instance of WebSocketHelper.
```
--------------------------------
### Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/FileUploadHelper.md
Initializes a new instance of the FileUploadHelper class.
```APIDOC
## Constructor
### Description
Initializes a new instance of the FileUploadHelper class.
### Returns
- `FileUploadHelper`: An instance of the FileUploadHelper class.
```
--------------------------------
### Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/RateLimiter.md
Initializes a new instance of the RateLimiter class.
```APIDOC
## Constructor
### Description
Initializes a new instance of the RateLimiter class.
### Parameters
#### config
- **config** (RateLimiterConfig) - Optional - Configuration object for the rate limiter.
```
--------------------------------
### Array Manipulation with ByteKit
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/GETTING_STARTED.md
Use ArrayUtils to chunk arrays into smaller arrays, get unique values, shuffle elements, and flatten nested arrays.
```typescript
import { ArrayUtils } from "bytekit";
// Chunk arrays
const chunks = ArrayUtils.chunk([1, 2, 3, 4, 5], 2);
// => [[1, 2], [3, 4], [5]]
// Unique values
const unique = ArrayUtils.unique([1, 2, 2, 3, 3, 3]);
// => [1, 2, 3]
// Shuffle
const shuffled = ArrayUtils.shuffle([1, 2, 3, 4, 5]);
// Flatten nested arrays
const flat = ArrayUtils.flatten([
[1, 2],
[3, [4, 5]],
]);
// => [1, 2, 3, 4, 5]
```
--------------------------------
### HTTP Headers Normalization Example
Source: https://github.com/sebamar88/bytekit/blob/main/docs/RELEASE_NOTES_v1.0.3.md
HTTP headers are normalized to lowercase according to the HTTP/2 standard. This is a normal and correct behavior that works with all HTTP servers.
```javascript
// Al enviar
{ 'Authorization': 'Bearer token' }
// Se convierte a
{ 'authorization': 'Bearer token' }
// Esto es correcto y funciona en todos los servidores HTTP
```
--------------------------------
### Basic QueryClient Implementation
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/QUERY_CLIENT_STATE.md
Initialize ApiClient and QueryClient for basic data fetching. Configure cache duration using staleTime.
```typescript
import { QueryClient, ApiClient } from 'bytekit';
const api = new ApiClient({ baseUrl: 'https://api.example.com' });
const queryClient = new QueryClient(api);
async function loadUser(id: string) {
return await queryClient.query({
queryKey: ['user', id],
path: `/users/${id}`,
staleTime: 60000 // Cache for 1 minute
});
}
```
--------------------------------
### Svelte Event Handling
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/codesandbox/svelte-basic/README.md
Attach event listeners to DOM elements using the `on:` directive. This example shows how to handle a click event to trigger a data refresh.
```svelte
```
--------------------------------
### Publish Bytekit to npm
Source: https://github.com/sebamar88/bytekit/blob/main/docs/RELEASE_NOTES_v1.0.3.md
Commands to log in to npm and publish the new version of the bytekit package.
```bash
# Asegurarse de estar logueado en npm
npm whoami
# Si no está logueado
npm login
# Publicar
npm publish
```
--------------------------------
### Type-Safe HTTP Requests with ApiClient
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/GETTING_STARTED.md
Utilize ApiClient for type-safe HTTP requests by defining response types. Supports GET, POST with bodies, and requests with query parameters.
```typescript
import { ApiClient } from "bytekit";
// Define your response types
interface User {
id: number;
name: string;
email: string;
}
// Create a typed client
const api = new ApiClient({
baseUrl: "https://api.example.com",
defaultHeaders: {
Authorization: "Bearer YOUR_TOKEN",
},
timeoutMs: 10000, // 10 seconds
});
// Type-safe GET request
const users = await api.get("/users");
// POST with body
const newUser = await api.post("/users", {
name: "John Doe",
email: "john@example.com",
});
// With query parameters
const results = await api.get("/users", {
searchParams: {
page: 1,
limit: 10,
},
});
```
--------------------------------
### Start and Stop Polling with PollingHelper
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/ADVANCED_USAGE.md
Use PollingHelper to periodically execute a function and stop when a condition is met or after a timeout. Configure interval, max retries, and error handling.
```typescript
import { PollingHelper } from "bytekit";
const poller = new PollingHelper({
interval: 5000, // Poll every 5 seconds
maxRetries: 10,
onError: (error) => console.error("Poll error:", error),
});
poller.start(async () => {
const status = await checkJobStatus(jobId);
if (status === "completed") {
poller.stop();
console.log("Job completed!");
}
return status;
});
// Stop polling manually
setTimeout(() => poller.stop(), 60000);
```
--------------------------------
### Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/CacheManager.md
Initializes a new instance of the CacheManager class.
```APIDOC
## Constructor
### Description
Initializes a new instance of the CacheManager class.
### Signature
```typescript
new CacheManager(options?: CacheManagerOptions)
```
### Parameters
#### options
- **options** (`CacheManagerOptions`) - Optional - Configuration options for the cache manager.
```
--------------------------------
### Specific API error handling for Groq
Source: https://github.com/sebamar88/bytekit/blob/main/docs/ERROR_HANDLING_COMPARISON.md
Example of handling specific API error types, like 'rate_limit_exceeded', by inspecting the structured error body returned by Groq.
```typescript
try {
await groqClient.post("/chat/completions", { ... });
} catch (error) {
if (error instanceof ApiError) {
// Groq devuelve errores estructurados
const groqError = error.body as {
error?: {
message: string;
type: string;
code?: string;
}
};
if (groqError?.error?.type === "rate_limit_exceeded") {
console.log("Rate limited! Wait before retry");
console.log("Details:", groqError.error.message);
}
}
}
```
--------------------------------
### ApiClient Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/ApiClient.md
Initializes a new instance of the ApiClient class.
```APIDOC
## Constructor
### Description
Initializes a new instance of the ApiClient class.
### Parameters
####
- **
__namedParameters** (`ApiClientConfig`) - Description of ApiClientConfig
### Returns
`ApiClient`
```
--------------------------------
### Vue with TypeScript Support
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/vue.md
Utilize Bytekit with TypeScript in Vue.js for enhanced type safety. This example demonstrates defining interfaces for API responses and using generic types with the client.
```vue
{{ user.name }}
```
--------------------------------
### Environment Configuration with EnvManager
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/BEST_PRACTICES.md
Use EnvManager to access environment variables for configuration. Supports getting strings, numbers, and booleans with default values. Includes validation for required and secret variables.
```typescript
// config/api.config.ts
import { EnvManager } from "bytekit";
const env = new EnvManager();
export const apiConfig = {
baseUrl: env.get("VITE_API_URL", "https://api.example.com"),
timeout: env.getNumber("VITE_API_TIMEOUT", 10000),
enableLogs: env.getBoolean("VITE_ENABLE_API_LOGS", false),
locale: env.get("VITE_LOCALE", "en"),
};
// Validate required variables
env.validate({
VITE_API_URL: { required: true },
VITE_API_KEY: { required: true, secret: true },
});
```
--------------------------------
### Profiler Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/Profiler.md
Initializes a new Profiler instance. An optional namespace can be provided.
```APIDOC
## new Profiler(namespace?)
### Description
Initializes a new Profiler instance.
### Parameters
#### Parameters
- **namespace** (string) - Optional - The namespace for the profiler.
### Returns
- **Profiler** - A new Profiler instance.
```
--------------------------------
### Implement API Middleware for Authentication
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/ADVANCED_USAGE.md
Use the middleware pattern with ApiClient to intercept requests and responses. This example shows how to add an Authorization header and handle 401 errors by refreshing the token.
```typescript
import { ApiClient } from "bytekit";
const authMiddleware = {
request: async (url: string, init: RequestInit) => {
const token = await getAuthToken();
const headers = new Headers(init.headers);
headers.set("Authorization", `Bearer ${token}`);
return [url, { ...init, headers }];
},
response: async (response: Response) => {
if (response.status === 401) {
await refreshAuthToken();
// Retry request with new token
}
return response;
},
};
const api = new ApiClient({
baseUrl: "https://api.example.com",
interceptors: authMiddleware,
});
```
--------------------------------
### QueryStringHelper Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/QueryStringHelper.md
Initializes a new instance of the QueryStringHelper class.
```APIDOC
## Constructor
### Description
Initializes a new instance of the QueryStringHelper class.
### Returns
`QueryStringHelper`
```
--------------------------------
### Vue Error Handling with Bytekit
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/vue.md
Handle API request errors gracefully in Vue components. This example shows how to catch errors, check status codes, and display user-friendly messages.
```vue
{{ errorMessage }}
{{ user.name }}
```
--------------------------------
### Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/RequestCache.md
Initializes a new instance of the RequestCache class with optional configuration.
```APIDOC
## new RequestCache(config)
### Description
Initializes a new instance of the RequestCache class.
### Parameters
#### config
- **config** (CacheConfig) - Optional - Configuration object for the cache.
```
--------------------------------
### Scaffold DDD/Hexagonal Architecture
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/CLI_AUTOMATION.md
Create a project skeleton for a bounded context using Domain-Driven Design principles. Specify the domain name, repository port, and desired actions to generate the initial structure.
```bash
npx bytekit --ddd --domain=Product --port=ProductRepository --actions=create,findById,update,delete
```
--------------------------------
### API Client Configuration with Bytekit
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/BEST_PRACTICES.md
Configure the ApiClient with base URL, default headers, locale, retry policy, and circuit breaker settings. Use environment variables for dynamic configuration.
```typescript
// services/api.ts
import { ApiClient } from "bytekit";
export const api = new ApiClient({
baseUrl: import.meta.env.VITE_API_URL || "https://api.example.com",
defaultHeaders: {
"X-App-Version": "1.0.0",
},
locale: navigator.language.startsWith("es") ? "es" : "en",
retryPolicy: {
maxAttempts: 3,
initialDelayMs: 100,
backoffMultiplier: 2,
},
circuitBreaker: {
failureThreshold: 5,
resetTimeoutMs: 60000,
},
});
// services/users.service.ts
import { api } from "./api";
export class UsersService {
async getAll(filters?: UserFilters) {
return api.getList("/users", {
filters,
cache: true,
cacheTTL: 60000,
});
}
async getById(id: string) {
return api.get(`/users/${id}`, {
cache: true,
cacheTTL: 300000, // Cache user data for 5 minutes
});
}
async create(data: CreateUserDto) {
return api.post("/users", data);
}
async update(id: string, data: UpdateUserDto) {
return api.put(`/users/${id}`, data);
}
}
export const usersService = new UsersService();
```
--------------------------------
### Advanced Cache Management with RequestCache
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/RESILIENCE.md
For complex state management, use `RequestCache` directly to control caching behavior. Instantiate `RequestCache` with TTL and stale-while-revalidate options, then use `get` and `set` methods.
```typescript
import { RequestCache } from "bytekit";
const myCache = new RequestCache({
ttl: 10 * 60 * 1000,
staleWhileRevalidate: 2 * 60 * 1000
});
const api = new ApiClient({
baseUrl: "https://api.example.com",
});
async function getStats() {
const cached = myCache.get("/stats");
if (cached) return cached;
const fresh = await api.get("/stats");
myCache.set("/stats", fresh);
return fresh;
}
```
--------------------------------
### Generate API Docs with pnpm
Source: https://github.com/sebamar88/bytekit/blob/main/docs/README.md
Use pnpm commands to generate, watch, and serve API documentation locally. Ensure you have the necessary scripts defined in your package.json.
```bash
pnpm run docs:generate
```
```bash
pnpm run docs:watch
```
```bash
pnpm run docs:serve
```
--------------------------------
### Implement Request Caching
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/codesandbox/react-basic/README.md
Enable caching for a GET request by setting 'cache' to true and specifying a 'cacheTTL' (Time To Live) in milliseconds. This reduces redundant network calls for frequently accessed data.
```typescript
const data = await api.get("/users", {
cache: true,
cacheTTL: 60000, // 1 minute
});
```
--------------------------------
### Integrating Bytekit with React Query
Source: https://github.com/sebamar88/bytekit/blob/main/examples/codesandbox/react/README.md
Demonstrates how to use Bytekit with React Query for efficient data fetching and caching. Requires `@tanstack/react-query`.
```jsx
import { useQuery } from "@tanstack/react-query";
import { createApiClient } from "bytekit";
const client = createApiClient({ baseUrl: "https://api.example.com" });
function useUser(id) {
return useQuery({
queryKey: ["user", id],
queryFn: () => client.get(`/users/${id}`),
});
}
```
--------------------------------
### Date Formatting and Relative Time Examples
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/README.md
Quickly format dates into 'YYYY-MM-DD' format and calculate relative time differences using DateUtils. This snippet also shows how to add days to a date.
```typescript
import { DateUtils } from "bytekit";
console.log(DateUtils.format(new Date(), "YYYY-MM-DD"));
console.log(DateUtils.timeAgo(new Date("2024-01-01")));
console.log(DateUtils.addDays(new Date(), 7));
```
--------------------------------
### Create Bytekit API Client in React
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/react.md
Initialize a Bytekit API client within a React component using `useState` for memoization. Configure base URL, timeout, and retry options.
```jsx
import { createApiClient } from "bytekit";
import { useState } from "react";
function App() {
const [client] = useState(() =>
createApiClient({
baseUrl: "https://api.example.com",
timeout: 5000,
retry: { maxRetries: 3 },
})
);
// Use client for requests
}
```
--------------------------------
### Structured Logging for API Errors
Source: https://github.com/sebamar88/bytekit/blob/main/docs/ERROR_HANDLING_COMPARISON.md
Log API errors in a structured format for monitoring. This example shows how to log specific details of an ApiError, including status, status text, endpoint, and error body.
```typescript
try {
await client.post("/endpoint", data);
} catch (error) {
if (error instanceof ApiError) {
// Log estructurado para monitoring
logger.error("API request failed", {
status: error.status,
statusText: error.statusText,
endpoint: "/endpoint",
errorBody: error.body,
timestamp: new Date().toISOString(),
});
// O serializa todo el error
logger.error("API request failed", JSON.parse(JSON.stringify(error)));
}
}
```
--------------------------------
### Structured Logging with ByteKit Logger
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/BEST_PRACTICES.md
Implement structured logging using createLogger for better monitoring. Configure log levels based on environment (e.g., 'info' for production, 'debug' for development). Log events with context and errors with stack traces.
```typescript
import { createLogger } from "bytekit";
const logger = createLogger({
namespace: "app",
level: import.meta.env.PROD ? "info" : "debug",
});
// Log with context
logger.info("User logged in", {
userId: user.id,
method: "oauth",
provider: "google",
timestamp: new Date().toISOString(),
});
// Log errors with stack traces
try {
await riskyOperation();
} catch (error) {
logger.error(
"Operation failed",
{
operation: "riskyOperation",
userId: currentUser.id,
},
error
);
}
```
--------------------------------
### Build and Test ApiClient Fix
Source: https://github.com/sebamar88/bytekit/blob/main/docs/RELEASE_NOTES_v1.0.3.md
Commands to compile the project, run a quick verification script, and execute all unit tests to ensure the ApiClient header fix is working correctly.
```bash
# Compilar el proyecto
pnpm build
# Ejecutar script de verificación rápida
node verify-fix.js
# Ejecutar todos los tests
pnpm test
```
--------------------------------
### Use EnvManager for Cross-Platform Configuration
Source: https://github.com/sebamar88/bytekit/blob/main/docs/guides/GETTING_STARTED.md
Utilize EnvManager to safely access environment variables across different platforms (Node.js and Vite/Browser). Provides a unified way to get configuration values and check environment status.
```typescript
import { ApiClient, EnvManager } from "bytekit";
const env = new EnvManager();
const api = new ApiClient({
baseUrl: env.get("API_URL") || "https://api.production.com",
locale: env.get("APP_LOCALE") || "en"
});
// Check environment properties
if (env.isProd()) {
console.log("Running in production mode");
}
```
--------------------------------
### Implement Request Deduplication and Caching
Source: https://github.com/sebamar88/bytekit/blob/main/docs/CONTEXT7.md
Enhance `ApiClient` with `requestCache` and `requestDeduplicator` to avoid redundant requests. Caching stores responses for identical GET requests, while deduplication shares pending promises for identical in-flight requests.
```typescript
const client = new ApiClient({
baseUrl: "https://api.service.local",
requestCache: { ttlMs: 60_000 },
requestDeduplicator: true,
});
const [first, second] = await Promise.all([
client.get("/stats"),
client.get("/stats"),
]);
```
--------------------------------
### summary()
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/Profiler.md
Returns a summary of all profiling sessions.
```APIDOC
## summary()
### Description
Returns a summary of all profiling sessions.
### Returns
- **Record | Record>** - An object containing the profiling summary.
```
--------------------------------
### Create API Client in Svelte
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/svelte.md
Initialize a Bytekit API client within a Svelte component's script section. Configure base URL, timeout, and retry options.
```svelte
```
--------------------------------
### Constructor
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/classes/ErrorBoundary.md
Initializes a new instance of the ErrorBoundary class.
```APIDOC
## Constructor
### Description
Initializes a new instance of the ErrorBoundary class.
### Signature
```typescript
new ErrorBoundary(config?: ErrorBoundaryConfig)
```
### Parameters
#### config
- **config** (`ErrorBoundaryConfig`) - Optional - Configuration object for the ErrorBoundary.
### Returns
- `ErrorBoundary` - An instance of the ErrorBoundary class.
```
--------------------------------
### Performance Profiling with Profiler and withTiming
Source: https://github.com/sebamar88/bytekit/blob/main/docs/examples/README.md
The Profiler class enables manual performance timing by starting and ending named operations. For automatic timing of asynchronous functions, use the withTiming utility. Metrics like count, total time, average, min, and max are collected.
```typescript
import { Profiler, withTiming } from "bytekit";
const profiler = new Profiler({ namespace: "api" });
// Manual timing
profiler.start("fetchUsers");
await api.get("/users");
profiler.end("fetchUsers");
// Automatic timing
const result = await withTiming("processData", async () => {
return await heavyComputation();
});
// Get metrics
const metrics = profiler.getMetrics();
console.log(metrics.fetchUsers);
// { count: 5, total: 1234, avg: 246.8, min: 180, max: 340 }
```
--------------------------------
### WebSocketOptions
Source: https://github.com/sebamar88/bytekit/blob/main/docs/api/interfaces/WebSocketOptions.md
Configuration options for WebSocket connections.
```APIDOC
## Interface: WebSocketOptions
### Description
Defines the configuration options for WebSocket connections.
### Properties
#### reconnect
- **Type**: `boolean`
- **Optional**: Yes
- **Description**: Enables or disables automatic reconnection.
#### maxReconnectAttempts
- **Type**: `number`
- **Optional**: Yes
- **Description**: The maximum number of times to attempt reconnection.
#### reconnectDelayMs
- **Type**: `number`
- **Optional**: Yes
- **Description**: The delay in milliseconds between reconnection attempts.
#### heartbeatIntervalMs
- **Type**: `number`
- **Optional**: Yes
- **Description**: The interval in milliseconds for sending heartbeat messages to keep the connection alive.
#### messageTimeout
- **Type**: `number`
- **Optional**: Yes
- **Description**: The timeout in milliseconds for receiving a message before considering the connection stalled.
```