Latest Threat Research:SANDWORM_MODE: Shai-Hulud-Style npm Worm Hijacks CI Workflows and Poisons AI Toolchains.Details
Socket
Book a DemoInstallSign in
Socket

@blimu/fetch

Package Overview
Dependencies
Maintainers
1
Versions
6
Alerts
File Explorer

Advanced tools

Socket logo

Install Socket

Detect and block malicious and high-risk dependencies

Install

@blimu/fetch - npm Package Compare versions

Comparing version
0.2.0
to
0.3.0
+7
-9
dist/index.cjs

@@ -689,8 +689,6 @@ "use strict";

addAuthStrategy(strategy) {
if (!this.cfg.auth) {
this.cfg.auth = {
strategies: []
};
if (!this.cfg.authStrategies) {
this.cfg.authStrategies = [];
}
this.cfg.auth.strategies.push(strategy);
this.cfg.authStrategies.push(strategy);
}

@@ -701,4 +699,4 @@ /**

clearAuthStrategies() {
if (this.cfg.auth) {
this.cfg.auth.strategies = [];
if (this.cfg.authStrategies) {
this.cfg.authStrategies = [];
}

@@ -1081,6 +1079,6 @@ }

async applyAuthentication(headers, url) {
if (!this.cfg.auth?.strategies) {
if (!this.cfg.authStrategies) {
return;
}
for (const strategy of this.cfg.auth.strategies) {
for (const strategy of this.cfg.authStrategies) {
await this.applyAuthStrategy(strategy, headers, url);

@@ -1087,0 +1085,0 @@ }

@@ -218,3 +218,3 @@ /**

interface BearerAuthStrategy {
type: "bearer";
type: 'bearer';
token: string | (() => string | undefined | Promise<string | undefined>);

@@ -227,3 +227,3 @@ headerName?: string;

interface BasicAuthStrategy {
type: "basic";
type: 'basic';
username: string;

@@ -236,5 +236,5 @@ password: string;

interface ApiKeyAuthStrategy {
type: "apiKey";
type: 'apiKey';
key: string | (() => string | undefined | Promise<string | undefined>);
location: "header" | "query" | "cookie";
location: 'header' | 'query' | 'cookie';
name: string;

@@ -246,3 +246,3 @@ }

interface CustomAuthStrategy {
type: "custom";
type: 'custom';
apply: (headers: Headers, url: URL) => void | Promise<void>;

@@ -254,5 +254,2 @@ }

type AuthStrategy = BearerAuthStrategy | BasicAuthStrategy | ApiKeyAuthStrategy | CustomAuthStrategy;
interface AuthConfig {
strategies: AuthStrategy[];
}
/**

@@ -283,5 +280,5 @@ * Main configuration interface for FetchClient

/**
* Authentication configuration
* Authentication strategies
*/
auth?: AuthConfig;
authStrategies?: AuthStrategy[];
/**

@@ -294,8 +291,13 @@ * Custom fetch implementation (useful for polyfills or testing)

*/
credentials?: RequestInit["credentials"];
credentials?: RequestInit['credentials'];
}
/**
* Body type that can be serialized by the fetch client
* Includes standard BodyInit types plus plain objects/arrays that will be JSON serialized
*/
type SerializableBody = RequestInit['body'] | Record<string, any> | any[] | null | undefined;
/**
* Request options for a single request
*/
interface RequestOptions extends RequestInit {
interface RequestOptions extends Omit<RequestInit, 'body'> {
/**

@@ -313,2 +315,6 @@ * Request path (will be appended to baseURL)

query?: Record<string, any>;
/**
* Request body - can be BodyInit, plain object/array (will be JSON serialized), or null/undefined
*/
body?: SerializableBody;
}

@@ -514,2 +520,2 @@ /**

export { type AfterRequestHookContext, type AfterResponseHookContext, type AfterRetryHookContext, type ApiKeyAuthStrategy, type AuthConfig, type AuthStrategy, BadGatewayError, BadRequestError, type BaseHookContext, type BasicAuthStrategy, type BearerAuthStrategy, type BeforeRequestHookContext, type BeforeRetryHookContext, ClientError, ConflictError, type CustomAuthStrategy, FetchClient, type FetchClientConfig, FetchError, ForbiddenError, GatewayTimeoutError, type Hook, type HookContext, HookRegistry, type HookStage, type HooksConfig, InternalServerError, MethodNotAllowedError, NotFoundError, type OnErrorHookContext, type OnStreamChunkHookContext, type OnStreamEndHookContext, type OnStreamStartHookContext, type OnTimeoutHookContext, type RequestOptions, type RetryConfig, type RetryStrategyFunction, ServerError, ServiceUnavailableError, type StreamingFormat, type StreamingRequestOptions, TooManyRequestsError, UnauthorizedError, UnprocessableEntityError, buildUrl, calculateRetryDelay, createFetchError, encodeBase64, exponentialStrategy, getContentType, getFetchErrorMessage, getRetryStrategy, isAbortControllerAvailable, isBrowser, isFetchAvailable, isNode, isSuccessResponse, linearStrategy, parseChunkedStream, parseNDJSONStream, parseResponse, parseSSEStream, serializeBody, serializeQueryParams };
export { type AfterRequestHookContext, type AfterResponseHookContext, type AfterRetryHookContext, type ApiKeyAuthStrategy, type AuthStrategy, BadGatewayError, BadRequestError, type BaseHookContext, type BasicAuthStrategy, type BearerAuthStrategy, type BeforeRequestHookContext, type BeforeRetryHookContext, ClientError, ConflictError, type CustomAuthStrategy, FetchClient, type FetchClientConfig, FetchError, ForbiddenError, GatewayTimeoutError, type Hook, type HookContext, HookRegistry, type HookStage, type HooksConfig, InternalServerError, MethodNotAllowedError, NotFoundError, type OnErrorHookContext, type OnStreamChunkHookContext, type OnStreamEndHookContext, type OnStreamStartHookContext, type OnTimeoutHookContext, type RequestOptions, type RetryConfig, type RetryStrategyFunction, type SerializableBody, ServerError, ServiceUnavailableError, type StreamingFormat, type StreamingRequestOptions, TooManyRequestsError, UnauthorizedError, UnprocessableEntityError, buildUrl, calculateRetryDelay, createFetchError, encodeBase64, exponentialStrategy, getContentType, getFetchErrorMessage, getRetryStrategy, isAbortControllerAvailable, isBrowser, isFetchAvailable, isNode, isSuccessResponse, linearStrategy, parseChunkedStream, parseNDJSONStream, parseResponse, parseSSEStream, serializeBody, serializeQueryParams };

@@ -218,3 +218,3 @@ /**

interface BearerAuthStrategy {
type: "bearer";
type: 'bearer';
token: string | (() => string | undefined | Promise<string | undefined>);

@@ -227,3 +227,3 @@ headerName?: string;

interface BasicAuthStrategy {
type: "basic";
type: 'basic';
username: string;

@@ -236,5 +236,5 @@ password: string;

interface ApiKeyAuthStrategy {
type: "apiKey";
type: 'apiKey';
key: string | (() => string | undefined | Promise<string | undefined>);
location: "header" | "query" | "cookie";
location: 'header' | 'query' | 'cookie';
name: string;

@@ -246,3 +246,3 @@ }

interface CustomAuthStrategy {
type: "custom";
type: 'custom';
apply: (headers: Headers, url: URL) => void | Promise<void>;

@@ -254,5 +254,2 @@ }

type AuthStrategy = BearerAuthStrategy | BasicAuthStrategy | ApiKeyAuthStrategy | CustomAuthStrategy;
interface AuthConfig {
strategies: AuthStrategy[];
}
/**

@@ -283,5 +280,5 @@ * Main configuration interface for FetchClient

/**
* Authentication configuration
* Authentication strategies
*/
auth?: AuthConfig;
authStrategies?: AuthStrategy[];
/**

@@ -294,8 +291,13 @@ * Custom fetch implementation (useful for polyfills or testing)

*/
credentials?: RequestInit["credentials"];
credentials?: RequestInit['credentials'];
}
/**
* Body type that can be serialized by the fetch client
* Includes standard BodyInit types plus plain objects/arrays that will be JSON serialized
*/
type SerializableBody = RequestInit['body'] | Record<string, any> | any[] | null | undefined;
/**
* Request options for a single request
*/
interface RequestOptions extends RequestInit {
interface RequestOptions extends Omit<RequestInit, 'body'> {
/**

@@ -313,2 +315,6 @@ * Request path (will be appended to baseURL)

query?: Record<string, any>;
/**
* Request body - can be BodyInit, plain object/array (will be JSON serialized), or null/undefined
*/
body?: SerializableBody;
}

@@ -514,2 +520,2 @@ /**

export { type AfterRequestHookContext, type AfterResponseHookContext, type AfterRetryHookContext, type ApiKeyAuthStrategy, type AuthConfig, type AuthStrategy, BadGatewayError, BadRequestError, type BaseHookContext, type BasicAuthStrategy, type BearerAuthStrategy, type BeforeRequestHookContext, type BeforeRetryHookContext, ClientError, ConflictError, type CustomAuthStrategy, FetchClient, type FetchClientConfig, FetchError, ForbiddenError, GatewayTimeoutError, type Hook, type HookContext, HookRegistry, type HookStage, type HooksConfig, InternalServerError, MethodNotAllowedError, NotFoundError, type OnErrorHookContext, type OnStreamChunkHookContext, type OnStreamEndHookContext, type OnStreamStartHookContext, type OnTimeoutHookContext, type RequestOptions, type RetryConfig, type RetryStrategyFunction, ServerError, ServiceUnavailableError, type StreamingFormat, type StreamingRequestOptions, TooManyRequestsError, UnauthorizedError, UnprocessableEntityError, buildUrl, calculateRetryDelay, createFetchError, encodeBase64, exponentialStrategy, getContentType, getFetchErrorMessage, getRetryStrategy, isAbortControllerAvailable, isBrowser, isFetchAvailable, isNode, isSuccessResponse, linearStrategy, parseChunkedStream, parseNDJSONStream, parseResponse, parseSSEStream, serializeBody, serializeQueryParams };
export { type AfterRequestHookContext, type AfterResponseHookContext, type AfterRetryHookContext, type ApiKeyAuthStrategy, type AuthStrategy, BadGatewayError, BadRequestError, type BaseHookContext, type BasicAuthStrategy, type BearerAuthStrategy, type BeforeRequestHookContext, type BeforeRetryHookContext, ClientError, ConflictError, type CustomAuthStrategy, FetchClient, type FetchClientConfig, FetchError, ForbiddenError, GatewayTimeoutError, type Hook, type HookContext, HookRegistry, type HookStage, type HooksConfig, InternalServerError, MethodNotAllowedError, NotFoundError, type OnErrorHookContext, type OnStreamChunkHookContext, type OnStreamEndHookContext, type OnStreamStartHookContext, type OnTimeoutHookContext, type RequestOptions, type RetryConfig, type RetryStrategyFunction, type SerializableBody, ServerError, ServiceUnavailableError, type StreamingFormat, type StreamingRequestOptions, TooManyRequestsError, UnauthorizedError, UnprocessableEntityError, buildUrl, calculateRetryDelay, createFetchError, encodeBase64, exponentialStrategy, getContentType, getFetchErrorMessage, getRetryStrategy, isAbortControllerAvailable, isBrowser, isFetchAvailable, isNode, isSuccessResponse, linearStrategy, parseChunkedStream, parseNDJSONStream, parseResponse, parseSSEStream, serializeBody, serializeQueryParams };

@@ -629,8 +629,6 @@ var __defProp = Object.defineProperty;

addAuthStrategy(strategy) {
if (!this.cfg.auth) {
this.cfg.auth = {
strategies: []
};
if (!this.cfg.authStrategies) {
this.cfg.authStrategies = [];
}
this.cfg.auth.strategies.push(strategy);
this.cfg.authStrategies.push(strategy);
}

@@ -641,4 +639,4 @@ /**

clearAuthStrategies() {
if (this.cfg.auth) {
this.cfg.auth.strategies = [];
if (this.cfg.authStrategies) {
this.cfg.authStrategies = [];
}

@@ -1021,6 +1019,6 @@ }

async applyAuthentication(headers, url) {
if (!this.cfg.auth?.strategies) {
if (!this.cfg.authStrategies) {
return;
}
for (const strategy of this.cfg.auth.strategies) {
for (const strategy of this.cfg.authStrategies) {
await this.applyAuthStrategy(strategy, headers, url);

@@ -1027,0 +1025,0 @@ }

{
"name": "@blimu/fetch",
"version": "0.2.0",
"version": "0.3.0",
"description": "Universal HTTP fetch client with hooks, retries, and streaming support for browser and Node.js",

@@ -5,0 +5,0 @@ "type": "module",

+119
-137

@@ -28,8 +28,8 @@ # @blimu/fetch

```typescript
import { FetchClient } from "@blimu/fetch";
import { FetchClient } from '@blimu/fetch';
const client = new FetchClient({
baseURL: "https://api.example.com",
baseURL: 'https://api.example.com',
headers: {
"Content-Type": "application/json",
'Content-Type': 'application/json',
},

@@ -40,4 +40,4 @@ });

const data = await client.request({
path: "/users",
method: "GET",
path: '/users',
method: 'GET',
});

@@ -52,8 +52,8 @@ ```

const client = new FetchClient({
baseURL: "https://api.example.com",
baseURL: 'https://api.example.com',
headers: {
"X-Custom-Header": "value",
'X-Custom-Header': 'value',
},
timeoutMs: 5000,
credentials: "include",
credentials: 'include',
});

@@ -64,3 +64,3 @@ ```

Authentication is configured using the `auth` option with strategies:
Authentication is configured using the `authStrategies` option:

@@ -70,11 +70,9 @@ ```typescript

const client = new FetchClient({
baseURL: "https://api.example.com",
auth: {
strategies: [
{
type: "bearer",
token: "your-token-here",
},
],
},
baseURL: 'https://api.example.com',
authStrategies: [
{
type: 'bearer',
token: 'your-token-here',
},
],
});

@@ -84,15 +82,13 @@

const client = new FetchClient({
baseURL: "https://api.example.com",
auth: {
strategies: [
{
type: "bearer",
token: async () => {
// Fetch or refresh token
return await getToken();
},
headerName: "Authorization", // Optional, defaults to "Authorization"
baseURL: 'https://api.example.com',
authStrategies: [
{
type: 'bearer',
token: async () => {
// Fetch or refresh token
return await getToken();
},
],
},
headerName: 'Authorization', // Optional, defaults to "Authorization"
},
],
});

@@ -102,12 +98,10 @@

const client = new FetchClient({
baseURL: "https://api.example.com",
auth: {
strategies: [
{
type: "basic",
username: "user",
password: "pass",
},
],
},
baseURL: 'https://api.example.com',
authStrategies: [
{
type: 'basic',
username: 'user',
password: 'pass',
},
],
});

@@ -117,13 +111,11 @@

const client = new FetchClient({
baseURL: "https://api.example.com",
auth: {
strategies: [
{
type: "apiKey",
key: "your-api-key",
location: "header",
name: "X-API-Key",
},
],
},
baseURL: 'https://api.example.com',
authStrategies: [
{
type: 'apiKey',
key: 'your-api-key',
location: 'header',
name: 'X-API-Key',
},
],
});

@@ -133,13 +125,11 @@

const client = new FetchClient({
baseURL: "https://api.example.com",
auth: {
strategies: [
{
type: "apiKey",
key: "your-api-key",
location: "query",
name: "api_key",
},
],
},
baseURL: 'https://api.example.com',
authStrategies: [
{
type: 'apiKey',
key: 'your-api-key',
location: 'query',
name: 'api_key',
},
],
});

@@ -149,17 +139,15 @@

const client = new FetchClient({
baseURL: "https://api.example.com",
auth: {
strategies: [
{
type: "bearer",
token: "token",
},
{
type: "apiKey",
key: "api-key",
location: "header",
name: "X-API-Key",
},
],
},
baseURL: 'https://api.example.com',
authStrategies: [
{
type: 'bearer',
token: 'token',
},
{
type: 'apiKey',
key: 'api-key',
location: 'header',
name: 'X-API-Key',
},
],
});

@@ -169,15 +157,13 @@

const client = new FetchClient({
baseURL: "https://api.example.com",
auth: {
strategies: [
{
type: "custom",
apply: async (headers, url) => {
// Custom authentication logic
const token = await getCustomToken();
headers.set("X-Custom-Auth", token);
},
baseURL: 'https://api.example.com',
authStrategies: [
{
type: 'custom',
apply: async (headers, url) => {
// Custom authentication logic
const token = await getCustomToken();
headers.set('X-Custom-Auth', token);
},
],
},
},
],
});

@@ -207,3 +193,3 @@ ```

const client = new FetchClient({
baseURL: "https://api.example.com",
baseURL: 'https://api.example.com',
hooks: {

@@ -213,3 +199,3 @@ beforeRequest: [

// Add custom header
ctx.init.headers.set("X-Request-ID", generateId());
ctx.init.headers.set('X-Request-ID', generateId());
},

@@ -219,3 +205,3 @@ async (ctx) => {

const token = await refreshToken();
ctx.init.headers.set("Authorization", `Bearer ${token}`);
ctx.init.headers.set('Authorization', `Bearer ${token}`);
},

@@ -226,3 +212,3 @@ ],

// Log response
console.log("Response:", ctx.data);
console.log('Response:', ctx.data);
},

@@ -233,3 +219,3 @@ ],

// Log errors
console.error("Request failed:", ctx.error);
console.error('Request failed:', ctx.error);
},

@@ -244,7 +230,7 @@ ],

```typescript
const client = new FetchClient({ baseURL: "https://api.example.com" });
const client = new FetchClient({ baseURL: 'https://api.example.com' });
// Register a hook
client.useHook("beforeRequest", (ctx) => {
console.log("Making request to:", ctx.url);
client.useHook('beforeRequest', (ctx) => {
console.log('Making request to:', ctx.url);
});

@@ -254,7 +240,7 @@

const hook = (ctx) => console.log(ctx);
client.useHook("beforeRequest", hook);
client.removeHook("beforeRequest", hook);
client.useHook('beforeRequest', hook);
client.removeHook('beforeRequest', hook);
// Clear all hooks for a stage
client.clearHooks("beforeRequest");
client.clearHooks('beforeRequest');

@@ -271,6 +257,6 @@ // Clear all hooks

const client = new FetchClient({
baseURL: "https://api.example.com",
baseURL: 'https://api.example.com',
retry: {
retries: 3,
strategy: "exponential",
strategy: 'exponential',
backoffMs: 100,

@@ -286,6 +272,6 @@ retryOn: [429, 500, 502, 503, 504],

const client = new FetchClient({
baseURL: "https://api.example.com",
baseURL: 'https://api.example.com',
retry: {
retries: 3,
strategy: "linear",
strategy: 'linear',
backoffMs: 200,

@@ -301,3 +287,3 @@ retryOn: [500, 502, 503],

const client = new FetchClient({
baseURL: "https://api.example.com",
baseURL: 'https://api.example.com',
retry: {

@@ -324,8 +310,8 @@ retries: 3,

for await (const chunk of client.requestStream({
path: "/events",
method: "GET",
contentType: "text/event-stream",
streamingFormat: "sse",
path: '/events',
method: 'GET',
contentType: 'text/event-stream',
streamingFormat: 'sse',
})) {
console.log("Event:", chunk);
console.log('Event:', chunk);
}

@@ -338,8 +324,8 @@ ```

for await (const item of client.requestStream({
path: "/items",
method: "GET",
contentType: "application/x-ndjson",
streamingFormat: "ndjson",
path: '/items',
method: 'GET',
contentType: 'application/x-ndjson',
streamingFormat: 'ndjson',
})) {
console.log("Item:", item);
console.log('Item:', item);
}

@@ -352,8 +338,8 @@ ```

for await (const chunk of client.requestStream({
path: "/stream",
method: "GET",
contentType: "application/octet-stream",
streamingFormat: "chunked",
path: '/stream',
method: 'GET',
contentType: 'application/octet-stream',
streamingFormat: 'chunked',
})) {
console.log("Chunk:", chunk);
console.log('Chunk:', chunk);
}

@@ -396,19 +382,19 @@ ```

ServerError,
} from "@blimu/fetch";
} from '@blimu/fetch';
try {
await client.request({ path: "/users/123", method: "GET" });
await client.request({ path: '/users/123', method: 'GET' });
} catch (error) {
if (error instanceof NotFoundError) {
// Handle 404
console.log("User not found");
console.log('User not found');
} else if (error instanceof UnauthorizedError) {
// Handle 401
console.log("Unauthorized - refresh token");
console.log('Unauthorized - refresh token');
} else if (error instanceof ServerError) {
// Handle any 5xx
console.log("Server error:", error.status);
console.log('Server error:', error.status);
} else {
// Handle other errors
console.error("Unexpected error:", error);
console.error('Unexpected error:', error);
}

@@ -425,6 +411,6 @@ }

```typescript
import { FetchClient } from "@blimu/fetch";
import { FetchClient } from '@blimu/fetch';
const client = new FetchClient({
baseURL: "https://api.example.com",
baseURL: 'https://api.example.com',
});

@@ -440,7 +426,7 @@ ```

```typescript
import { FetchClient } from "@blimu/fetch";
import { fetch } from "undici"; // or "node-fetch"
import { FetchClient } from '@blimu/fetch';
import { fetch } from 'undici'; // or "node-fetch"
const client = new FetchClient({
baseURL: "https://api.example.com",
baseURL: 'https://api.example.com',
fetch, // Provide custom fetch

@@ -479,3 +465,3 @@ });

hooks?: HooksConfig;
auth?: AuthConfig;
authStrategies?: AuthStrategy[];
fetch?: typeof fetch;

@@ -485,6 +471,2 @@ credentials?: RequestCredentials;

interface AuthConfig {
strategies: AuthStrategy[];
}
type AuthStrategy =

@@ -504,3 +486,3 @@ | BearerAuthStrategy

contentType: string;
streamingFormat?: "sse" | "ndjson" | "chunked";
streamingFormat?: 'sse' | 'ndjson' | 'chunked';
}

@@ -507,0 +489,0 @@ ```

Sorry, the diff of this file is too big to display

Sorry, the diff of this file is too big to display