@tahanabavi/typefetch 1.5.3 → 1.5.6

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -164,7 +164,7 @@ z.object({
164
164
  path: z.object({}).optional(),
165
165
  query: z.object({}).optional(),
166
166
  body: z.any().optional(),
167
- headers: z.record(z.string()).optional(),
167
+ headers: z.record(z.string(), z.string()).optional(),
168
168
  });
169
169
  ```
170
170
 
@@ -195,7 +195,7 @@ const contracts = {
195
195
  body: z.object({
196
196
  name: z.string(),
197
197
  }),
198
- headers: z.record(z.string()).optional(),
198
+ headers: z.record(z.string(), z.string()).optional(),
199
199
  }),
200
200
  response: z.object({
201
201
  id: z.string(),
@@ -261,7 +261,7 @@ const updateUserRequest = makeRequestSchema<
261
261
  body: z.object({
262
262
  name: z.string(),
263
263
  }),
264
- headers: z.record(z.string()).optional(),
264
+ headers: z.record(z.string(), z.string()).optional(),
265
265
  });
266
266
  ```
267
267
 
package/dist/index.d.mts CHANGED
@@ -393,26 +393,17 @@ interface EncryptionOptions {
393
393
  declare function processDeep<T = unknown>(data: unknown, map: DeepEncryptionMap | null | undefined, defaultMethod: EncryptionMethod, transform: (value: unknown, method: EncryptionMethod) => Promise<unknown>): Promise<T>;
394
394
  declare const encryptionMiddleware: Middleware<z.ZodTypeAny, z.ZodTypeAny, EncryptionOptions>;
395
395
 
396
- declare const makeRequestSchema: <TPath extends z.ZodRawShape = {}, TQuery extends z.ZodRawShape = {}, TBody extends z.ZodTypeAny = z.ZodUndefined>() => (defs?: {
396
+ type OptionalUndefinedBody<T extends z.ZodTypeAny> = T extends z.ZodUndefined ? z.ZodOptional<T> : T;
397
+ declare const makeRequestSchema: <TPath extends z.ZodRawShape = {}, TQuery extends z.ZodRawShape = {}, TBody extends z.ZodTypeAny = z.ZodUndefined, THeaders extends z.ZodTypeAny = z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>() => (defs?: {
397
398
  path?: z.ZodObject<TPath>;
398
399
  query?: z.ZodObject<TQuery>;
399
400
  body?: TBody;
400
- headers?: z.ZodTypeAny;
401
+ headers?: THeaders;
401
402
  }) => z.ZodObject<{
402
- path: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TPath, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TPath>, any> extends infer T ? { [k in keyof T]: T[k]; } : never, z.baseObjectInputType<TPath> extends infer T_1 ? { [k_1 in keyof T_1]: T_1[k_1]; } : never>>;
403
- query: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TQuery, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TQuery>, any> extends infer T_2 ? { [k_2 in keyof T_2]: T_2[k_2]; } : never, z.baseObjectInputType<TQuery> extends infer T_3 ? { [k_3 in keyof T_3]: T_3[k_3]; } : never>>;
404
- body: TBody | z.ZodUndefined;
405
- headers: any;
406
- }, "strip", z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
407
- path: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TPath, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TPath>, any> extends infer T_5 ? { [k in keyof T_5]: T_5[k]; } : never, z.baseObjectInputType<TPath> extends infer T_6 ? { [k_1 in keyof T_6]: T_6[k_1]; } : never>>;
408
- query: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TQuery, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TQuery>, any> extends infer T_7 ? { [k_2 in keyof T_7]: T_7[k_2]; } : never, z.baseObjectInputType<TQuery> extends infer T_8 ? { [k_3 in keyof T_8]: T_8[k_3]; } : never>>;
409
- body: TBody | z.ZodUndefined;
410
- headers: any;
411
- }>, any> extends infer T_4 ? { [k_4 in keyof T_4]: T_4[k_4]; } : never, z.baseObjectInputType<{
412
- path: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TPath, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TPath>, any> extends infer T_10 ? { [k in keyof T_10]: T_10[k]; } : never, z.baseObjectInputType<TPath> extends infer T_11 ? { [k_1 in keyof T_11]: T_11[k_1]; } : never>>;
413
- query: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TQuery, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TQuery>, any> extends infer T_12 ? { [k_2 in keyof T_12]: T_12[k_2]; } : never, z.baseObjectInputType<TQuery> extends infer T_13 ? { [k_3 in keyof T_13]: T_13[k_3]; } : never>>;
414
- body: TBody | z.ZodUndefined;
415
- headers: any;
416
- }> extends infer T_9 ? { [k_5 in keyof T_9]: T_9[k_5]; } : never>;
403
+ path: z.ZodOptional<z.ZodObject<TPath, z.core.$strip>>;
404
+ query: z.ZodOptional<z.ZodObject<TQuery, z.core.$strip>>;
405
+ body: OptionalUndefinedBody<TBody>;
406
+ headers: THeaders;
407
+ }, z.core.$strip>;
417
408
 
418
409
  export { ApiClient, type AuthOptions, type CacheOptions, type Contracts, type DeepEncryptionMap, type EncryptionConfig, type EncryptionMethod, type EncryptionOptions, type EndpointDef, type EndpointDefZ, type EndpointMethods, type ErrorLike, type LoggingOptions, type Method, type Middleware, type MiddlewareContext, type MiddlewareNext, type RequestOptions, type RequestParts, type RequestSchema, type ResponseSchema, type RetryOptions, RichError, type TokenProvider, authMiddleware, cacheMiddleware, encryptionMiddleware, loggingMiddleware, makeRequestSchema, processDeep, retryMiddleware };
package/dist/index.d.ts CHANGED
@@ -393,26 +393,17 @@ interface EncryptionOptions {
393
393
  declare function processDeep<T = unknown>(data: unknown, map: DeepEncryptionMap | null | undefined, defaultMethod: EncryptionMethod, transform: (value: unknown, method: EncryptionMethod) => Promise<unknown>): Promise<T>;
394
394
  declare const encryptionMiddleware: Middleware<z.ZodTypeAny, z.ZodTypeAny, EncryptionOptions>;
395
395
 
396
- declare const makeRequestSchema: <TPath extends z.ZodRawShape = {}, TQuery extends z.ZodRawShape = {}, TBody extends z.ZodTypeAny = z.ZodUndefined>() => (defs?: {
396
+ type OptionalUndefinedBody<T extends z.ZodTypeAny> = T extends z.ZodUndefined ? z.ZodOptional<T> : T;
397
+ declare const makeRequestSchema: <TPath extends z.ZodRawShape = {}, TQuery extends z.ZodRawShape = {}, TBody extends z.ZodTypeAny = z.ZodUndefined, THeaders extends z.ZodTypeAny = z.ZodOptional<z.ZodRecord<z.ZodString, z.ZodString>>>() => (defs?: {
397
398
  path?: z.ZodObject<TPath>;
398
399
  query?: z.ZodObject<TQuery>;
399
400
  body?: TBody;
400
- headers?: z.ZodTypeAny;
401
+ headers?: THeaders;
401
402
  }) => z.ZodObject<{
402
- path: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TPath, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TPath>, any> extends infer T ? { [k in keyof T]: T[k]; } : never, z.baseObjectInputType<TPath> extends infer T_1 ? { [k_1 in keyof T_1]: T_1[k_1]; } : never>>;
403
- query: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TQuery, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TQuery>, any> extends infer T_2 ? { [k_2 in keyof T_2]: T_2[k_2]; } : never, z.baseObjectInputType<TQuery> extends infer T_3 ? { [k_3 in keyof T_3]: T_3[k_3]; } : never>>;
404
- body: TBody | z.ZodUndefined;
405
- headers: any;
406
- }, "strip", z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<{
407
- path: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TPath, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TPath>, any> extends infer T_5 ? { [k in keyof T_5]: T_5[k]; } : never, z.baseObjectInputType<TPath> extends infer T_6 ? { [k_1 in keyof T_6]: T_6[k_1]; } : never>>;
408
- query: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TQuery, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TQuery>, any> extends infer T_7 ? { [k_2 in keyof T_7]: T_7[k_2]; } : never, z.baseObjectInputType<TQuery> extends infer T_8 ? { [k_3 in keyof T_8]: T_8[k_3]; } : never>>;
409
- body: TBody | z.ZodUndefined;
410
- headers: any;
411
- }>, any> extends infer T_4 ? { [k_4 in keyof T_4]: T_4[k_4]; } : never, z.baseObjectInputType<{
412
- path: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TPath, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TPath>, any> extends infer T_10 ? { [k in keyof T_10]: T_10[k]; } : never, z.baseObjectInputType<TPath> extends infer T_11 ? { [k_1 in keyof T_11]: T_11[k_1]; } : never>>;
413
- query: z.ZodOptional<z.ZodObject<{}, "strip", z.ZodTypeAny, {}, {}>> | z.ZodOptional<z.ZodObject<TQuery, z.UnknownKeysParam, z.ZodTypeAny, z.objectUtil.addQuestionMarks<z.baseObjectOutputType<TQuery>, any> extends infer T_12 ? { [k_2 in keyof T_12]: T_12[k_2]; } : never, z.baseObjectInputType<TQuery> extends infer T_13 ? { [k_3 in keyof T_13]: T_13[k_3]; } : never>>;
414
- body: TBody | z.ZodUndefined;
415
- headers: any;
416
- }> extends infer T_9 ? { [k_5 in keyof T_9]: T_9[k_5]; } : never>;
403
+ path: z.ZodOptional<z.ZodObject<TPath, z.core.$strip>>;
404
+ query: z.ZodOptional<z.ZodObject<TQuery, z.core.$strip>>;
405
+ body: OptionalUndefinedBody<TBody>;
406
+ headers: THeaders;
407
+ }, z.core.$strip>;
417
408
 
418
409
  export { ApiClient, type AuthOptions, type CacheOptions, type Contracts, type DeepEncryptionMap, type EncryptionConfig, type EncryptionMethod, type EncryptionOptions, type EndpointDef, type EndpointDefZ, type EndpointMethods, type ErrorLike, type LoggingOptions, type Method, type Middleware, type MiddlewareContext, type MiddlewareNext, type RequestOptions, type RequestParts, type RequestSchema, type ResponseSchema, type RetryOptions, RichError, type TokenProvider, authMiddleware, cacheMiddleware, encryptionMiddleware, loggingMiddleware, makeRequestSchema, processDeep, retryMiddleware };
package/dist/index.js CHANGED
@@ -379,7 +379,7 @@ var ApiClient = class {
379
379
  if (err instanceof RichError) return err;
380
380
  if (err instanceof import_zod.z.ZodError) {
381
381
  return this.createError({
382
- message: `Validation error: ${err.errors.map((e) => e.message).join(", ")}`,
382
+ message: `Validation error: ${err.issues.map((e) => e.message).join(", ")}`,
383
383
  code: "VALIDATION_ERROR"
384
384
  });
385
385
  }
@@ -721,12 +721,19 @@ var encryptionMiddleware = async (ctx, next, options) => {
721
721
 
722
722
  // src/utils/make-request-schema.ts
723
723
  var import_zod2 = require("zod");
724
- var makeRequestSchema = () => (defs = {}) => import_zod2.z.object({
725
- path: (defs.path ?? import_zod2.z.object({})).optional(),
726
- query: (defs.query ?? import_zod2.z.object({})).optional(),
727
- body: defs.body ?? import_zod2.z.undefined(),
728
- headers: defs.headers ?? import_zod2.z.record(import_zod2.z.string()).optional()
729
- });
724
+ var makeRequestSchema = () => (defs = {}) => {
725
+ const pathSchema = defs.path ?? import_zod2.z.object({});
726
+ const querySchema = defs.query ?? import_zod2.z.object({});
727
+ const rawBodySchema = defs.body ?? import_zod2.z.undefined();
728
+ const bodySchema = defs.body ? rawBodySchema : rawBodySchema.optional();
729
+ const headersSchema = defs.headers ?? import_zod2.z.record(import_zod2.z.string(), import_zod2.z.string()).optional();
730
+ return import_zod2.z.object({
731
+ path: pathSchema.optional(),
732
+ query: querySchema.optional(),
733
+ body: bodySchema,
734
+ headers: headersSchema
735
+ });
736
+ };
730
737
  // Annotate the CommonJS export names for ESM import in node:
731
738
  0 && (module.exports = {
732
739
  ApiClient,
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/middlewares/logging.ts","../src/middlewares/retry.ts","../src/middlewares/auth.ts","../src/middlewares/cache.ts","../src/middlewares/encryption.ts","../src/utils/make-request-schema.ts"],"sourcesContent":["export * from \"./types\";\nexport * from \"./client\";\nexport * from \"./middlewares/logging\";\nexport * from \"./middlewares/retry\";\nexport * from \"./middlewares/auth\";\nexport * from \"./middlewares/cache\";\nexport * from \"./middlewares/encryption\";\nexport * from \"./utils/make-request-schema\";\n","import { z } from \"zod\";\nimport {\n Contracts,\n EndpointDef,\n EndpointDefZ,\n Middleware,\n ErrorLike,\n EndpointMethods,\n TokenProvider,\n RequestOptions,\n MiddlewareContext,\n} from \"./types\";\n\nexport class RichError extends Error implements ErrorLike {\n status?: number;\n code?: string;\n title?: string;\n detail?: string;\n errors?: Record<string, string[]>;\n\n constructor(error: Partial<ErrorLike> & { message: string }) {\n super(error.message);\n Object.assign(this, error);\n }\n}\n\ntype ParsedRequestParts = {\n path?: Record<string, any>;\n query?: Record<string, any>;\n body?: any;\n headers: Record<string, string>;\n isStructured: boolean;\n};\n\nconst REQUEST_PART_KEYS = new Set([\n \"path\",\n \"query\",\n \"body\",\n \"headers\",\n \"header\",\n]);\n\nexport class ApiClient<C extends Contracts, E extends ErrorLike = RichError> {\n private middlewares: Array<{ fn: Middleware; options?: any }> = [];\n private errorHandler?: (error: E) => void;\n private responseTransform: (data: any) => any = (d) => d;\n private useMockData = false;\n private mockDelay = { min: 100, max: 1000 };\n private responseWrapper?: (successResponse: z.ZodTypeAny) => z.ZodTypeAny;\n private tokenProvider?: TokenProvider;\n\n private retryConfig?: {\n maxRetries: number;\n backoff: \"fixed\" | \"linear\" | \"exponential\";\n retryCondition?: (error: RichError, attempt: number) => boolean;\n };\n\n private _modules!: { [M in keyof C]: EndpointMethods<C[M]> };\n\n constructor(\n private config: {\n baseUrl: string;\n token?: string;\n tokenProvider?: TokenProvider;\n useMockData?: boolean;\n mockDelay?: { min: number; max: number };\n },\n private contracts: C,\n ) {\n this.useMockData = config.useMockData || false;\n this.mockDelay = config.mockDelay || { min: 100, max: 1000 };\n this.tokenProvider = config.tokenProvider;\n }\n\n init() {\n const modules = {} as { [M in keyof C]: EndpointMethods<C[M]> };\n\n for (const moduleName in this.contracts) {\n const module = this.contracts[moduleName];\n (modules as any)[moduleName] = {} as EndpointMethods<typeof module>;\n\n for (const endpointName in module) {\n const endpoint = module[endpointName] as EndpointDefZ;\n\n (modules as any)[moduleName][endpointName] = (\n input: any,\n options?: RequestOptions,\n ) => this.request(endpoint as any, input, options);\n }\n }\n\n this._modules = modules;\n }\n\n get modules() {\n return this._modules;\n }\n\n use<T>(middleware: Middleware<any, any, T>, options?: T) {\n this.middlewares.push({ fn: middleware, options });\n }\n\n onError(handler: (error: E) => void) {\n this.errorHandler = handler;\n }\n\n useResponseTransform(fn: (data: any) => any) {\n this.responseTransform = fn;\n }\n\n setRetryConfig(config: ApiClient<C>[\"retryConfig\"]) {\n this.retryConfig = config;\n }\n\n setTokenProvider(provider: TokenProvider) {\n this.tokenProvider = provider;\n }\n\n setMockMode(enabled: boolean, delay?: { min: number; max: number }) {\n this.useMockData = enabled;\n if (delay) this.mockDelay = delay;\n }\n\n setResponseWrapper(wrapper: (successResponse: z.ZodTypeAny) => z.ZodTypeAny) {\n this.responseWrapper = wrapper;\n }\n\n async getCurrentToken(): Promise<string | undefined> {\n if (this.tokenProvider) return await this.tokenProvider();\n return this.config.token;\n }\n\n private async request<TReq extends z.ZodTypeAny, TRes extends z.ZodTypeAny>(\n endpoint: EndpointDef<TReq, TRes>,\n input: z.infer<TReq>,\n options?: RequestOptions,\n ): Promise<z.infer<TRes>> {\n const parsedInput = endpoint.request.parse(input);\n\n if (this.useMockData && endpoint.mockData) {\n return this.handleMockRequest(endpoint);\n }\n\n const built = this.buildUrlAndBody(endpoint as EndpointDefZ, parsedInput);\n\n return this.performRequestLogic(\n endpoint,\n parsedInput,\n built.url,\n built.body,\n built.headers,\n built.parts,\n options,\n );\n }\n\n private async performRequestLogic<\n TReq extends z.ZodTypeAny,\n TRes extends z.ZodTypeAny,\n >(\n endpoint: EndpointDef<TReq, TRes>,\n parsedInput: z.infer<TReq>,\n url: string,\n body: BodyInit | undefined,\n requestHeaders: Record<string, string>,\n requestParts: ParsedRequestParts,\n options?: RequestOptions,\n ): Promise<z.infer<TRes>> {\n const headers: Record<string, string> = {};\n\n if (endpoint.bodyType !== \"form-data\") {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n const endpointHeaders =\n typeof endpoint.headers === \"function\"\n ? endpoint.headers(parsedInput)\n : endpoint.headers;\n\n Object.assign(\n headers,\n this.normalizeHeaders(endpointHeaders),\n requestHeaders,\n );\n\n if (endpoint.auth) {\n const token = await this.getCurrentToken();\n\n if (!token) {\n const error = this.createError({\n message: `Missing token for ${endpoint.path}`,\n status: 401,\n code: \"NO_TOKEN\",\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n\n const ctx = {\n url,\n init: { method: endpoint.method, headers, body } as RequestInit,\n endpoint: endpoint as never,\n request: {\n ...requestParts,\n rawInput: parsedInput,\n },\n } satisfies MiddlewareContext;\n\n let controller: AbortController | undefined;\n let timeoutId: any;\n\n if (options?.timeout) {\n controller = new AbortController();\n timeoutId = setTimeout(() => controller!.abort(), options.timeout);\n }\n\n if (options?.signal || controller) {\n ctx.init.signal = options?.signal || controller?.signal;\n }\n\n const runner = this.middlewares.reduceRight(\n (next, mw) => () => mw.fn(ctx, next, mw.options),\n () => fetch(ctx.url, ctx.init),\n );\n\n const execute = async () => {\n const res = await runner();\n const json = await res.json();\n let responseData = json;\n\n if (this.responseWrapper) {\n const wrappedSchema = this.responseWrapper(endpoint.response);\n const parsedWrapped = wrappedSchema.parse(json);\n\n if (parsedWrapped.success === false) {\n const error = this.createError({\n message:\n parsedWrapped.message || parsedWrapped.error || \"Request failed\",\n status: parsedWrapped.code || res.status,\n code: parsedWrapped.code\n ? `API_ERROR_${parsedWrapped.code}`\n : \"API_ERROR\",\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n responseData = parsedWrapped.data;\n }\n\n if (!res.ok) {\n const error = this.createError({\n message: json.message || res.statusText,\n status: res.status,\n code: json.code,\n title: json.title,\n detail: json.detail,\n errors: json.errors,\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n const parsed = endpoint.response.parse(responseData);\n return this.responseTransform(parsed);\n };\n\n try {\n const result = await this.executeWithRetry(execute);\n if (timeoutId) clearTimeout(timeoutId);\n return result;\n } catch (err: any) {\n if (timeoutId) clearTimeout(timeoutId);\n const error = this.normalizeError(err);\n this.errorHandler?.(error as any);\n throw error;\n }\n }\n\n private async executeWithRetry(fn: () => Promise<any>): Promise<any> {\n if (!this.retryConfig) return fn();\n\n const { maxRetries, backoff, retryCondition } = this.retryConfig;\n let attempt = 0;\n\n while (true) {\n try {\n return await fn();\n } catch (err: any) {\n attempt++;\n const error = this.normalizeError(err);\n\n const shouldRetry =\n attempt <= maxRetries &&\n (retryCondition?.(error, attempt) ??\n (error.status !== undefined && error.status >= 500));\n\n if (!shouldRetry) throw error;\n\n const delay = this.getBackoffDelay(backoff, attempt);\n await new Promise((r) => setTimeout(r, delay));\n }\n }\n }\n\n private getBackoffDelay(\n type: \"fixed\" | \"linear\" | \"exponential\",\n attempt: number,\n ) {\n const base = 300;\n switch (type) {\n case \"fixed\":\n return base;\n case \"linear\":\n return base * attempt;\n case \"exponential\":\n return base * Math.pow(2, attempt - 1);\n }\n }\n\n private buildUrlAndBody(endpoint: EndpointDefZ, input: any) {\n const parts = this.extractRequestParts(input);\n\n let url = this.config.baseUrl + endpoint.path;\n url = this.applyPathParams(url, parts.path);\n url = this.appendQueryParams(url, parts.query);\n\n let body: BodyInit | undefined;\n const payload = parts.isStructured ? parts.body : input;\n\n if (endpoint.method !== \"GET\" && payload !== undefined) {\n if (endpoint.bodyType === \"form-data\") {\n if (typeof FormData !== \"undefined\" && payload instanceof FormData) {\n body = payload;\n } else {\n const form = new FormData();\n\n if (this.isObjectRecord(payload)) {\n for (const [key, value] of Object.entries(payload)) {\n this.appendFormValue(form, key, value);\n }\n } else if (payload != null) {\n form.append(\"value\", String(payload));\n }\n\n body = form;\n }\n } else {\n body = JSON.stringify(payload);\n }\n }\n\n return { url, body, headers: parts.headers, parts };\n }\n\n private extractRequestParts(input: any): ParsedRequestParts {\n if (this.isStructuredRequestInput(input)) {\n return {\n path: this.isObjectRecord(input.path) ? input.path : undefined,\n query: this.isObjectRecord(input.query) ? input.query : undefined,\n body: input.body,\n headers: this.normalizeHeaders(input.headers ?? input.header),\n isStructured: true,\n };\n }\n\n return {\n body: input,\n headers: {},\n isStructured: false,\n };\n }\n\n private isStructuredRequestInput(\n input: unknown,\n ): input is Record<string, any> {\n if (!this.isObjectRecord(input)) return false;\n\n const keys = Object.keys(input);\n if (keys.length === 0) return false;\n\n return (\n keys.some((key) => REQUEST_PART_KEYS.has(key)) &&\n keys.every((key) => REQUEST_PART_KEYS.has(key))\n );\n }\n\n private isObjectRecord(value: unknown): value is Record<string, any> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n\n private applyPathParams(\n url: string,\n pathParams?: Record<string, any>,\n ): string {\n return url.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = pathParams?.[key];\n\n if (value === undefined || value === null) {\n throw this.createError({\n message: `Missing path param \"${key}\"`,\n code: \"MISSING_PATH_PARAM\",\n });\n }\n\n return encodeURIComponent(String(value));\n });\n }\n\n private appendQueryParams(url: string, query?: Record<string, any>): string {\n if (!query) return url;\n\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(query)) {\n this.appendQueryValue(params, key, value);\n }\n\n const queryString = params.toString();\n if (!queryString) return url;\n\n return `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${queryString}`;\n }\n\n private appendQueryValue(params: URLSearchParams, key: string, value: any) {\n if (value === undefined || value === null) return;\n\n if (Array.isArray(value)) {\n for (const item of value) this.appendQueryValue(params, key, item);\n return;\n }\n\n if (value instanceof Date) {\n params.append(key, value.toISOString());\n return;\n }\n\n if (typeof value === \"object\") {\n params.append(key, JSON.stringify(value));\n return;\n }\n\n params.append(key, String(value));\n }\n\n private appendFormValue(form: FormData, key: string, value: any) {\n if (value === undefined || value === null) return;\n\n if (Array.isArray(value)) {\n for (const item of value) this.appendFormValue(form, key, item);\n return;\n }\n\n if (value instanceof Date) {\n form.append(key, value.toISOString());\n return;\n }\n\n const isBlob = typeof Blob !== \"undefined\" && value instanceof Blob;\n\n if (typeof value === \"object\" && !isBlob) {\n form.append(key, JSON.stringify(value));\n return;\n }\n\n form.append(key, value as any);\n }\n\n private normalizeHeaders(headers: unknown): Record<string, string> {\n if (!this.isObjectRecord(headers)) return {};\n\n const normalized: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined || value === null) continue;\n normalized[key] = String(value);\n }\n\n return normalized;\n }\n\n private createError(error: Partial<RichError> & { message: string }) {\n return new RichError(error);\n }\n\n private normalizeError(err: any) {\n if (err instanceof RichError) return err;\n if (err instanceof z.ZodError) {\n return this.createError({\n message: `Validation error: ${err.errors.map((e) => e.message).join(\", \")}`,\n code: \"VALIDATION_ERROR\",\n });\n }\n return this.createError({ message: err.message || \"Unknown error\" });\n }\n\n private async handleMockRequest(endpoint: any) {\n const delay =\n Math.floor(\n Math.random() * (this.mockDelay.max - this.mockDelay.min + 1),\n ) + this.mockDelay.min;\n\n await new Promise((r) => setTimeout(r, delay));\n\n const data =\n typeof endpoint.mockData === \"function\"\n ? endpoint.mockData()\n : endpoint.mockData;\n\n return this.responseTransform(endpoint.response.parse(data));\n }\n}\n","import { Middleware } from \"@/types\";\nimport z from \"zod\";\n\nexport type LoggingOptions = {\n logRequest?: boolean;\n logResponse?: boolean;\n debug?: boolean;\n};\n\nexport const loggingMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n LoggingOptions\n> = async (ctx, next, options) => {\n const { logRequest = true, logResponse = true, debug = true } = options || {};\n\n if (debug && logRequest) console.log(\"➡️ Request:\", ctx.url, ctx.init);\n\n const res = await next();\n\n if (debug && logResponse) console.log(\"⬅️ Response:\", res.status);\n\n return res;\n};\n","import { Middleware } from \"@/types\";\n\n\nexport type RetryOptions = {\n maxRetries?: number;\n delay?: number; // ms\n};\n\nexport const retryMiddleware = (options?: RetryOptions): Middleware => {\n const { maxRetries = 3, delay = 500 } = options || {};\n\n const middleware: Middleware = async (ctx, next) => {\n let attempt = 0;\n while (true) {\n try {\n return await next();\n } catch (err) {\n if (attempt >= maxRetries) throw err;\n attempt++;\n await new Promise((r) => setTimeout(r, delay * 2 ** attempt));\n }\n }\n };\n\n return middleware;\n};\n","import { Middleware } from \"@/types\";\nimport z from \"zod\";\n\n/**\n * TokenManagementOptions\n * ======================\n * Configuration structure for supplying credentials to the authentication layer.\n *\n * @property refreshToken A required asynchronous function responsible for\n * obtaining a current, valid access token string. This allows\n * for token fetching from storage or re-issuance upon expiry.\n */\nexport type AuthOptions = {\n refreshToken?: () => Promise<string>;\n};\n\n/**\n * AuthenticationInjectorMiddleware\n * ==================================\n * This middleware operates early in the request pipeline to ensure every\n * outgoing request is properly authorized by prepending an Authorization header.\n *\n * Core Logic:\n * -----------\n * 1. It checks if an explicit `refreshToken` supplier was configured in its options.\n * 2. If present, it synchronously calls this supplier to obtain the latest token.\n * 3. The resulting token is formatted as a standard 'Bearer' token and merged\n * into the request's `init.headers`.\n * 4. The request context (`ctx`) is then passed downstream.\n *\n * Note on Error Handling:\n * -----------------------\n * Any failure during the token retrieval process (e.g., if `refreshToken` throws)\n * results in the error being caught, and the request proceeds **without** an\n * Authorization header. This design defers failure response handling to\n * subsequent middleware or the final network fetcher.\n *\n * @param ctx The current request context object, including mutable `init` properties.\n * @param next The function to execute the rest of the middleware chain.\n * @param options The specific configuration passed to this middleware instance.\n *\n * @returns The final `Response` object after the network call completes.\n *\n * @example\n * // Assuming token retrieval logic is defined elsewhere\n * const tokenSupplier = () => fetchTokenFromSecureStorage();\n *\n * client.addInterceptor(\n * authMiddleware({ refreshToken: tokenSupplier })\n * );\n */\nexport const authMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n AuthOptions\n> = async (ctx, next, options) => {\n // Step 1 & 2: Check for and execute the token provider\n if (options?.refreshToken) {\n try {\n const newToken = await options.refreshToken();\n\n // Step 3: Mutate the context's request initialization object\n ctx.init.headers = {\n ...ctx.init.headers, // Preserve any headers set by prior middleware\n Authorization: `Bearer ${newToken}`,\n };\n } catch (error) {\n // Step 4: Fail silently for header injection purposes\n // The request will proceed unauthenticated if the token failed to load\n console.warn(\n \"Authentication token refresh failed, proceeding without authorization header.\",\n error,\n );\n }\n }\n\n // Step 5: Pass control to the next step in the request pipeline\n return next();\n};\n","import { MiddlewareContext, MiddlewareNext } from \"@/types\";\n\n/**\n * CacheOptions\n * ============\n * Options for configuring the cache middleware.\n * - `ttl` (Time To Live): Duration (in milliseconds) to keep cached GET responses.\n * After this time, cached data expires and a fresh network call is performed.\n */\nexport type CacheOptions = { ttl?: number };\n\n/**\n * cacheMiddleware\n * ===============\n * A generic caching middleware for GET requests in the ApiClient.\n * It stores successful responses in memory based on URL and method,\n * returning cached data for subsequent identical requests until the TTL expires.\n *\n * Purpose:\n * --------\n * - Reduces redundant network calls\n * - Improves performance for frequently fetched resources\n * - Useful for lightweight front-end caching (not suitable for sensitive data)\n *\n * Behavior:\n * ---------\n * 1. Only applies to `GET` requests; all other HTTP methods bypass caching.\n * 2. Caches the parsed JSON response in a simple in-memory Map.\n * 3. On subsequent requests:\n * - If the cache entry exists and hasn’t expired, returns a synthetic\n * `Response` object built from cached JSON.\n * - Otherwise performs the network call and refreshes the cache.\n *\n * @param options - Optional cache configuration (TTL in ms)\n *\n * @returns Middleware function compatible with the ApiClient pipeline.\n *\n * @example\n * client.use(\n * cacheMiddleware({ ttl: 120000 }) // cache GET results for 2 minutes\n * );\n *\n * @note Each middleware instance maintains its own internal cache\n * and is memory-scoped (not persistent between reloads).\n */\nexport const cacheMiddleware = (options: CacheOptions = {}) => {\n // Default TTL = 60 seconds, unless overridden\n const { ttl = 60000 } = options;\n\n /**\n * Internal cache store.\n * Keys are composed as `\"METHOD:URL\"`.\n * Values include cached response data and expiration timestamp.\n */\n const cache = new Map<string, { data: any; expires: number }>();\n\n // Return an asynchronous middleware function conforming to the standard signature\n return async (ctx: MiddlewareContext, next: MiddlewareNext) => {\n // Caching only applies to GET requests\n if (ctx.init.method === \"GET\") {\n const key = `${ctx.init.method}:${ctx.url}`;\n const cached = cache.get(key);\n const now = Date.now();\n\n // Check if valid cached response exists and hasn't expired\n if (cached && cached.expires > now) {\n // Return a new synthetic Response containing cached data\n return new Response(JSON.stringify(cached.data), {\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n // Perform the actual network request via the next middleware/fetcher\n const res = await next();\n\n // Attempt to read JSON data from the response (clone avoids stream lock)\n const data = await res\n .clone()\n .json()\n .catch(() => null);\n\n // Store parsed data with expiration if successfully obtained\n if (data) {\n cache.set(key, { data, expires: now + ttl });\n }\n\n // Return original response to caller\n return res;\n }\n\n // For all non‑GET requests, just forward the call with no caching logic\n return next();\n };\n};\n","import type { Middleware, DeepEncryptionMap, EncryptionMethod } from \"@/types\";\nimport CryptoJS from \"crypto-js\";\nimport forge from \"node-forge\";\nimport { z } from \"zod\";\n\ntype SymmetricKeyMaterial = {\n type: \"symmetric\";\n key: string;\n};\n\ntype RSAKeyMaterial = {\n type: \"rsa\";\n publicKey: string;\n privateKey: string;\n};\n\ntype KeyMaterial = SymmetricKeyMaterial | RSAKeyMaterial;\n\ntype CustomHandlers = {\n encrypt: (value: string, key: KeyMaterial) => string | Promise<string>;\n decrypt: (value: string, key: KeyMaterial) => string | Promise<string>;\n};\n\nexport interface EncryptionOptions {\n keyProvider: () => KeyMaterial | Promise<KeyMaterial>;\n customHandlers?: CustomHandlers;\n\n /**\n * true = throw when encryption/decryption fails, which avoids leaking plaintext.\n * false = log and continue/fallback to the original response.\n * Default: true\n */\n failClosed?: boolean;\n}\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasKey(value: unknown, key: string): value is Record<string, unknown> {\n return (\n isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, key)\n );\n}\n\nfunction toMiddlewareError(message: string, error: unknown): Error {\n const err = new Error(\n `${message}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n (err as any).cause = error;\n return err;\n}\n\nfunction encryptWithAES(value: string, key: string): string {\n return CryptoJS.AES.encrypt(value, key).toString();\n}\n\nfunction decryptWithAES(value: string, key: string): string {\n const bytes = CryptoJS.AES.decrypt(value, key);\n return bytes.toString(CryptoJS.enc.Utf8);\n}\n\nfunction encryptWithDES(value: string, key: string): string {\n return CryptoJS.DES.encrypt(value, key).toString();\n}\n\nfunction decryptWithDES(value: string, key: string): string {\n const bytes = CryptoJS.DES.decrypt(value, key);\n return bytes.toString(CryptoJS.enc.Utf8);\n}\n\nfunction encodeWithBase64(value: string): string {\n return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(value));\n}\n\nfunction decodeWithBase64(value: string): string {\n return CryptoJS.enc.Base64.parse(value).toString(CryptoJS.enc.Utf8);\n}\n\nfunction encryptWithRSA(value: string, publicKey: string): string {\n const publicKeyObject = forge.pki.publicKeyFromPem(publicKey);\n const encrypted = publicKeyObject.encrypt(\n forge.util.encodeUtf8(value),\n \"RSA-OAEP\",\n );\n return forge.util.encode64(encrypted);\n}\n\nfunction decryptWithRSA(value: string, privateKey: string): string {\n const privateKeyObject = forge.pki.privateKeyFromPem(privateKey);\n const decrypted = privateKeyObject.decrypt(\n forge.util.decode64(value),\n \"RSA-OAEP\",\n );\n return forge.util.decodeUtf8(decrypted);\n}\n\nasync function encryptValue(\n value: string,\n method: EncryptionMethod,\n keyMaterial: KeyMaterial,\n customHandlers?: CustomHandlers,\n): Promise<string> {\n switch (method) {\n case \"AES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"AES encryption requires symmetric key material.\");\n }\n return encryptWithAES(value, keyMaterial.key);\n }\n\n case \"DES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"DES encryption requires symmetric key material.\");\n }\n return encryptWithDES(value, keyMaterial.key);\n }\n\n case \"Base64\": {\n return encodeWithBase64(value);\n }\n\n case \"RSA\": {\n if (keyMaterial.type !== \"rsa\") {\n throw new Error(\"RSA encryption requires RSA key material.\");\n }\n return encryptWithRSA(value, keyMaterial.publicKey);\n }\n\n case \"Custom\": {\n if (!customHandlers) {\n throw new Error(\"Custom encryption requires custom handlers.\");\n }\n return await customHandlers.encrypt(value, keyMaterial);\n }\n\n default: {\n const exhaustiveCheck: never = method;\n throw new Error(`Unsupported encryption method: ${exhaustiveCheck}`);\n }\n }\n}\n\nasync function decryptValue(\n value: string,\n method: EncryptionMethod,\n keyMaterial: KeyMaterial,\n customHandlers?: CustomHandlers,\n): Promise<string> {\n switch (method) {\n case \"AES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"AES decryption requires symmetric key material.\");\n }\n return decryptWithAES(value, keyMaterial.key);\n }\n\n case \"DES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"DES decryption requires symmetric key material.\");\n }\n return decryptWithDES(value, keyMaterial.key);\n }\n\n case \"Base64\": {\n return decodeWithBase64(value);\n }\n\n case \"RSA\": {\n if (keyMaterial.type !== \"rsa\") {\n throw new Error(\"RSA decryption requires RSA key material.\");\n }\n return decryptWithRSA(value, keyMaterial.privateKey);\n }\n\n case \"Custom\": {\n if (!customHandlers) {\n throw new Error(\"Custom decryption requires custom handlers.\");\n }\n return await customHandlers.decrypt(value, keyMaterial);\n }\n\n default: {\n const exhaustiveCheck: never = method;\n throw new Error(`Unsupported decryption method: ${exhaustiveCheck}`);\n }\n }\n}\n\nexport async function processDeep<T = unknown>(\n data: unknown,\n map: DeepEncryptionMap | null | undefined,\n defaultMethod: EncryptionMethod,\n transform: (value: unknown, method: EncryptionMethod) => Promise<unknown>,\n): Promise<T> {\n if (data == null || map == null) return data as T;\n\n if (typeof map === \"string\") return (await transform(data, map)) as T;\n\n if (typeof map === \"boolean\") {\n return (map ? await transform(data, defaultMethod) : data) as T;\n }\n\n if (Array.isArray(data)) {\n if (!Array.isArray(map)) {\n return Promise.all(\n data.map((item) => processDeep(item, map, defaultMethod, transform)),\n ) as Promise<T>;\n }\n\n return Promise.all(\n data.map((item, idx) =>\n processDeep(item, map[idx] ?? map[0], defaultMethod, transform),\n ),\n ) as Promise<T>;\n }\n\n if (isPlainObject(data) && isPlainObject(map)) {\n const result: Record<string, unknown> = { ...data };\n\n for (const key of Object.keys(map)) {\n const childMap = (map as Record<string, DeepEncryptionMap>)[key];\n if (childMap == null) continue;\n\n const currentVal = result[key];\n if (currentVal !== undefined) {\n result[key] = await processDeep(\n currentVal,\n childMap,\n defaultMethod,\n transform,\n );\n }\n }\n\n return result as T;\n }\n\n return data as T;\n}\n\nfunction getRequestBodyMap(map: DeepEncryptionMap): DeepEncryptionMap {\n // Supports both styles:\n // encryption.request: { password: true }\n // encryption.request: { body: { password: true } }\n if (hasKey(map, \"body\")) {\n return map.body as DeepEncryptionMap;\n }\n\n return map;\n}\n\nexport const encryptionMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n EncryptionOptions\n> = async (ctx, next, options) => {\n if (!options) {\n throw new Error(\"Encryption middleware options were not provided.\");\n }\n\n const { keyProvider, customHandlers } = options;\n const failClosed = options.failClosed ?? true;\n const encryption = ctx.endpoint.encryption;\n\n if (!encryption || (!encryption.request && !encryption.response)) {\n return next();\n }\n\n const requestMethod: EncryptionMethod =\n typeof encryption.method === \"string\"\n ? encryption.method\n : (encryption.method?.request ?? \"AES\");\n\n const responseMethod: EncryptionMethod =\n typeof encryption.method === \"string\"\n ? encryption.method\n : (encryption.method?.response ?? \"AES\");\n\n const keyMaterial = await keyProvider();\n\n if (\n encryption.request &&\n typeof ctx.init.body === \"string\" &&\n ctx.init.body.length > 0\n ) {\n try {\n const parsedBody = JSON.parse(ctx.init.body);\n const bodyMap = getRequestBodyMap(encryption.request);\n\n const encryptedBody = await processDeep(\n parsedBody,\n bodyMap,\n requestMethod,\n async (value, method) => {\n const serialized =\n typeof value === \"string\" ? value : JSON.stringify(value);\n\n return encryptValue(serialized, method, keyMaterial, customHandlers);\n },\n );\n\n ctx.init.body = JSON.stringify(encryptedBody);\n\n if (ctx.request) {\n ctx.request.body = encryptedBody;\n }\n } catch (error) {\n if (failClosed) {\n throw toMiddlewareError(\n \"Encryption middleware request encryption failed\",\n error,\n );\n }\n\n console.error(\"Encryption middleware request encryption failed.\", error);\n }\n }\n\n const response = await next();\n\n if (!encryption.response) {\n return response;\n }\n\n try {\n const text = await response.clone().text();\n if (!text) return response;\n\n const parsedResponse = JSON.parse(text);\n\n const decryptedPayload = await processDeep(\n parsedResponse,\n encryption.response,\n responseMethod,\n async (value, method) => {\n if (typeof value !== \"string\") return value;\n\n const decrypted = await decryptValue(\n value,\n method,\n keyMaterial,\n customHandlers,\n );\n\n return safeJsonParse(decrypted);\n },\n );\n\n return new Response(JSON.stringify(decryptedPayload), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } catch (error) {\n if (failClosed) {\n throw toMiddlewareError(\n \"Encryption middleware response decryption failed\",\n error,\n );\n }\n\n console.error(\"Encryption middleware response decryption failed.\", error);\n return response;\n }\n};\n","import { z } from \"zod\";\n\nexport const makeRequestSchema =\n <\n TPath extends z.ZodRawShape = {},\n TQuery extends z.ZodRawShape = {},\n TBody extends z.ZodTypeAny = z.ZodUndefined,\n >() =>\n (\n defs: {\n path?: z.ZodObject<TPath>;\n query?: z.ZodObject<TQuery>;\n body?: TBody;\n headers?: z.ZodTypeAny;\n } = {},\n ) =>\n z.object({\n path: (defs.path ?? z.object({})).optional(),\n query: (defs.query ?? z.object({})).optional(),\n body: (defs.body ?? z.undefined()) as TBody | z.ZodUndefined,\n headers: (defs.headers ?? z.record(z.string()).optional()) as any,\n });\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAaX,IAAM,YAAN,cAAwB,MAA2B;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,OAAiD;AAC3D,UAAM,MAAM,OAAO;AACnB,WAAO,OAAO,MAAM,KAAK;AAAA,EAC3B;AACF;AAUA,IAAM,oBAAoB,oBAAI,IAAI;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,YAAN,MAAsE;AAAA,EAiB3E,YACU,QAOA,WACR;AARQ;AAOA;AAER,SAAK,cAAc,OAAO,eAAe;AACzC,SAAK,YAAY,OAAO,aAAa,EAAE,KAAK,KAAK,KAAK,IAAK;AAC3D,SAAK,gBAAgB,OAAO;AAAA,EAC9B;AAAA,EAZU;AAAA,EAOA;AAAA,EAxBF,cAAwD,CAAC;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EAC7C,MAAO,KAAK,QAAQ,cAAE,UAAU;AAAA,EAChC,SAAU,KAAK,WAAW,cAAE,OAAO,cAAE,OAAO,CAAC,EAAE,SAAS;AAC1D,CAAC;","names":["module","CryptoJS","forge","import_zod"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/client.ts","../src/middlewares/logging.ts","../src/middlewares/retry.ts","../src/middlewares/auth.ts","../src/middlewares/cache.ts","../src/middlewares/encryption.ts","../src/utils/make-request-schema.ts"],"sourcesContent":["export * from \"./types\";\nexport * from \"./client\";\nexport * from \"./middlewares/logging\";\nexport * from \"./middlewares/retry\";\nexport * from \"./middlewares/auth\";\nexport * from \"./middlewares/cache\";\nexport * from \"./middlewares/encryption\";\nexport * from \"./utils/make-request-schema\";\n","import { z } from \"zod\";\nimport {\n Contracts,\n EndpointDef,\n EndpointDefZ,\n Middleware,\n ErrorLike,\n EndpointMethods,\n TokenProvider,\n RequestOptions,\n MiddlewareContext,\n} from \"./types\";\n\nexport class RichError extends Error implements ErrorLike {\n status?: number;\n code?: string;\n title?: string;\n detail?: string;\n errors?: Record<string, string[]>;\n\n constructor(error: Partial<ErrorLike> & { message: string }) {\n super(error.message);\n Object.assign(this, error);\n }\n}\n\ntype ParsedRequestParts = {\n path?: Record<string, any>;\n query?: Record<string, any>;\n body?: any;\n headers: Record<string, string>;\n isStructured: boolean;\n};\n\nconst REQUEST_PART_KEYS = new Set([\n \"path\",\n \"query\",\n \"body\",\n \"headers\",\n \"header\",\n]);\n\nexport class ApiClient<C extends Contracts, E extends ErrorLike = RichError> {\n private middlewares: Array<{ fn: Middleware; options?: any }> = [];\n private errorHandler?: (error: E) => void;\n private responseTransform: (data: any) => any = (d) => d;\n private useMockData = false;\n private mockDelay = { min: 100, max: 1000 };\n private responseWrapper?: (successResponse: z.ZodTypeAny) => z.ZodTypeAny;\n private tokenProvider?: TokenProvider;\n\n private retryConfig?: {\n maxRetries: number;\n backoff: \"fixed\" | \"linear\" | \"exponential\";\n retryCondition?: (error: RichError, attempt: number) => boolean;\n };\n\n private _modules!: { [M in keyof C]: EndpointMethods<C[M]> };\n\n constructor(\n private config: {\n baseUrl: string;\n token?: string;\n tokenProvider?: TokenProvider;\n useMockData?: boolean;\n mockDelay?: { min: number; max: number };\n },\n private contracts: C,\n ) {\n this.useMockData = config.useMockData || false;\n this.mockDelay = config.mockDelay || { min: 100, max: 1000 };\n this.tokenProvider = config.tokenProvider;\n }\n\n init() {\n const modules = {} as { [M in keyof C]: EndpointMethods<C[M]> };\n\n for (const moduleName in this.contracts) {\n const module = this.contracts[moduleName];\n (modules as any)[moduleName] = {} as EndpointMethods<typeof module>;\n\n for (const endpointName in module) {\n const endpoint = module[endpointName] as EndpointDefZ;\n\n (modules as any)[moduleName][endpointName] = (\n input: any,\n options?: RequestOptions,\n ) => this.request(endpoint as any, input, options);\n }\n }\n\n this._modules = modules;\n }\n\n get modules() {\n return this._modules;\n }\n\n use<T>(middleware: Middleware<any, any, T>, options?: T) {\n this.middlewares.push({ fn: middleware, options });\n }\n\n onError(handler: (error: E) => void) {\n this.errorHandler = handler;\n }\n\n useResponseTransform(fn: (data: any) => any) {\n this.responseTransform = fn;\n }\n\n setRetryConfig(config: ApiClient<C>[\"retryConfig\"]) {\n this.retryConfig = config;\n }\n\n setTokenProvider(provider: TokenProvider) {\n this.tokenProvider = provider;\n }\n\n setMockMode(enabled: boolean, delay?: { min: number; max: number }) {\n this.useMockData = enabled;\n if (delay) this.mockDelay = delay;\n }\n\n setResponseWrapper(wrapper: (successResponse: z.ZodTypeAny) => z.ZodTypeAny) {\n this.responseWrapper = wrapper;\n }\n\n async getCurrentToken(): Promise<string | undefined> {\n if (this.tokenProvider) return await this.tokenProvider();\n return this.config.token;\n }\n\n private async request<TReq extends z.ZodTypeAny, TRes extends z.ZodTypeAny>(\n endpoint: EndpointDef<TReq, TRes>,\n input: z.infer<TReq>,\n options?: RequestOptions,\n ): Promise<z.infer<TRes>> {\n const parsedInput = endpoint.request.parse(input);\n\n if (this.useMockData && endpoint.mockData) {\n return this.handleMockRequest(endpoint);\n }\n\n const built = this.buildUrlAndBody(endpoint as EndpointDefZ, parsedInput);\n\n return this.performRequestLogic(\n endpoint,\n parsedInput,\n built.url,\n built.body,\n built.headers,\n built.parts,\n options,\n );\n }\n\n private async performRequestLogic<\n TReq extends z.ZodTypeAny,\n TRes extends z.ZodTypeAny,\n >(\n endpoint: EndpointDef<TReq, TRes>,\n parsedInput: z.infer<TReq>,\n url: string,\n body: BodyInit | undefined,\n requestHeaders: Record<string, string>,\n requestParts: ParsedRequestParts,\n options?: RequestOptions,\n ): Promise<z.infer<TRes>> {\n const headers: Record<string, string> = {};\n\n if (endpoint.bodyType !== \"form-data\") {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n const endpointHeaders =\n typeof endpoint.headers === \"function\"\n ? endpoint.headers(parsedInput)\n : endpoint.headers;\n\n Object.assign(\n headers,\n this.normalizeHeaders(endpointHeaders),\n requestHeaders,\n );\n\n if (endpoint.auth) {\n const token = await this.getCurrentToken();\n\n if (!token) {\n const error = this.createError({\n message: `Missing token for ${endpoint.path}`,\n status: 401,\n code: \"NO_TOKEN\",\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n\n const ctx = {\n url,\n init: { method: endpoint.method, headers, body } as RequestInit,\n endpoint: endpoint as never,\n request: {\n ...requestParts,\n rawInput: parsedInput,\n },\n } satisfies MiddlewareContext;\n\n let controller: AbortController | undefined;\n let timeoutId: any;\n\n if (options?.timeout) {\n controller = new AbortController();\n timeoutId = setTimeout(() => controller!.abort(), options.timeout);\n }\n\n if (options?.signal || controller) {\n ctx.init.signal = options?.signal || controller?.signal;\n }\n\n const runner = this.middlewares.reduceRight(\n (next, mw) => () => mw.fn(ctx, next, mw.options),\n () => fetch(ctx.url, ctx.init),\n );\n\n const execute = async () => {\n const res = await runner();\n const json = await res.json();\n let responseData = json;\n\n if (this.responseWrapper) {\n const wrappedSchema = this.responseWrapper(endpoint.response);\n const parsedWrapped = wrappedSchema.parse(json) as any;\n\n if (parsedWrapped.success === false) {\n const error = this.createError({\n message:\n parsedWrapped.message || parsedWrapped.error || \"Request failed\",\n status: parsedWrapped.code || res.status,\n code: parsedWrapped.code\n ? `API_ERROR_${parsedWrapped.code}`\n : \"API_ERROR\",\n });\n\n this.errorHandler?.(error as any);\n throw error;\n }\n\n responseData = parsedWrapped.data;\n }\n\n if (!res.ok) {\n const error = this.createError({\n message: json.message || res.statusText,\n status: res.status,\n code: json.code,\n title: json.title,\n detail: json.detail,\n errors: json.errors,\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n const parsed = endpoint.response.parse(responseData);\n return this.responseTransform(parsed);\n };\n\n try {\n const result = await this.executeWithRetry(execute);\n if (timeoutId) clearTimeout(timeoutId);\n return result;\n } catch (err: any) {\n if (timeoutId) clearTimeout(timeoutId);\n const error = this.normalizeError(err);\n this.errorHandler?.(error as any);\n throw error;\n }\n }\n\n private async executeWithRetry(fn: () => Promise<any>): Promise<any> {\n if (!this.retryConfig) return fn();\n\n const { maxRetries, backoff, retryCondition } = this.retryConfig;\n let attempt = 0;\n\n while (true) {\n try {\n return await fn();\n } catch (err: any) {\n attempt++;\n const error = this.normalizeError(err);\n\n const shouldRetry =\n attempt <= maxRetries &&\n (retryCondition?.(error, attempt) ??\n (error.status !== undefined && error.status >= 500));\n\n if (!shouldRetry) throw error;\n\n const delay = this.getBackoffDelay(backoff, attempt);\n await new Promise((r) => setTimeout(r, delay));\n }\n }\n }\n\n private getBackoffDelay(\n type: \"fixed\" | \"linear\" | \"exponential\",\n attempt: number,\n ) {\n const base = 300;\n switch (type) {\n case \"fixed\":\n return base;\n case \"linear\":\n return base * attempt;\n case \"exponential\":\n return base * Math.pow(2, attempt - 1);\n }\n }\n\n private buildUrlAndBody(endpoint: EndpointDefZ, input: any) {\n const parts = this.extractRequestParts(input);\n\n let url = this.config.baseUrl + endpoint.path;\n url = this.applyPathParams(url, parts.path);\n url = this.appendQueryParams(url, parts.query);\n\n let body: BodyInit | undefined;\n const payload = parts.isStructured ? parts.body : input;\n\n if (endpoint.method !== \"GET\" && payload !== undefined) {\n if (endpoint.bodyType === \"form-data\") {\n if (typeof FormData !== \"undefined\" && payload instanceof FormData) {\n body = payload;\n } else {\n const form = new FormData();\n\n if (this.isObjectRecord(payload)) {\n for (const [key, value] of Object.entries(payload)) {\n this.appendFormValue(form, key, value);\n }\n } else if (payload != null) {\n form.append(\"value\", String(payload));\n }\n\n body = form;\n }\n } else {\n body = JSON.stringify(payload);\n }\n }\n\n return { url, body, headers: parts.headers, parts };\n }\n\n private extractRequestParts(input: any): ParsedRequestParts {\n if (this.isStructuredRequestInput(input)) {\n return {\n path: this.isObjectRecord(input.path) ? input.path : undefined,\n query: this.isObjectRecord(input.query) ? input.query : undefined,\n body: input.body,\n headers: this.normalizeHeaders(input.headers ?? input.header),\n isStructured: true,\n };\n }\n\n return {\n body: input,\n headers: {},\n isStructured: false,\n };\n }\n\n private isStructuredRequestInput(\n input: unknown,\n ): input is Record<string, any> {\n if (!this.isObjectRecord(input)) return false;\n\n const keys = Object.keys(input);\n if (keys.length === 0) return false;\n\n return (\n keys.some((key) => REQUEST_PART_KEYS.has(key)) &&\n keys.every((key) => REQUEST_PART_KEYS.has(key))\n );\n }\n\n private isObjectRecord(value: unknown): value is Record<string, any> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n\n private applyPathParams(\n url: string,\n pathParams?: Record<string, any>,\n ): string {\n return url.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = pathParams?.[key];\n\n if (value === undefined || value === null) {\n throw this.createError({\n message: `Missing path param \"${key}\"`,\n code: \"MISSING_PATH_PARAM\",\n });\n }\n\n return encodeURIComponent(String(value));\n });\n }\n\n private appendQueryParams(url: string, query?: Record<string, any>): string {\n if (!query) return url;\n\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(query)) {\n this.appendQueryValue(params, key, value);\n }\n\n const queryString = params.toString();\n if (!queryString) return url;\n\n return `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${queryString}`;\n }\n\n private appendQueryValue(params: URLSearchParams, key: string, value: any) {\n if (value === undefined || value === null) return;\n\n if (Array.isArray(value)) {\n for (const item of value) this.appendQueryValue(params, key, item);\n return;\n }\n\n if (value instanceof Date) {\n params.append(key, value.toISOString());\n return;\n }\n\n if (typeof value === \"object\") {\n params.append(key, JSON.stringify(value));\n return;\n }\n\n params.append(key, String(value));\n }\n\n private appendFormValue(form: FormData, key: string, value: any) {\n if (value === undefined || value === null) return;\n\n if (Array.isArray(value)) {\n for (const item of value) this.appendFormValue(form, key, item);\n return;\n }\n\n if (value instanceof Date) {\n form.append(key, value.toISOString());\n return;\n }\n\n const isBlob = typeof Blob !== \"undefined\" && value instanceof Blob;\n\n if (typeof value === \"object\" && !isBlob) {\n form.append(key, JSON.stringify(value));\n return;\n }\n\n form.append(key, value as any);\n }\n\n private normalizeHeaders(headers: unknown): Record<string, string> {\n if (!this.isObjectRecord(headers)) return {};\n\n const normalized: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined || value === null) continue;\n normalized[key] = String(value);\n }\n\n return normalized;\n }\n\n private createError(error: Partial<RichError> & { message: string }) {\n return new RichError(error);\n }\n\n private normalizeError(err: any) {\n if (err instanceof RichError) return err;\n if (err instanceof z.ZodError) {\n return this.createError({\n message: `Validation error: ${err.issues.map((e) => e.message).join(\", \")}`,\n code: \"VALIDATION_ERROR\",\n });\n }\n return this.createError({ message: err.message || \"Unknown error\" });\n }\n\n private async handleMockRequest(endpoint: any) {\n const delay =\n Math.floor(\n Math.random() * (this.mockDelay.max - this.mockDelay.min + 1),\n ) + this.mockDelay.min;\n\n await new Promise((r) => setTimeout(r, delay));\n\n const data =\n typeof endpoint.mockData === \"function\"\n ? endpoint.mockData()\n : endpoint.mockData;\n\n return this.responseTransform(endpoint.response.parse(data));\n }\n}\n","import { Middleware } from \"@/types\";\nimport z from \"zod\";\n\nexport type LoggingOptions = {\n logRequest?: boolean;\n logResponse?: boolean;\n debug?: boolean;\n};\n\nexport const loggingMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n LoggingOptions\n> = async (ctx, next, options) => {\n const { logRequest = true, logResponse = true, debug = true } = options || {};\n\n if (debug && logRequest) console.log(\"➡️ Request:\", ctx.url, ctx.init);\n\n const res = await next();\n\n if (debug && logResponse) console.log(\"⬅️ Response:\", res.status);\n\n return res;\n};\n","import { Middleware } from \"@/types\";\n\n\nexport type RetryOptions = {\n maxRetries?: number;\n delay?: number; // ms\n};\n\nexport const retryMiddleware = (options?: RetryOptions): Middleware => {\n const { maxRetries = 3, delay = 500 } = options || {};\n\n const middleware: Middleware = async (ctx, next) => {\n let attempt = 0;\n while (true) {\n try {\n return await next();\n } catch (err) {\n if (attempt >= maxRetries) throw err;\n attempt++;\n await new Promise((r) => setTimeout(r, delay * 2 ** attempt));\n }\n }\n };\n\n return middleware;\n};\n","import { Middleware } from \"@/types\";\nimport z from \"zod\";\n\n/**\n * TokenManagementOptions\n * ======================\n * Configuration structure for supplying credentials to the authentication layer.\n *\n * @property refreshToken A required asynchronous function responsible for\n * obtaining a current, valid access token string. This allows\n * for token fetching from storage or re-issuance upon expiry.\n */\nexport type AuthOptions = {\n refreshToken?: () => Promise<string>;\n};\n\n/**\n * AuthenticationInjectorMiddleware\n * ==================================\n * This middleware operates early in the request pipeline to ensure every\n * outgoing request is properly authorized by prepending an Authorization header.\n *\n * Core Logic:\n * -----------\n * 1. It checks if an explicit `refreshToken` supplier was configured in its options.\n * 2. If present, it synchronously calls this supplier to obtain the latest token.\n * 3. The resulting token is formatted as a standard 'Bearer' token and merged\n * into the request's `init.headers`.\n * 4. The request context (`ctx`) is then passed downstream.\n *\n * Note on Error Handling:\n * -----------------------\n * Any failure during the token retrieval process (e.g., if `refreshToken` throws)\n * results in the error being caught, and the request proceeds **without** an\n * Authorization header. This design defers failure response handling to\n * subsequent middleware or the final network fetcher.\n *\n * @param ctx The current request context object, including mutable `init` properties.\n * @param next The function to execute the rest of the middleware chain.\n * @param options The specific configuration passed to this middleware instance.\n *\n * @returns The final `Response` object after the network call completes.\n *\n * @example\n * // Assuming token retrieval logic is defined elsewhere\n * const tokenSupplier = () => fetchTokenFromSecureStorage();\n *\n * client.addInterceptor(\n * authMiddleware({ refreshToken: tokenSupplier })\n * );\n */\nexport const authMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n AuthOptions\n> = async (ctx, next, options) => {\n // Step 1 & 2: Check for and execute the token provider\n if (options?.refreshToken) {\n try {\n const newToken = await options.refreshToken();\n\n // Step 3: Mutate the context's request initialization object\n ctx.init.headers = {\n ...ctx.init.headers, // Preserve any headers set by prior middleware\n Authorization: `Bearer ${newToken}`,\n };\n } catch (error) {\n // Step 4: Fail silently for header injection purposes\n // The request will proceed unauthenticated if the token failed to load\n console.warn(\n \"Authentication token refresh failed, proceeding without authorization header.\",\n error,\n );\n }\n }\n\n // Step 5: Pass control to the next step in the request pipeline\n return next();\n};\n","import { MiddlewareContext, MiddlewareNext } from \"@/types\";\n\n/**\n * CacheOptions\n * ============\n * Options for configuring the cache middleware.\n * - `ttl` (Time To Live): Duration (in milliseconds) to keep cached GET responses.\n * After this time, cached data expires and a fresh network call is performed.\n */\nexport type CacheOptions = { ttl?: number };\n\n/**\n * cacheMiddleware\n * ===============\n * A generic caching middleware for GET requests in the ApiClient.\n * It stores successful responses in memory based on URL and method,\n * returning cached data for subsequent identical requests until the TTL expires.\n *\n * Purpose:\n * --------\n * - Reduces redundant network calls\n * - Improves performance for frequently fetched resources\n * - Useful for lightweight front-end caching (not suitable for sensitive data)\n *\n * Behavior:\n * ---------\n * 1. Only applies to `GET` requests; all other HTTP methods bypass caching.\n * 2. Caches the parsed JSON response in a simple in-memory Map.\n * 3. On subsequent requests:\n * - If the cache entry exists and hasn’t expired, returns a synthetic\n * `Response` object built from cached JSON.\n * - Otherwise performs the network call and refreshes the cache.\n *\n * @param options - Optional cache configuration (TTL in ms)\n *\n * @returns Middleware function compatible with the ApiClient pipeline.\n *\n * @example\n * client.use(\n * cacheMiddleware({ ttl: 120000 }) // cache GET results for 2 minutes\n * );\n *\n * @note Each middleware instance maintains its own internal cache\n * and is memory-scoped (not persistent between reloads).\n */\nexport const cacheMiddleware = (options: CacheOptions = {}) => {\n // Default TTL = 60 seconds, unless overridden\n const { ttl = 60000 } = options;\n\n /**\n * Internal cache store.\n * Keys are composed as `\"METHOD:URL\"`.\n * Values include cached response data and expiration timestamp.\n */\n const cache = new Map<string, { data: any; expires: number }>();\n\n // Return an asynchronous middleware function conforming to the standard signature\n return async (ctx: MiddlewareContext, next: MiddlewareNext) => {\n // Caching only applies to GET requests\n if (ctx.init.method === \"GET\") {\n const key = `${ctx.init.method}:${ctx.url}`;\n const cached = cache.get(key);\n const now = Date.now();\n\n // Check if valid cached response exists and hasn't expired\n if (cached && cached.expires > now) {\n // Return a new synthetic Response containing cached data\n return new Response(JSON.stringify(cached.data), {\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n // Perform the actual network request via the next middleware/fetcher\n const res = await next();\n\n // Attempt to read JSON data from the response (clone avoids stream lock)\n const data = await res\n .clone()\n .json()\n .catch(() => null);\n\n // Store parsed data with expiration if successfully obtained\n if (data) {\n cache.set(key, { data, expires: now + ttl });\n }\n\n // Return original response to caller\n return res;\n }\n\n // For all non‑GET requests, just forward the call with no caching logic\n return next();\n };\n};\n","import type { Middleware, DeepEncryptionMap, EncryptionMethod } from \"@/types\";\nimport CryptoJS from \"crypto-js\";\nimport forge from \"node-forge\";\nimport { z } from \"zod\";\n\ntype SymmetricKeyMaterial = {\n type: \"symmetric\";\n key: string;\n};\n\ntype RSAKeyMaterial = {\n type: \"rsa\";\n publicKey: string;\n privateKey: string;\n};\n\ntype KeyMaterial = SymmetricKeyMaterial | RSAKeyMaterial;\n\ntype CustomHandlers = {\n encrypt: (value: string, key: KeyMaterial) => string | Promise<string>;\n decrypt: (value: string, key: KeyMaterial) => string | Promise<string>;\n};\n\nexport interface EncryptionOptions {\n keyProvider: () => KeyMaterial | Promise<KeyMaterial>;\n customHandlers?: CustomHandlers;\n\n /**\n * true = throw when encryption/decryption fails, which avoids leaking plaintext.\n * false = log and continue/fallback to the original response.\n * Default: true\n */\n failClosed?: boolean;\n}\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasKey(value: unknown, key: string): value is Record<string, unknown> {\n return (\n isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, key)\n );\n}\n\nfunction toMiddlewareError(message: string, error: unknown): Error {\n const err = new Error(\n `${message}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n (err as any).cause = error;\n return err;\n}\n\nfunction encryptWithAES(value: string, key: string): string {\n return CryptoJS.AES.encrypt(value, key).toString();\n}\n\nfunction decryptWithAES(value: string, key: string): string {\n const bytes = CryptoJS.AES.decrypt(value, key);\n return bytes.toString(CryptoJS.enc.Utf8);\n}\n\nfunction encryptWithDES(value: string, key: string): string {\n return CryptoJS.DES.encrypt(value, key).toString();\n}\n\nfunction decryptWithDES(value: string, key: string): string {\n const bytes = CryptoJS.DES.decrypt(value, key);\n return bytes.toString(CryptoJS.enc.Utf8);\n}\n\nfunction encodeWithBase64(value: string): string {\n return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(value));\n}\n\nfunction decodeWithBase64(value: string): string {\n return CryptoJS.enc.Base64.parse(value).toString(CryptoJS.enc.Utf8);\n}\n\nfunction encryptWithRSA(value: string, publicKey: string): string {\n const publicKeyObject = forge.pki.publicKeyFromPem(publicKey);\n const encrypted = publicKeyObject.encrypt(\n forge.util.encodeUtf8(value),\n \"RSA-OAEP\",\n );\n return forge.util.encode64(encrypted);\n}\n\nfunction decryptWithRSA(value: string, privateKey: string): string {\n const privateKeyObject = forge.pki.privateKeyFromPem(privateKey);\n const decrypted = privateKeyObject.decrypt(\n forge.util.decode64(value),\n \"RSA-OAEP\",\n );\n return forge.util.decodeUtf8(decrypted);\n}\n\nasync function encryptValue(\n value: string,\n method: EncryptionMethod,\n keyMaterial: KeyMaterial,\n customHandlers?: CustomHandlers,\n): Promise<string> {\n switch (method) {\n case \"AES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"AES encryption requires symmetric key material.\");\n }\n return encryptWithAES(value, keyMaterial.key);\n }\n\n case \"DES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"DES encryption requires symmetric key material.\");\n }\n return encryptWithDES(value, keyMaterial.key);\n }\n\n case \"Base64\": {\n return encodeWithBase64(value);\n }\n\n case \"RSA\": {\n if (keyMaterial.type !== \"rsa\") {\n throw new Error(\"RSA encryption requires RSA key material.\");\n }\n return encryptWithRSA(value, keyMaterial.publicKey);\n }\n\n case \"Custom\": {\n if (!customHandlers) {\n throw new Error(\"Custom encryption requires custom handlers.\");\n }\n return await customHandlers.encrypt(value, keyMaterial);\n }\n\n default: {\n const exhaustiveCheck: never = method;\n throw new Error(`Unsupported encryption method: ${exhaustiveCheck}`);\n }\n }\n}\n\nasync function decryptValue(\n value: string,\n method: EncryptionMethod,\n keyMaterial: KeyMaterial,\n customHandlers?: CustomHandlers,\n): Promise<string> {\n switch (method) {\n case \"AES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"AES decryption requires symmetric key material.\");\n }\n return decryptWithAES(value, keyMaterial.key);\n }\n\n case \"DES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"DES decryption requires symmetric key material.\");\n }\n return decryptWithDES(value, keyMaterial.key);\n }\n\n case \"Base64\": {\n return decodeWithBase64(value);\n }\n\n case \"RSA\": {\n if (keyMaterial.type !== \"rsa\") {\n throw new Error(\"RSA decryption requires RSA key material.\");\n }\n return decryptWithRSA(value, keyMaterial.privateKey);\n }\n\n case \"Custom\": {\n if (!customHandlers) {\n throw new Error(\"Custom decryption requires custom handlers.\");\n }\n return await customHandlers.decrypt(value, keyMaterial);\n }\n\n default: {\n const exhaustiveCheck: never = method;\n throw new Error(`Unsupported decryption method: ${exhaustiveCheck}`);\n }\n }\n}\n\nexport async function processDeep<T = unknown>(\n data: unknown,\n map: DeepEncryptionMap | null | undefined,\n defaultMethod: EncryptionMethod,\n transform: (value: unknown, method: EncryptionMethod) => Promise<unknown>,\n): Promise<T> {\n if (data == null || map == null) return data as T;\n\n if (typeof map === \"string\") return (await transform(data, map)) as T;\n\n if (typeof map === \"boolean\") {\n return (map ? await transform(data, defaultMethod) : data) as T;\n }\n\n if (Array.isArray(data)) {\n if (!Array.isArray(map)) {\n return Promise.all(\n data.map((item) => processDeep(item, map, defaultMethod, transform)),\n ) as Promise<T>;\n }\n\n return Promise.all(\n data.map((item, idx) =>\n processDeep(item, map[idx] ?? map[0], defaultMethod, transform),\n ),\n ) as Promise<T>;\n }\n\n if (isPlainObject(data) && isPlainObject(map)) {\n const result: Record<string, unknown> = { ...data };\n\n for (const key of Object.keys(map)) {\n const childMap = (map as Record<string, DeepEncryptionMap>)[key];\n if (childMap == null) continue;\n\n const currentVal = result[key];\n if (currentVal !== undefined) {\n result[key] = await processDeep(\n currentVal,\n childMap,\n defaultMethod,\n transform,\n );\n }\n }\n\n return result as T;\n }\n\n return data as T;\n}\n\nfunction getRequestBodyMap(map: DeepEncryptionMap): DeepEncryptionMap {\n // Supports both styles:\n // encryption.request: { password: true }\n // encryption.request: { body: { password: true } }\n if (hasKey(map, \"body\")) {\n return map.body as DeepEncryptionMap;\n }\n\n return map;\n}\n\nexport const encryptionMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n EncryptionOptions\n> = async (ctx, next, options) => {\n if (!options) {\n throw new Error(\"Encryption middleware options were not provided.\");\n }\n\n const { keyProvider, customHandlers } = options;\n const failClosed = options.failClosed ?? true;\n const encryption = ctx.endpoint.encryption;\n\n if (!encryption || (!encryption.request && !encryption.response)) {\n return next();\n }\n\n const requestMethod: EncryptionMethod =\n typeof encryption.method === \"string\"\n ? encryption.method\n : (encryption.method?.request ?? \"AES\");\n\n const responseMethod: EncryptionMethod =\n typeof encryption.method === \"string\"\n ? encryption.method\n : (encryption.method?.response ?? \"AES\");\n\n const keyMaterial = await keyProvider();\n\n if (\n encryption.request &&\n typeof ctx.init.body === \"string\" &&\n ctx.init.body.length > 0\n ) {\n try {\n const parsedBody = JSON.parse(ctx.init.body);\n const bodyMap = getRequestBodyMap(encryption.request);\n\n const encryptedBody = await processDeep(\n parsedBody,\n bodyMap,\n requestMethod,\n async (value, method) => {\n const serialized =\n typeof value === \"string\" ? value : JSON.stringify(value);\n\n return encryptValue(serialized, method, keyMaterial, customHandlers);\n },\n );\n\n ctx.init.body = JSON.stringify(encryptedBody);\n\n if (ctx.request) {\n ctx.request.body = encryptedBody;\n }\n } catch (error) {\n if (failClosed) {\n throw toMiddlewareError(\n \"Encryption middleware request encryption failed\",\n error,\n );\n }\n\n console.error(\"Encryption middleware request encryption failed.\", error);\n }\n }\n\n const response = await next();\n\n if (!encryption.response) {\n return response;\n }\n\n try {\n const text = await response.clone().text();\n if (!text) return response;\n\n const parsedResponse = JSON.parse(text);\n\n const decryptedPayload = await processDeep(\n parsedResponse,\n encryption.response,\n responseMethod,\n async (value, method) => {\n if (typeof value !== \"string\") return value;\n\n const decrypted = await decryptValue(\n value,\n method,\n keyMaterial,\n customHandlers,\n );\n\n return safeJsonParse(decrypted);\n },\n );\n\n return new Response(JSON.stringify(decryptedPayload), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } catch (error) {\n if (failClosed) {\n throw toMiddlewareError(\n \"Encryption middleware response decryption failed\",\n error,\n );\n }\n\n console.error(\"Encryption middleware response decryption failed.\", error);\n return response;\n }\n};\n","import { z } from \"zod\";\n\ntype OptionalUndefinedBody<T extends z.ZodTypeAny> = T extends z.ZodUndefined\n ? z.ZodOptional<T>\n : T;\n\nexport const makeRequestSchema =\n <\n TPath extends z.ZodRawShape = {},\n TQuery extends z.ZodRawShape = {},\n TBody extends z.ZodTypeAny = z.ZodUndefined,\n THeaders extends z.ZodTypeAny = z.ZodOptional<\n z.ZodRecord<z.ZodString, z.ZodString>\n >,\n >() =>\n (\n defs: {\n path?: z.ZodObject<TPath>;\n query?: z.ZodObject<TQuery>;\n body?: TBody;\n headers?: THeaders;\n } = {},\n ) => {\n const pathSchema = (defs.path ??\n z.object({})) as unknown as z.ZodObject<TPath>;\n\n const querySchema = (defs.query ??\n z.object({})) as unknown as z.ZodObject<TQuery>;\n\n const rawBodySchema = (defs.body ?? z.undefined()) as TBody;\n\n const bodySchema = (\n defs.body ? rawBodySchema : rawBodySchema.optional()\n ) as OptionalUndefinedBody<TBody>;\n\n const headersSchema = (defs.headers ??\n z.record(z.string(), z.string()).optional()) as THeaders;\n\n return z.object({\n path: pathSchema.optional(),\n query: querySchema.optional(),\n body: bodySchema,\n headers: headersSchema,\n });\n };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACAA,iBAAkB;AAaX,IAAM,YAAN,cAAwB,MAA2B;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,OAAiD;AAC3D,UAAM,MAAM,OAAO;AACnB,WAAO,OAAO,MAAM,KAAK;AAAA,EAC3B;AACF;AAUA,IAAM,oBAAoB,oBAAI,IAAI;AAAA,EAChC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,CAAC;AAEM,IAAM,YAAN,MAAsE;AAAA,EAiB3E,YACU,QAOA,WACR;AARQ;AAOA;AAER,SAAK,cAAc,OAAO,eAAe;AACzC,SAAK,YAAY,OAAO,aAAa,EAAE,KAAK,KAAK,K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;AAEb,QAAM,cAAe,KAAK,SACxB,cAAE,OAAO,CAAC,CAAC;AAEb,QAAM,gBAAiB,KAAK,QAAQ,cAAE,UAAU;AAEhD,QAAM,aACJ,KAAK,OAAO,gBAAgB,cAAc,SAAS;AAGrD,QAAM,gBAAiB,KAAK,WAC1B,cAAE,OAAO,cAAE,OAAO,GAAG,cAAE,OAAO,CAAC,EAAE,SAAS;AAE5C,SAAO,cAAE,OAAO;AAAA,IACd,MAAM,WAAW,SAAS;AAAA,IAC1B,OAAO,YAAY,SAAS;AAAA,IAC5B,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AACH;","names":["module","CryptoJS","forge","import_zod"]}
package/dist/index.mjs CHANGED
@@ -336,7 +336,7 @@ var ApiClient = class {
336
336
  if (err instanceof RichError) return err;
337
337
  if (err instanceof z.ZodError) {
338
338
  return this.createError({
339
- message: `Validation error: ${err.errors.map((e) => e.message).join(", ")}`,
339
+ message: `Validation error: ${err.issues.map((e) => e.message).join(", ")}`,
340
340
  code: "VALIDATION_ERROR"
341
341
  });
342
342
  }
@@ -678,12 +678,19 @@ var encryptionMiddleware = async (ctx, next, options) => {
678
678
 
679
679
  // src/utils/make-request-schema.ts
680
680
  import { z as z2 } from "zod";
681
- var makeRequestSchema = () => (defs = {}) => z2.object({
682
- path: (defs.path ?? z2.object({})).optional(),
683
- query: (defs.query ?? z2.object({})).optional(),
684
- body: defs.body ?? z2.undefined(),
685
- headers: defs.headers ?? z2.record(z2.string()).optional()
686
- });
681
+ var makeRequestSchema = () => (defs = {}) => {
682
+ const pathSchema = defs.path ?? z2.object({});
683
+ const querySchema = defs.query ?? z2.object({});
684
+ const rawBodySchema = defs.body ?? z2.undefined();
685
+ const bodySchema = defs.body ? rawBodySchema : rawBodySchema.optional();
686
+ const headersSchema = defs.headers ?? z2.record(z2.string(), z2.string()).optional();
687
+ return z2.object({
688
+ path: pathSchema.optional(),
689
+ query: querySchema.optional(),
690
+ body: bodySchema,
691
+ headers: headersSchema
692
+ });
693
+ };
687
694
  export {
688
695
  ApiClient,
689
696
  RichError,
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/client.ts","../src/middlewares/logging.ts","../src/middlewares/retry.ts","../src/middlewares/auth.ts","../src/middlewares/cache.ts","../src/middlewares/encryption.ts","../src/utils/make-request-schema.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n Contracts,\n EndpointDef,\n EndpointDefZ,\n Middleware,\n ErrorLike,\n EndpointMethods,\n TokenProvider,\n RequestOptions,\n MiddlewareContext,\n} from \"./types\";\n\nexport class RichError extends Error implements ErrorLike {\n status?: number;\n code?: string;\n title?: string;\n detail?: string;\n errors?: Record<string, string[]>;\n\n constructor(error: Partial<ErrorLike> & { message: string }) {\n super(error.message);\n Object.assign(this, error);\n }\n}\n\ntype ParsedRequestParts = {\n path?: Record<string, any>;\n query?: Record<string, any>;\n body?: any;\n headers: Record<string, string>;\n isStructured: boolean;\n};\n\nconst REQUEST_PART_KEYS = new Set([\n \"path\",\n \"query\",\n \"body\",\n \"headers\",\n \"header\",\n]);\n\nexport class ApiClient<C extends Contracts, E extends ErrorLike = RichError> {\n private middlewares: Array<{ fn: Middleware; options?: any }> = [];\n private errorHandler?: (error: E) => void;\n private responseTransform: (data: any) => any = (d) => d;\n private useMockData = false;\n private mockDelay = { min: 100, max: 1000 };\n private responseWrapper?: (successResponse: z.ZodTypeAny) => z.ZodTypeAny;\n private tokenProvider?: TokenProvider;\n\n private retryConfig?: {\n maxRetries: number;\n backoff: \"fixed\" | \"linear\" | \"exponential\";\n retryCondition?: (error: RichError, attempt: number) => boolean;\n };\n\n private _modules!: { [M in keyof C]: EndpointMethods<C[M]> };\n\n constructor(\n private config: {\n baseUrl: string;\n token?: string;\n tokenProvider?: TokenProvider;\n useMockData?: boolean;\n mockDelay?: { min: number; max: number };\n },\n private contracts: C,\n ) {\n this.useMockData = config.useMockData || false;\n this.mockDelay = config.mockDelay || { min: 100, max: 1000 };\n this.tokenProvider = config.tokenProvider;\n }\n\n init() {\n const modules = {} as { [M in keyof C]: EndpointMethods<C[M]> };\n\n for (const moduleName in this.contracts) {\n const module = this.contracts[moduleName];\n (modules as any)[moduleName] = {} as EndpointMethods<typeof module>;\n\n for (const endpointName in module) {\n const endpoint = module[endpointName] as EndpointDefZ;\n\n (modules as any)[moduleName][endpointName] = (\n input: any,\n options?: RequestOptions,\n ) => this.request(endpoint as any, input, options);\n }\n }\n\n this._modules = modules;\n }\n\n get modules() {\n return this._modules;\n }\n\n use<T>(middleware: Middleware<any, any, T>, options?: T) {\n this.middlewares.push({ fn: middleware, options });\n }\n\n onError(handler: (error: E) => void) {\n this.errorHandler = handler;\n }\n\n useResponseTransform(fn: (data: any) => any) {\n this.responseTransform = fn;\n }\n\n setRetryConfig(config: ApiClient<C>[\"retryConfig\"]) {\n this.retryConfig = config;\n }\n\n setTokenProvider(provider: TokenProvider) {\n this.tokenProvider = provider;\n }\n\n setMockMode(enabled: boolean, delay?: { min: number; max: number }) {\n this.useMockData = enabled;\n if (delay) this.mockDelay = delay;\n }\n\n setResponseWrapper(wrapper: (successResponse: z.ZodTypeAny) => z.ZodTypeAny) {\n this.responseWrapper = wrapper;\n }\n\n async getCurrentToken(): Promise<string | undefined> {\n if (this.tokenProvider) return await this.tokenProvider();\n return this.config.token;\n }\n\n private async request<TReq extends z.ZodTypeAny, TRes extends z.ZodTypeAny>(\n endpoint: EndpointDef<TReq, TRes>,\n input: z.infer<TReq>,\n options?: RequestOptions,\n ): Promise<z.infer<TRes>> {\n const parsedInput = endpoint.request.parse(input);\n\n if (this.useMockData && endpoint.mockData) {\n return this.handleMockRequest(endpoint);\n }\n\n const built = this.buildUrlAndBody(endpoint as EndpointDefZ, parsedInput);\n\n return this.performRequestLogic(\n endpoint,\n parsedInput,\n built.url,\n built.body,\n built.headers,\n built.parts,\n options,\n );\n }\n\n private async performRequestLogic<\n TReq extends z.ZodTypeAny,\n TRes extends z.ZodTypeAny,\n >(\n endpoint: EndpointDef<TReq, TRes>,\n parsedInput: z.infer<TReq>,\n url: string,\n body: BodyInit | undefined,\n requestHeaders: Record<string, string>,\n requestParts: ParsedRequestParts,\n options?: RequestOptions,\n ): Promise<z.infer<TRes>> {\n const headers: Record<string, string> = {};\n\n if (endpoint.bodyType !== \"form-data\") {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n const endpointHeaders =\n typeof endpoint.headers === \"function\"\n ? endpoint.headers(parsedInput)\n : endpoint.headers;\n\n Object.assign(\n headers,\n this.normalizeHeaders(endpointHeaders),\n requestHeaders,\n );\n\n if (endpoint.auth) {\n const token = await this.getCurrentToken();\n\n if (!token) {\n const error = this.createError({\n message: `Missing token for ${endpoint.path}`,\n status: 401,\n code: \"NO_TOKEN\",\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n\n const ctx = {\n url,\n init: { method: endpoint.method, headers, body } as RequestInit,\n endpoint: endpoint as never,\n request: {\n ...requestParts,\n rawInput: parsedInput,\n },\n } satisfies MiddlewareContext;\n\n let controller: AbortController | undefined;\n let timeoutId: any;\n\n if (options?.timeout) {\n controller = new AbortController();\n timeoutId = setTimeout(() => controller!.abort(), options.timeout);\n }\n\n if (options?.signal || controller) {\n ctx.init.signal = options?.signal || controller?.signal;\n }\n\n const runner = this.middlewares.reduceRight(\n (next, mw) => () => mw.fn(ctx, next, mw.options),\n () => fetch(ctx.url, ctx.init),\n );\n\n const execute = async () => {\n const res = await runner();\n const json = await res.json();\n let responseData = json;\n\n if (this.responseWrapper) {\n const wrappedSchema = this.responseWrapper(endpoint.response);\n const parsedWrapped = wrappedSchema.parse(json);\n\n if (parsedWrapped.success === false) {\n const error = this.createError({\n message:\n parsedWrapped.message || parsedWrapped.error || \"Request failed\",\n status: parsedWrapped.code || res.status,\n code: parsedWrapped.code\n ? `API_ERROR_${parsedWrapped.code}`\n : \"API_ERROR\",\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n responseData = parsedWrapped.data;\n }\n\n if (!res.ok) {\n const error = this.createError({\n message: json.message || res.statusText,\n status: res.status,\n code: json.code,\n title: json.title,\n detail: json.detail,\n errors: json.errors,\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n const parsed = endpoint.response.parse(responseData);\n return this.responseTransform(parsed);\n };\n\n try {\n const result = await this.executeWithRetry(execute);\n if (timeoutId) clearTimeout(timeoutId);\n return result;\n } catch (err: any) {\n if (timeoutId) clearTimeout(timeoutId);\n const error = this.normalizeError(err);\n this.errorHandler?.(error as any);\n throw error;\n }\n }\n\n private async executeWithRetry(fn: () => Promise<any>): Promise<any> {\n if (!this.retryConfig) return fn();\n\n const { maxRetries, backoff, retryCondition } = this.retryConfig;\n let attempt = 0;\n\n while (true) {\n try {\n return await fn();\n } catch (err: any) {\n attempt++;\n const error = this.normalizeError(err);\n\n const shouldRetry =\n attempt <= maxRetries &&\n (retryCondition?.(error, attempt) ??\n (error.status !== undefined && error.status >= 500));\n\n if (!shouldRetry) throw error;\n\n const delay = this.getBackoffDelay(backoff, attempt);\n await new Promise((r) => setTimeout(r, delay));\n }\n }\n }\n\n private getBackoffDelay(\n type: \"fixed\" | \"linear\" | \"exponential\",\n attempt: number,\n ) {\n const base = 300;\n switch (type) {\n case \"fixed\":\n return base;\n case \"linear\":\n return base * attempt;\n case \"exponential\":\n return base * Math.pow(2, attempt - 1);\n }\n }\n\n private buildUrlAndBody(endpoint: EndpointDefZ, input: any) {\n const parts = this.extractRequestParts(input);\n\n let url = this.config.baseUrl + endpoint.path;\n url = this.applyPathParams(url, parts.path);\n url = this.appendQueryParams(url, parts.query);\n\n let body: BodyInit | undefined;\n const payload = parts.isStructured ? parts.body : input;\n\n if (endpoint.method !== \"GET\" && payload !== undefined) {\n if (endpoint.bodyType === \"form-data\") {\n if (typeof FormData !== \"undefined\" && payload instanceof FormData) {\n body = payload;\n } else {\n const form = new FormData();\n\n if (this.isObjectRecord(payload)) {\n for (const [key, value] of Object.entries(payload)) {\n this.appendFormValue(form, key, value);\n }\n } else if (payload != null) {\n form.append(\"value\", String(payload));\n }\n\n body = form;\n }\n } else {\n body = JSON.stringify(payload);\n }\n }\n\n return { url, body, headers: parts.headers, parts };\n }\n\n private extractRequestParts(input: any): ParsedRequestParts {\n if (this.isStructuredRequestInput(input)) {\n return {\n path: this.isObjectRecord(input.path) ? input.path : undefined,\n query: this.isObjectRecord(input.query) ? input.query : undefined,\n body: input.body,\n headers: this.normalizeHeaders(input.headers ?? input.header),\n isStructured: true,\n };\n }\n\n return {\n body: input,\n headers: {},\n isStructured: false,\n };\n }\n\n private isStructuredRequestInput(\n input: unknown,\n ): input is Record<string, any> {\n if (!this.isObjectRecord(input)) return false;\n\n const keys = Object.keys(input);\n if (keys.length === 0) return false;\n\n return (\n keys.some((key) => REQUEST_PART_KEYS.has(key)) &&\n keys.every((key) => REQUEST_PART_KEYS.has(key))\n );\n }\n\n private isObjectRecord(value: unknown): value is Record<string, any> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n\n private applyPathParams(\n url: string,\n pathParams?: Record<string, any>,\n ): string {\n return url.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = pathParams?.[key];\n\n if (value === undefined || value === null) {\n throw this.createError({\n message: `Missing path param \"${key}\"`,\n code: \"MISSING_PATH_PARAM\",\n });\n }\n\n return encodeURIComponent(String(value));\n });\n }\n\n private appendQueryParams(url: string, query?: Record<string, any>): string {\n if (!query) return url;\n\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(query)) {\n this.appendQueryValue(params, key, value);\n }\n\n const queryString = params.toString();\n if (!queryString) return url;\n\n return `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${queryString}`;\n }\n\n private appendQueryValue(params: URLSearchParams, key: string, value: any) {\n if (value === undefined || value === null) return;\n\n if (Array.isArray(value)) {\n for (const item of value) this.appendQueryValue(params, key, item);\n return;\n }\n\n if (value instanceof Date) {\n params.append(key, value.toISOString());\n return;\n }\n\n if (typeof value === \"object\") {\n params.append(key, JSON.stringify(value));\n return;\n }\n\n params.append(key, String(value));\n }\n\n private appendFormValue(form: FormData, key: string, value: any) {\n if (value === undefined || value === null) return;\n\n if (Array.isArray(value)) {\n for (const item of value) this.appendFormValue(form, key, item);\n return;\n }\n\n if (value instanceof Date) {\n form.append(key, value.toISOString());\n return;\n }\n\n const isBlob = typeof Blob !== \"undefined\" && value instanceof Blob;\n\n if (typeof value === \"object\" && !isBlob) {\n form.append(key, JSON.stringify(value));\n return;\n }\n\n form.append(key, value as any);\n }\n\n private normalizeHeaders(headers: unknown): Record<string, string> {\n if (!this.isObjectRecord(headers)) return {};\n\n const normalized: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined || value === null) continue;\n normalized[key] = String(value);\n }\n\n return normalized;\n }\n\n private createError(error: Partial<RichError> & { message: string }) {\n return new RichError(error);\n }\n\n private normalizeError(err: any) {\n if (err instanceof RichError) return err;\n if (err instanceof z.ZodError) {\n return this.createError({\n message: `Validation error: ${err.errors.map((e) => e.message).join(\", \")}`,\n code: \"VALIDATION_ERROR\",\n });\n }\n return this.createError({ message: err.message || \"Unknown error\" });\n }\n\n private async handleMockRequest(endpoint: any) {\n const delay =\n Math.floor(\n Math.random() * (this.mockDelay.max - this.mockDelay.min + 1),\n ) + this.mockDelay.min;\n\n await new Promise((r) => setTimeout(r, delay));\n\n const data =\n typeof endpoint.mockData === \"function\"\n ? endpoint.mockData()\n : endpoint.mockData;\n\n return this.responseTransform(endpoint.response.parse(data));\n }\n}\n","import { Middleware } from \"@/types\";\nimport z from \"zod\";\n\nexport type LoggingOptions = {\n logRequest?: boolean;\n logResponse?: boolean;\n debug?: boolean;\n};\n\nexport const loggingMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n LoggingOptions\n> = async (ctx, next, options) => {\n const { logRequest = true, logResponse = true, debug = true } = options || {};\n\n if (debug && logRequest) console.log(\"➡️ Request:\", ctx.url, ctx.init);\n\n const res = await next();\n\n if (debug && logResponse) console.log(\"⬅️ Response:\", res.status);\n\n return res;\n};\n","import { Middleware } from \"@/types\";\n\n\nexport type RetryOptions = {\n maxRetries?: number;\n delay?: number; // ms\n};\n\nexport const retryMiddleware = (options?: RetryOptions): Middleware => {\n const { maxRetries = 3, delay = 500 } = options || {};\n\n const middleware: Middleware = async (ctx, next) => {\n let attempt = 0;\n while (true) {\n try {\n return await next();\n } catch (err) {\n if (attempt >= maxRetries) throw err;\n attempt++;\n await new Promise((r) => setTimeout(r, delay * 2 ** attempt));\n }\n }\n };\n\n return middleware;\n};\n","import { Middleware } from \"@/types\";\nimport z from \"zod\";\n\n/**\n * TokenManagementOptions\n * ======================\n * Configuration structure for supplying credentials to the authentication layer.\n *\n * @property refreshToken A required asynchronous function responsible for\n * obtaining a current, valid access token string. This allows\n * for token fetching from storage or re-issuance upon expiry.\n */\nexport type AuthOptions = {\n refreshToken?: () => Promise<string>;\n};\n\n/**\n * AuthenticationInjectorMiddleware\n * ==================================\n * This middleware operates early in the request pipeline to ensure every\n * outgoing request is properly authorized by prepending an Authorization header.\n *\n * Core Logic:\n * -----------\n * 1. It checks if an explicit `refreshToken` supplier was configured in its options.\n * 2. If present, it synchronously calls this supplier to obtain the latest token.\n * 3. The resulting token is formatted as a standard 'Bearer' token and merged\n * into the request's `init.headers`.\n * 4. The request context (`ctx`) is then passed downstream.\n *\n * Note on Error Handling:\n * -----------------------\n * Any failure during the token retrieval process (e.g., if `refreshToken` throws)\n * results in the error being caught, and the request proceeds **without** an\n * Authorization header. This design defers failure response handling to\n * subsequent middleware or the final network fetcher.\n *\n * @param ctx The current request context object, including mutable `init` properties.\n * @param next The function to execute the rest of the middleware chain.\n * @param options The specific configuration passed to this middleware instance.\n *\n * @returns The final `Response` object after the network call completes.\n *\n * @example\n * // Assuming token retrieval logic is defined elsewhere\n * const tokenSupplier = () => fetchTokenFromSecureStorage();\n *\n * client.addInterceptor(\n * authMiddleware({ refreshToken: tokenSupplier })\n * );\n */\nexport const authMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n AuthOptions\n> = async (ctx, next, options) => {\n // Step 1 & 2: Check for and execute the token provider\n if (options?.refreshToken) {\n try {\n const newToken = await options.refreshToken();\n\n // Step 3: Mutate the context's request initialization object\n ctx.init.headers = {\n ...ctx.init.headers, // Preserve any headers set by prior middleware\n Authorization: `Bearer ${newToken}`,\n };\n } catch (error) {\n // Step 4: Fail silently for header injection purposes\n // The request will proceed unauthenticated if the token failed to load\n console.warn(\n \"Authentication token refresh failed, proceeding without authorization header.\",\n error,\n );\n }\n }\n\n // Step 5: Pass control to the next step in the request pipeline\n return next();\n};\n","import { MiddlewareContext, MiddlewareNext } from \"@/types\";\n\n/**\n * CacheOptions\n * ============\n * Options for configuring the cache middleware.\n * - `ttl` (Time To Live): Duration (in milliseconds) to keep cached GET responses.\n * After this time, cached data expires and a fresh network call is performed.\n */\nexport type CacheOptions = { ttl?: number };\n\n/**\n * cacheMiddleware\n * ===============\n * A generic caching middleware for GET requests in the ApiClient.\n * It stores successful responses in memory based on URL and method,\n * returning cached data for subsequent identical requests until the TTL expires.\n *\n * Purpose:\n * --------\n * - Reduces redundant network calls\n * - Improves performance for frequently fetched resources\n * - Useful for lightweight front-end caching (not suitable for sensitive data)\n *\n * Behavior:\n * ---------\n * 1. Only applies to `GET` requests; all other HTTP methods bypass caching.\n * 2. Caches the parsed JSON response in a simple in-memory Map.\n * 3. On subsequent requests:\n * - If the cache entry exists and hasn’t expired, returns a synthetic\n * `Response` object built from cached JSON.\n * - Otherwise performs the network call and refreshes the cache.\n *\n * @param options - Optional cache configuration (TTL in ms)\n *\n * @returns Middleware function compatible with the ApiClient pipeline.\n *\n * @example\n * client.use(\n * cacheMiddleware({ ttl: 120000 }) // cache GET results for 2 minutes\n * );\n *\n * @note Each middleware instance maintains its own internal cache\n * and is memory-scoped (not persistent between reloads).\n */\nexport const cacheMiddleware = (options: CacheOptions = {}) => {\n // Default TTL = 60 seconds, unless overridden\n const { ttl = 60000 } = options;\n\n /**\n * Internal cache store.\n * Keys are composed as `\"METHOD:URL\"`.\n * Values include cached response data and expiration timestamp.\n */\n const cache = new Map<string, { data: any; expires: number }>();\n\n // Return an asynchronous middleware function conforming to the standard signature\n return async (ctx: MiddlewareContext, next: MiddlewareNext) => {\n // Caching only applies to GET requests\n if (ctx.init.method === \"GET\") {\n const key = `${ctx.init.method}:${ctx.url}`;\n const cached = cache.get(key);\n const now = Date.now();\n\n // Check if valid cached response exists and hasn't expired\n if (cached && cached.expires > now) {\n // Return a new synthetic Response containing cached data\n return new Response(JSON.stringify(cached.data), {\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n // Perform the actual network request via the next middleware/fetcher\n const res = await next();\n\n // Attempt to read JSON data from the response (clone avoids stream lock)\n const data = await res\n .clone()\n .json()\n .catch(() => null);\n\n // Store parsed data with expiration if successfully obtained\n if (data) {\n cache.set(key, { data, expires: now + ttl });\n }\n\n // Return original response to caller\n return res;\n }\n\n // For all non‑GET requests, just forward the call with no caching logic\n return next();\n };\n};\n","import type { Middleware, DeepEncryptionMap, EncryptionMethod } from \"@/types\";\nimport CryptoJS from \"crypto-js\";\nimport forge from \"node-forge\";\nimport { z } from \"zod\";\n\ntype SymmetricKeyMaterial = {\n type: \"symmetric\";\n key: string;\n};\n\ntype RSAKeyMaterial = {\n type: \"rsa\";\n publicKey: string;\n privateKey: string;\n};\n\ntype KeyMaterial = SymmetricKeyMaterial | RSAKeyMaterial;\n\ntype CustomHandlers = {\n encrypt: (value: string, key: KeyMaterial) => string | Promise<string>;\n decrypt: (value: string, key: KeyMaterial) => string | Promise<string>;\n};\n\nexport interface EncryptionOptions {\n keyProvider: () => KeyMaterial | Promise<KeyMaterial>;\n customHandlers?: CustomHandlers;\n\n /**\n * true = throw when encryption/decryption fails, which avoids leaking plaintext.\n * false = log and continue/fallback to the original response.\n * Default: true\n */\n failClosed?: boolean;\n}\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasKey(value: unknown, key: string): value is Record<string, unknown> {\n return (\n isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, key)\n );\n}\n\nfunction toMiddlewareError(message: string, error: unknown): Error {\n const err = new Error(\n `${message}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n (err as any).cause = error;\n return err;\n}\n\nfunction encryptWithAES(value: string, key: string): string {\n return CryptoJS.AES.encrypt(value, key).toString();\n}\n\nfunction decryptWithAES(value: string, key: string): string {\n const bytes = CryptoJS.AES.decrypt(value, key);\n return bytes.toString(CryptoJS.enc.Utf8);\n}\n\nfunction encryptWithDES(value: string, key: string): string {\n return CryptoJS.DES.encrypt(value, key).toString();\n}\n\nfunction decryptWithDES(value: string, key: string): string {\n const bytes = CryptoJS.DES.decrypt(value, key);\n return bytes.toString(CryptoJS.enc.Utf8);\n}\n\nfunction encodeWithBase64(value: string): string {\n return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(value));\n}\n\nfunction decodeWithBase64(value: string): string {\n return CryptoJS.enc.Base64.parse(value).toString(CryptoJS.enc.Utf8);\n}\n\nfunction encryptWithRSA(value: string, publicKey: string): string {\n const publicKeyObject = forge.pki.publicKeyFromPem(publicKey);\n const encrypted = publicKeyObject.encrypt(\n forge.util.encodeUtf8(value),\n \"RSA-OAEP\",\n );\n return forge.util.encode64(encrypted);\n}\n\nfunction decryptWithRSA(value: string, privateKey: string): string {\n const privateKeyObject = forge.pki.privateKeyFromPem(privateKey);\n const decrypted = privateKeyObject.decrypt(\n forge.util.decode64(value),\n \"RSA-OAEP\",\n );\n return forge.util.decodeUtf8(decrypted);\n}\n\nasync function encryptValue(\n value: string,\n method: EncryptionMethod,\n keyMaterial: KeyMaterial,\n customHandlers?: CustomHandlers,\n): Promise<string> {\n switch (method) {\n case \"AES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"AES encryption requires symmetric key material.\");\n }\n return encryptWithAES(value, keyMaterial.key);\n }\n\n case \"DES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"DES encryption requires symmetric key material.\");\n }\n return encryptWithDES(value, keyMaterial.key);\n }\n\n case \"Base64\": {\n return encodeWithBase64(value);\n }\n\n case \"RSA\": {\n if (keyMaterial.type !== \"rsa\") {\n throw new Error(\"RSA encryption requires RSA key material.\");\n }\n return encryptWithRSA(value, keyMaterial.publicKey);\n }\n\n case \"Custom\": {\n if (!customHandlers) {\n throw new Error(\"Custom encryption requires custom handlers.\");\n }\n return await customHandlers.encrypt(value, keyMaterial);\n }\n\n default: {\n const exhaustiveCheck: never = method;\n throw new Error(`Unsupported encryption method: ${exhaustiveCheck}`);\n }\n }\n}\n\nasync function decryptValue(\n value: string,\n method: EncryptionMethod,\n keyMaterial: KeyMaterial,\n customHandlers?: CustomHandlers,\n): Promise<string> {\n switch (method) {\n case \"AES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"AES decryption requires symmetric key material.\");\n }\n return decryptWithAES(value, keyMaterial.key);\n }\n\n case \"DES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"DES decryption requires symmetric key material.\");\n }\n return decryptWithDES(value, keyMaterial.key);\n }\n\n case \"Base64\": {\n return decodeWithBase64(value);\n }\n\n case \"RSA\": {\n if (keyMaterial.type !== \"rsa\") {\n throw new Error(\"RSA decryption requires RSA key material.\");\n }\n return decryptWithRSA(value, keyMaterial.privateKey);\n }\n\n case \"Custom\": {\n if (!customHandlers) {\n throw new Error(\"Custom decryption requires custom handlers.\");\n }\n return await customHandlers.decrypt(value, keyMaterial);\n }\n\n default: {\n const exhaustiveCheck: never = method;\n throw new Error(`Unsupported decryption method: ${exhaustiveCheck}`);\n }\n }\n}\n\nexport async function processDeep<T = unknown>(\n data: unknown,\n map: DeepEncryptionMap | null | undefined,\n defaultMethod: EncryptionMethod,\n transform: (value: unknown, method: EncryptionMethod) => Promise<unknown>,\n): Promise<T> {\n if (data == null || map == null) return data as T;\n\n if (typeof map === \"string\") return (await transform(data, map)) as T;\n\n if (typeof map === \"boolean\") {\n return (map ? await transform(data, defaultMethod) : data) as T;\n }\n\n if (Array.isArray(data)) {\n if (!Array.isArray(map)) {\n return Promise.all(\n data.map((item) => processDeep(item, map, defaultMethod, transform)),\n ) as Promise<T>;\n }\n\n return Promise.all(\n data.map((item, idx) =>\n processDeep(item, map[idx] ?? map[0], defaultMethod, transform),\n ),\n ) as Promise<T>;\n }\n\n if (isPlainObject(data) && isPlainObject(map)) {\n const result: Record<string, unknown> = { ...data };\n\n for (const key of Object.keys(map)) {\n const childMap = (map as Record<string, DeepEncryptionMap>)[key];\n if (childMap == null) continue;\n\n const currentVal = result[key];\n if (currentVal !== undefined) {\n result[key] = await processDeep(\n currentVal,\n childMap,\n defaultMethod,\n transform,\n );\n }\n }\n\n return result as T;\n }\n\n return data as T;\n}\n\nfunction getRequestBodyMap(map: DeepEncryptionMap): DeepEncryptionMap {\n // Supports both styles:\n // encryption.request: { password: true }\n // encryption.request: { body: { password: true } }\n if (hasKey(map, \"body\")) {\n return map.body as DeepEncryptionMap;\n }\n\n return map;\n}\n\nexport const encryptionMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n EncryptionOptions\n> = async (ctx, next, options) => {\n if (!options) {\n throw new Error(\"Encryption middleware options were not provided.\");\n }\n\n const { keyProvider, customHandlers } = options;\n const failClosed = options.failClosed ?? true;\n const encryption = ctx.endpoint.encryption;\n\n if (!encryption || (!encryption.request && !encryption.response)) {\n return next();\n }\n\n const requestMethod: EncryptionMethod =\n typeof encryption.method === \"string\"\n ? encryption.method\n : (encryption.method?.request ?? \"AES\");\n\n const responseMethod: EncryptionMethod =\n typeof encryption.method === \"string\"\n ? encryption.method\n : (encryption.method?.response ?? \"AES\");\n\n const keyMaterial = await keyProvider();\n\n if (\n encryption.request &&\n typeof ctx.init.body === \"string\" &&\n ctx.init.body.length > 0\n ) {\n try {\n const parsedBody = JSON.parse(ctx.init.body);\n const bodyMap = getRequestBodyMap(encryption.request);\n\n const encryptedBody = await processDeep(\n parsedBody,\n bodyMap,\n requestMethod,\n async (value, method) => {\n const serialized =\n typeof value === \"string\" ? value : JSON.stringify(value);\n\n return encryptValue(serialized, method, keyMaterial, customHandlers);\n },\n );\n\n ctx.init.body = JSON.stringify(encryptedBody);\n\n if (ctx.request) {\n ctx.request.body = encryptedBody;\n }\n } catch (error) {\n if (failClosed) {\n throw toMiddlewareError(\n \"Encryption middleware request encryption failed\",\n error,\n );\n }\n\n console.error(\"Encryption middleware request encryption failed.\", error);\n }\n }\n\n const response = await next();\n\n if (!encryption.response) {\n return response;\n }\n\n try {\n const text = await response.clone().text();\n if (!text) return response;\n\n const parsedResponse = JSON.parse(text);\n\n const decryptedPayload = await processDeep(\n parsedResponse,\n encryption.response,\n responseMethod,\n async (value, method) => {\n if (typeof value !== \"string\") return value;\n\n const decrypted = await decryptValue(\n value,\n method,\n keyMaterial,\n customHandlers,\n );\n\n return safeJsonParse(decrypted);\n },\n );\n\n return new Response(JSON.stringify(decryptedPayload), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } catch (error) {\n if (failClosed) {\n throw toMiddlewareError(\n \"Encryption middleware response decryption failed\",\n error,\n );\n }\n\n console.error(\"Encryption middleware response decryption failed.\", error);\n return response;\n }\n};\n","import { z } from \"zod\";\n\nexport const makeRequestSchema =\n <\n TPath extends z.ZodRawShape = {},\n TQuery extends z.ZodRawShape = {},\n TBody extends z.ZodTypeAny = z.ZodUndefined,\n >() =>\n (\n defs: {\n path?: z.ZodObject<TPath>;\n query?: z.ZodObject<TQuery>;\n body?: TBody;\n headers?: z.ZodTypeAny;\n } = {},\n ) =>\n z.object({\n path: (defs.path ?? z.object({})).optional(),\n query: (defs.query ?? z.object({})).optional(),\n body: (defs.body ?? z.undefined()) as TBody | z.ZodU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GAAG;AAAA,MACpD,QAAQ,SAAS;AAAA,MACjB,YAAY,SAAS;AAAA,MACrB,SAAS,SAAS;AAAA,IACpB,CAAC;AAAA,EACH,SAAS,OAAO;AACd,QAAI,YAAY;AACd,YAAM;AAAA,QACJ;AAAA,QACA;AAAA,MACF;AAAA,IACF;AAEA,YAAQ,MAAM,qDAAqD,KAAK;AACxE,WAAO;AAAA,EACT;AACF;;;AC1XA,SAAS,KAAAA,UAAS;AAEX,IAAM,oBACX,MAKA,CACE,OAKI,CAAC,MAELA,GAAE,OAAO;AAAA,EACP,OAAO,KAAK,QAAQA,GAAE,OAAO,CAAC,CAAC,GAAG,SAAS;AAAA,EAC3C,QAAQ,KAAK,SAASA,GAAE,OAAO,CAAC,CAAC,GAAG,SAAS;AAAA,EAC7C,MAAO,KAAK,QAAQA,GAAE,UAAU;AAAA,EAChC,SAAU,KAAK,WAAWA,GAAE,OAAOA,GAAE,OAAO,CAAC,EAAE,SAAS;AAC1D,CAAC;","names":["z"]}
1
+ {"version":3,"sources":["../src/client.ts","../src/middlewares/logging.ts","../src/middlewares/retry.ts","../src/middlewares/auth.ts","../src/middlewares/cache.ts","../src/middlewares/encryption.ts","../src/utils/make-request-schema.ts"],"sourcesContent":["import { z } from \"zod\";\nimport {\n Contracts,\n EndpointDef,\n EndpointDefZ,\n Middleware,\n ErrorLike,\n EndpointMethods,\n TokenProvider,\n RequestOptions,\n MiddlewareContext,\n} from \"./types\";\n\nexport class RichError extends Error implements ErrorLike {\n status?: number;\n code?: string;\n title?: string;\n detail?: string;\n errors?: Record<string, string[]>;\n\n constructor(error: Partial<ErrorLike> & { message: string }) {\n super(error.message);\n Object.assign(this, error);\n }\n}\n\ntype ParsedRequestParts = {\n path?: Record<string, any>;\n query?: Record<string, any>;\n body?: any;\n headers: Record<string, string>;\n isStructured: boolean;\n};\n\nconst REQUEST_PART_KEYS = new Set([\n \"path\",\n \"query\",\n \"body\",\n \"headers\",\n \"header\",\n]);\n\nexport class ApiClient<C extends Contracts, E extends ErrorLike = RichError> {\n private middlewares: Array<{ fn: Middleware; options?: any }> = [];\n private errorHandler?: (error: E) => void;\n private responseTransform: (data: any) => any = (d) => d;\n private useMockData = false;\n private mockDelay = { min: 100, max: 1000 };\n private responseWrapper?: (successResponse: z.ZodTypeAny) => z.ZodTypeAny;\n private tokenProvider?: TokenProvider;\n\n private retryConfig?: {\n maxRetries: number;\n backoff: \"fixed\" | \"linear\" | \"exponential\";\n retryCondition?: (error: RichError, attempt: number) => boolean;\n };\n\n private _modules!: { [M in keyof C]: EndpointMethods<C[M]> };\n\n constructor(\n private config: {\n baseUrl: string;\n token?: string;\n tokenProvider?: TokenProvider;\n useMockData?: boolean;\n mockDelay?: { min: number; max: number };\n },\n private contracts: C,\n ) {\n this.useMockData = config.useMockData || false;\n this.mockDelay = config.mockDelay || { min: 100, max: 1000 };\n this.tokenProvider = config.tokenProvider;\n }\n\n init() {\n const modules = {} as { [M in keyof C]: EndpointMethods<C[M]> };\n\n for (const moduleName in this.contracts) {\n const module = this.contracts[moduleName];\n (modules as any)[moduleName] = {} as EndpointMethods<typeof module>;\n\n for (const endpointName in module) {\n const endpoint = module[endpointName] as EndpointDefZ;\n\n (modules as any)[moduleName][endpointName] = (\n input: any,\n options?: RequestOptions,\n ) => this.request(endpoint as any, input, options);\n }\n }\n\n this._modules = modules;\n }\n\n get modules() {\n return this._modules;\n }\n\n use<T>(middleware: Middleware<any, any, T>, options?: T) {\n this.middlewares.push({ fn: middleware, options });\n }\n\n onError(handler: (error: E) => void) {\n this.errorHandler = handler;\n }\n\n useResponseTransform(fn: (data: any) => any) {\n this.responseTransform = fn;\n }\n\n setRetryConfig(config: ApiClient<C>[\"retryConfig\"]) {\n this.retryConfig = config;\n }\n\n setTokenProvider(provider: TokenProvider) {\n this.tokenProvider = provider;\n }\n\n setMockMode(enabled: boolean, delay?: { min: number; max: number }) {\n this.useMockData = enabled;\n if (delay) this.mockDelay = delay;\n }\n\n setResponseWrapper(wrapper: (successResponse: z.ZodTypeAny) => z.ZodTypeAny) {\n this.responseWrapper = wrapper;\n }\n\n async getCurrentToken(): Promise<string | undefined> {\n if (this.tokenProvider) return await this.tokenProvider();\n return this.config.token;\n }\n\n private async request<TReq extends z.ZodTypeAny, TRes extends z.ZodTypeAny>(\n endpoint: EndpointDef<TReq, TRes>,\n input: z.infer<TReq>,\n options?: RequestOptions,\n ): Promise<z.infer<TRes>> {\n const parsedInput = endpoint.request.parse(input);\n\n if (this.useMockData && endpoint.mockData) {\n return this.handleMockRequest(endpoint);\n }\n\n const built = this.buildUrlAndBody(endpoint as EndpointDefZ, parsedInput);\n\n return this.performRequestLogic(\n endpoint,\n parsedInput,\n built.url,\n built.body,\n built.headers,\n built.parts,\n options,\n );\n }\n\n private async performRequestLogic<\n TReq extends z.ZodTypeAny,\n TRes extends z.ZodTypeAny,\n >(\n endpoint: EndpointDef<TReq, TRes>,\n parsedInput: z.infer<TReq>,\n url: string,\n body: BodyInit | undefined,\n requestHeaders: Record<string, string>,\n requestParts: ParsedRequestParts,\n options?: RequestOptions,\n ): Promise<z.infer<TRes>> {\n const headers: Record<string, string> = {};\n\n if (endpoint.bodyType !== \"form-data\") {\n headers[\"Content-Type\"] = \"application/json\";\n }\n\n const endpointHeaders =\n typeof endpoint.headers === \"function\"\n ? endpoint.headers(parsedInput)\n : endpoint.headers;\n\n Object.assign(\n headers,\n this.normalizeHeaders(endpointHeaders),\n requestHeaders,\n );\n\n if (endpoint.auth) {\n const token = await this.getCurrentToken();\n\n if (!token) {\n const error = this.createError({\n message: `Missing token for ${endpoint.path}`,\n status: 401,\n code: \"NO_TOKEN\",\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n headers[\"Authorization\"] = `Bearer ${token}`;\n }\n\n const ctx = {\n url,\n init: { method: endpoint.method, headers, body } as RequestInit,\n endpoint: endpoint as never,\n request: {\n ...requestParts,\n rawInput: parsedInput,\n },\n } satisfies MiddlewareContext;\n\n let controller: AbortController | undefined;\n let timeoutId: any;\n\n if (options?.timeout) {\n controller = new AbortController();\n timeoutId = setTimeout(() => controller!.abort(), options.timeout);\n }\n\n if (options?.signal || controller) {\n ctx.init.signal = options?.signal || controller?.signal;\n }\n\n const runner = this.middlewares.reduceRight(\n (next, mw) => () => mw.fn(ctx, next, mw.options),\n () => fetch(ctx.url, ctx.init),\n );\n\n const execute = async () => {\n const res = await runner();\n const json = await res.json();\n let responseData = json;\n\n if (this.responseWrapper) {\n const wrappedSchema = this.responseWrapper(endpoint.response);\n const parsedWrapped = wrappedSchema.parse(json) as any;\n\n if (parsedWrapped.success === false) {\n const error = this.createError({\n message:\n parsedWrapped.message || parsedWrapped.error || \"Request failed\",\n status: parsedWrapped.code || res.status,\n code: parsedWrapped.code\n ? `API_ERROR_${parsedWrapped.code}`\n : \"API_ERROR\",\n });\n\n this.errorHandler?.(error as any);\n throw error;\n }\n\n responseData = parsedWrapped.data;\n }\n\n if (!res.ok) {\n const error = this.createError({\n message: json.message || res.statusText,\n status: res.status,\n code: json.code,\n title: json.title,\n detail: json.detail,\n errors: json.errors,\n });\n this.errorHandler?.(error as any);\n throw error;\n }\n\n const parsed = endpoint.response.parse(responseData);\n return this.responseTransform(parsed);\n };\n\n try {\n const result = await this.executeWithRetry(execute);\n if (timeoutId) clearTimeout(timeoutId);\n return result;\n } catch (err: any) {\n if (timeoutId) clearTimeout(timeoutId);\n const error = this.normalizeError(err);\n this.errorHandler?.(error as any);\n throw error;\n }\n }\n\n private async executeWithRetry(fn: () => Promise<any>): Promise<any> {\n if (!this.retryConfig) return fn();\n\n const { maxRetries, backoff, retryCondition } = this.retryConfig;\n let attempt = 0;\n\n while (true) {\n try {\n return await fn();\n } catch (err: any) {\n attempt++;\n const error = this.normalizeError(err);\n\n const shouldRetry =\n attempt <= maxRetries &&\n (retryCondition?.(error, attempt) ??\n (error.status !== undefined && error.status >= 500));\n\n if (!shouldRetry) throw error;\n\n const delay = this.getBackoffDelay(backoff, attempt);\n await new Promise((r) => setTimeout(r, delay));\n }\n }\n }\n\n private getBackoffDelay(\n type: \"fixed\" | \"linear\" | \"exponential\",\n attempt: number,\n ) {\n const base = 300;\n switch (type) {\n case \"fixed\":\n return base;\n case \"linear\":\n return base * attempt;\n case \"exponential\":\n return base * Math.pow(2, attempt - 1);\n }\n }\n\n private buildUrlAndBody(endpoint: EndpointDefZ, input: any) {\n const parts = this.extractRequestParts(input);\n\n let url = this.config.baseUrl + endpoint.path;\n url = this.applyPathParams(url, parts.path);\n url = this.appendQueryParams(url, parts.query);\n\n let body: BodyInit | undefined;\n const payload = parts.isStructured ? parts.body : input;\n\n if (endpoint.method !== \"GET\" && payload !== undefined) {\n if (endpoint.bodyType === \"form-data\") {\n if (typeof FormData !== \"undefined\" && payload instanceof FormData) {\n body = payload;\n } else {\n const form = new FormData();\n\n if (this.isObjectRecord(payload)) {\n for (const [key, value] of Object.entries(payload)) {\n this.appendFormValue(form, key, value);\n }\n } else if (payload != null) {\n form.append(\"value\", String(payload));\n }\n\n body = form;\n }\n } else {\n body = JSON.stringify(payload);\n }\n }\n\n return { url, body, headers: parts.headers, parts };\n }\n\n private extractRequestParts(input: any): ParsedRequestParts {\n if (this.isStructuredRequestInput(input)) {\n return {\n path: this.isObjectRecord(input.path) ? input.path : undefined,\n query: this.isObjectRecord(input.query) ? input.query : undefined,\n body: input.body,\n headers: this.normalizeHeaders(input.headers ?? input.header),\n isStructured: true,\n };\n }\n\n return {\n body: input,\n headers: {},\n isStructured: false,\n };\n }\n\n private isStructuredRequestInput(\n input: unknown,\n ): input is Record<string, any> {\n if (!this.isObjectRecord(input)) return false;\n\n const keys = Object.keys(input);\n if (keys.length === 0) return false;\n\n return (\n keys.some((key) => REQUEST_PART_KEYS.has(key)) &&\n keys.every((key) => REQUEST_PART_KEYS.has(key))\n );\n }\n\n private isObjectRecord(value: unknown): value is Record<string, any> {\n return typeof value === \"object\" && value !== null && !Array.isArray(value);\n }\n\n private applyPathParams(\n url: string,\n pathParams?: Record<string, any>,\n ): string {\n return url.replace(/:([A-Za-z0-9_]+)/g, (_, key: string) => {\n const value = pathParams?.[key];\n\n if (value === undefined || value === null) {\n throw this.createError({\n message: `Missing path param \"${key}\"`,\n code: \"MISSING_PATH_PARAM\",\n });\n }\n\n return encodeURIComponent(String(value));\n });\n }\n\n private appendQueryParams(url: string, query?: Record<string, any>): string {\n if (!query) return url;\n\n const params = new URLSearchParams();\n\n for (const [key, value] of Object.entries(query)) {\n this.appendQueryValue(params, key, value);\n }\n\n const queryString = params.toString();\n if (!queryString) return url;\n\n return `${url}${url.includes(\"?\") ? \"&\" : \"?\"}${queryString}`;\n }\n\n private appendQueryValue(params: URLSearchParams, key: string, value: any) {\n if (value === undefined || value === null) return;\n\n if (Array.isArray(value)) {\n for (const item of value) this.appendQueryValue(params, key, item);\n return;\n }\n\n if (value instanceof Date) {\n params.append(key, value.toISOString());\n return;\n }\n\n if (typeof value === \"object\") {\n params.append(key, JSON.stringify(value));\n return;\n }\n\n params.append(key, String(value));\n }\n\n private appendFormValue(form: FormData, key: string, value: any) {\n if (value === undefined || value === null) return;\n\n if (Array.isArray(value)) {\n for (const item of value) this.appendFormValue(form, key, item);\n return;\n }\n\n if (value instanceof Date) {\n form.append(key, value.toISOString());\n return;\n }\n\n const isBlob = typeof Blob !== \"undefined\" && value instanceof Blob;\n\n if (typeof value === \"object\" && !isBlob) {\n form.append(key, JSON.stringify(value));\n return;\n }\n\n form.append(key, value as any);\n }\n\n private normalizeHeaders(headers: unknown): Record<string, string> {\n if (!this.isObjectRecord(headers)) return {};\n\n const normalized: Record<string, string> = {};\n\n for (const [key, value] of Object.entries(headers)) {\n if (value === undefined || value === null) continue;\n normalized[key] = String(value);\n }\n\n return normalized;\n }\n\n private createError(error: Partial<RichError> & { message: string }) {\n return new RichError(error);\n }\n\n private normalizeError(err: any) {\n if (err instanceof RichError) return err;\n if (err instanceof z.ZodError) {\n return this.createError({\n message: `Validation error: ${err.issues.map((e) => e.message).join(\", \")}`,\n code: \"VALIDATION_ERROR\",\n });\n }\n return this.createError({ message: err.message || \"Unknown error\" });\n }\n\n private async handleMockRequest(endpoint: any) {\n const delay =\n Math.floor(\n Math.random() * (this.mockDelay.max - this.mockDelay.min + 1),\n ) + this.mockDelay.min;\n\n await new Promise((r) => setTimeout(r, delay));\n\n const data =\n typeof endpoint.mockData === \"function\"\n ? endpoint.mockData()\n : endpoint.mockData;\n\n return this.responseTransform(endpoint.response.parse(data));\n }\n}\n","import { Middleware } from \"@/types\";\nimport z from \"zod\";\n\nexport type LoggingOptions = {\n logRequest?: boolean;\n logResponse?: boolean;\n debug?: boolean;\n};\n\nexport const loggingMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n LoggingOptions\n> = async (ctx, next, options) => {\n const { logRequest = true, logResponse = true, debug = true } = options || {};\n\n if (debug && logRequest) console.log(\"➡️ Request:\", ctx.url, ctx.init);\n\n const res = await next();\n\n if (debug && logResponse) console.log(\"⬅️ Response:\", res.status);\n\n return res;\n};\n","import { Middleware } from \"@/types\";\n\n\nexport type RetryOptions = {\n maxRetries?: number;\n delay?: number; // ms\n};\n\nexport const retryMiddleware = (options?: RetryOptions): Middleware => {\n const { maxRetries = 3, delay = 500 } = options || {};\n\n const middleware: Middleware = async (ctx, next) => {\n let attempt = 0;\n while (true) {\n try {\n return await next();\n } catch (err) {\n if (attempt >= maxRetries) throw err;\n attempt++;\n await new Promise((r) => setTimeout(r, delay * 2 ** attempt));\n }\n }\n };\n\n return middleware;\n};\n","import { Middleware } from \"@/types\";\nimport z from \"zod\";\n\n/**\n * TokenManagementOptions\n * ======================\n * Configuration structure for supplying credentials to the authentication layer.\n *\n * @property refreshToken A required asynchronous function responsible for\n * obtaining a current, valid access token string. This allows\n * for token fetching from storage or re-issuance upon expiry.\n */\nexport type AuthOptions = {\n refreshToken?: () => Promise<string>;\n};\n\n/**\n * AuthenticationInjectorMiddleware\n * ==================================\n * This middleware operates early in the request pipeline to ensure every\n * outgoing request is properly authorized by prepending an Authorization header.\n *\n * Core Logic:\n * -----------\n * 1. It checks if an explicit `refreshToken` supplier was configured in its options.\n * 2. If present, it synchronously calls this supplier to obtain the latest token.\n * 3. The resulting token is formatted as a standard 'Bearer' token and merged\n * into the request's `init.headers`.\n * 4. The request context (`ctx`) is then passed downstream.\n *\n * Note on Error Handling:\n * -----------------------\n * Any failure during the token retrieval process (e.g., if `refreshToken` throws)\n * results in the error being caught, and the request proceeds **without** an\n * Authorization header. This design defers failure response handling to\n * subsequent middleware or the final network fetcher.\n *\n * @param ctx The current request context object, including mutable `init` properties.\n * @param next The function to execute the rest of the middleware chain.\n * @param options The specific configuration passed to this middleware instance.\n *\n * @returns The final `Response` object after the network call completes.\n *\n * @example\n * // Assuming token retrieval logic is defined elsewhere\n * const tokenSupplier = () => fetchTokenFromSecureStorage();\n *\n * client.addInterceptor(\n * authMiddleware({ refreshToken: tokenSupplier })\n * );\n */\nexport const authMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n AuthOptions\n> = async (ctx, next, options) => {\n // Step 1 & 2: Check for and execute the token provider\n if (options?.refreshToken) {\n try {\n const newToken = await options.refreshToken();\n\n // Step 3: Mutate the context's request initialization object\n ctx.init.headers = {\n ...ctx.init.headers, // Preserve any headers set by prior middleware\n Authorization: `Bearer ${newToken}`,\n };\n } catch (error) {\n // Step 4: Fail silently for header injection purposes\n // The request will proceed unauthenticated if the token failed to load\n console.warn(\n \"Authentication token refresh failed, proceeding without authorization header.\",\n error,\n );\n }\n }\n\n // Step 5: Pass control to the next step in the request pipeline\n return next();\n};\n","import { MiddlewareContext, MiddlewareNext } from \"@/types\";\n\n/**\n * CacheOptions\n * ============\n * Options for configuring the cache middleware.\n * - `ttl` (Time To Live): Duration (in milliseconds) to keep cached GET responses.\n * After this time, cached data expires and a fresh network call is performed.\n */\nexport type CacheOptions = { ttl?: number };\n\n/**\n * cacheMiddleware\n * ===============\n * A generic caching middleware for GET requests in the ApiClient.\n * It stores successful responses in memory based on URL and method,\n * returning cached data for subsequent identical requests until the TTL expires.\n *\n * Purpose:\n * --------\n * - Reduces redundant network calls\n * - Improves performance for frequently fetched resources\n * - Useful for lightweight front-end caching (not suitable for sensitive data)\n *\n * Behavior:\n * ---------\n * 1. Only applies to `GET` requests; all other HTTP methods bypass caching.\n * 2. Caches the parsed JSON response in a simple in-memory Map.\n * 3. On subsequent requests:\n * - If the cache entry exists and hasn’t expired, returns a synthetic\n * `Response` object built from cached JSON.\n * - Otherwise performs the network call and refreshes the cache.\n *\n * @param options - Optional cache configuration (TTL in ms)\n *\n * @returns Middleware function compatible with the ApiClient pipeline.\n *\n * @example\n * client.use(\n * cacheMiddleware({ ttl: 120000 }) // cache GET results for 2 minutes\n * );\n *\n * @note Each middleware instance maintains its own internal cache\n * and is memory-scoped (not persistent between reloads).\n */\nexport const cacheMiddleware = (options: CacheOptions = {}) => {\n // Default TTL = 60 seconds, unless overridden\n const { ttl = 60000 } = options;\n\n /**\n * Internal cache store.\n * Keys are composed as `\"METHOD:URL\"`.\n * Values include cached response data and expiration timestamp.\n */\n const cache = new Map<string, { data: any; expires: number }>();\n\n // Return an asynchronous middleware function conforming to the standard signature\n return async (ctx: MiddlewareContext, next: MiddlewareNext) => {\n // Caching only applies to GET requests\n if (ctx.init.method === \"GET\") {\n const key = `${ctx.init.method}:${ctx.url}`;\n const cached = cache.get(key);\n const now = Date.now();\n\n // Check if valid cached response exists and hasn't expired\n if (cached && cached.expires > now) {\n // Return a new synthetic Response containing cached data\n return new Response(JSON.stringify(cached.data), {\n headers: { \"Content-Type\": \"application/json\" },\n });\n }\n\n // Perform the actual network request via the next middleware/fetcher\n const res = await next();\n\n // Attempt to read JSON data from the response (clone avoids stream lock)\n const data = await res\n .clone()\n .json()\n .catch(() => null);\n\n // Store parsed data with expiration if successfully obtained\n if (data) {\n cache.set(key, { data, expires: now + ttl });\n }\n\n // Return original response to caller\n return res;\n }\n\n // For all non‑GET requests, just forward the call with no caching logic\n return next();\n };\n};\n","import type { Middleware, DeepEncryptionMap, EncryptionMethod } from \"@/types\";\nimport CryptoJS from \"crypto-js\";\nimport forge from \"node-forge\";\nimport { z } from \"zod\";\n\ntype SymmetricKeyMaterial = {\n type: \"symmetric\";\n key: string;\n};\n\ntype RSAKeyMaterial = {\n type: \"rsa\";\n publicKey: string;\n privateKey: string;\n};\n\ntype KeyMaterial = SymmetricKeyMaterial | RSAKeyMaterial;\n\ntype CustomHandlers = {\n encrypt: (value: string, key: KeyMaterial) => string | Promise<string>;\n decrypt: (value: string, key: KeyMaterial) => string | Promise<string>;\n};\n\nexport interface EncryptionOptions {\n keyProvider: () => KeyMaterial | Promise<KeyMaterial>;\n customHandlers?: CustomHandlers;\n\n /**\n * true = throw when encryption/decryption fails, which avoids leaking plaintext.\n * false = log and continue/fallback to the original response.\n * Default: true\n */\n failClosed?: boolean;\n}\n\nfunction safeJsonParse(value: string): unknown {\n try {\n return JSON.parse(value);\n } catch {\n return value;\n }\n}\n\nfunction isPlainObject(value: unknown): value is Record<string, unknown> {\n return (\n typeof value === \"object\" &&\n value !== null &&\n !Array.isArray(value) &&\n Object.prototype.toString.call(value) === \"[object Object]\"\n );\n}\n\nfunction hasKey(value: unknown, key: string): value is Record<string, unknown> {\n return (\n isPlainObject(value) && Object.prototype.hasOwnProperty.call(value, key)\n );\n}\n\nfunction toMiddlewareError(message: string, error: unknown): Error {\n const err = new Error(\n `${message}: ${error instanceof Error ? error.message : \"Unknown error\"}`,\n );\n (err as any).cause = error;\n return err;\n}\n\nfunction encryptWithAES(value: string, key: string): string {\n return CryptoJS.AES.encrypt(value, key).toString();\n}\n\nfunction decryptWithAES(value: string, key: string): string {\n const bytes = CryptoJS.AES.decrypt(value, key);\n return bytes.toString(CryptoJS.enc.Utf8);\n}\n\nfunction encryptWithDES(value: string, key: string): string {\n return CryptoJS.DES.encrypt(value, key).toString();\n}\n\nfunction decryptWithDES(value: string, key: string): string {\n const bytes = CryptoJS.DES.decrypt(value, key);\n return bytes.toString(CryptoJS.enc.Utf8);\n}\n\nfunction encodeWithBase64(value: string): string {\n return CryptoJS.enc.Base64.stringify(CryptoJS.enc.Utf8.parse(value));\n}\n\nfunction decodeWithBase64(value: string): string {\n return CryptoJS.enc.Base64.parse(value).toString(CryptoJS.enc.Utf8);\n}\n\nfunction encryptWithRSA(value: string, publicKey: string): string {\n const publicKeyObject = forge.pki.publicKeyFromPem(publicKey);\n const encrypted = publicKeyObject.encrypt(\n forge.util.encodeUtf8(value),\n \"RSA-OAEP\",\n );\n return forge.util.encode64(encrypted);\n}\n\nfunction decryptWithRSA(value: string, privateKey: string): string {\n const privateKeyObject = forge.pki.privateKeyFromPem(privateKey);\n const decrypted = privateKeyObject.decrypt(\n forge.util.decode64(value),\n \"RSA-OAEP\",\n );\n return forge.util.decodeUtf8(decrypted);\n}\n\nasync function encryptValue(\n value: string,\n method: EncryptionMethod,\n keyMaterial: KeyMaterial,\n customHandlers?: CustomHandlers,\n): Promise<string> {\n switch (method) {\n case \"AES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"AES encryption requires symmetric key material.\");\n }\n return encryptWithAES(value, keyMaterial.key);\n }\n\n case \"DES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"DES encryption requires symmetric key material.\");\n }\n return encryptWithDES(value, keyMaterial.key);\n }\n\n case \"Base64\": {\n return encodeWithBase64(value);\n }\n\n case \"RSA\": {\n if (keyMaterial.type !== \"rsa\") {\n throw new Error(\"RSA encryption requires RSA key material.\");\n }\n return encryptWithRSA(value, keyMaterial.publicKey);\n }\n\n case \"Custom\": {\n if (!customHandlers) {\n throw new Error(\"Custom encryption requires custom handlers.\");\n }\n return await customHandlers.encrypt(value, keyMaterial);\n }\n\n default: {\n const exhaustiveCheck: never = method;\n throw new Error(`Unsupported encryption method: ${exhaustiveCheck}`);\n }\n }\n}\n\nasync function decryptValue(\n value: string,\n method: EncryptionMethod,\n keyMaterial: KeyMaterial,\n customHandlers?: CustomHandlers,\n): Promise<string> {\n switch (method) {\n case \"AES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"AES decryption requires symmetric key material.\");\n }\n return decryptWithAES(value, keyMaterial.key);\n }\n\n case \"DES\": {\n if (keyMaterial.type !== \"symmetric\") {\n throw new Error(\"DES decryption requires symmetric key material.\");\n }\n return decryptWithDES(value, keyMaterial.key);\n }\n\n case \"Base64\": {\n return decodeWithBase64(value);\n }\n\n case \"RSA\": {\n if (keyMaterial.type !== \"rsa\") {\n throw new Error(\"RSA decryption requires RSA key material.\");\n }\n return decryptWithRSA(value, keyMaterial.privateKey);\n }\n\n case \"Custom\": {\n if (!customHandlers) {\n throw new Error(\"Custom decryption requires custom handlers.\");\n }\n return await customHandlers.decrypt(value, keyMaterial);\n }\n\n default: {\n const exhaustiveCheck: never = method;\n throw new Error(`Unsupported decryption method: ${exhaustiveCheck}`);\n }\n }\n}\n\nexport async function processDeep<T = unknown>(\n data: unknown,\n map: DeepEncryptionMap | null | undefined,\n defaultMethod: EncryptionMethod,\n transform: (value: unknown, method: EncryptionMethod) => Promise<unknown>,\n): Promise<T> {\n if (data == null || map == null) return data as T;\n\n if (typeof map === \"string\") return (await transform(data, map)) as T;\n\n if (typeof map === \"boolean\") {\n return (map ? await transform(data, defaultMethod) : data) as T;\n }\n\n if (Array.isArray(data)) {\n if (!Array.isArray(map)) {\n return Promise.all(\n data.map((item) => processDeep(item, map, defaultMethod, transform)),\n ) as Promise<T>;\n }\n\n return Promise.all(\n data.map((item, idx) =>\n processDeep(item, map[idx] ?? map[0], defaultMethod, transform),\n ),\n ) as Promise<T>;\n }\n\n if (isPlainObject(data) && isPlainObject(map)) {\n const result: Record<string, unknown> = { ...data };\n\n for (const key of Object.keys(map)) {\n const childMap = (map as Record<string, DeepEncryptionMap>)[key];\n if (childMap == null) continue;\n\n const currentVal = result[key];\n if (currentVal !== undefined) {\n result[key] = await processDeep(\n currentVal,\n childMap,\n defaultMethod,\n transform,\n );\n }\n }\n\n return result as T;\n }\n\n return data as T;\n}\n\nfunction getRequestBodyMap(map: DeepEncryptionMap): DeepEncryptionMap {\n // Supports both styles:\n // encryption.request: { password: true }\n // encryption.request: { body: { password: true } }\n if (hasKey(map, \"body\")) {\n return map.body as DeepEncryptionMap;\n }\n\n return map;\n}\n\nexport const encryptionMiddleware: Middleware<\n z.ZodTypeAny,\n z.ZodTypeAny,\n EncryptionOptions\n> = async (ctx, next, options) => {\n if (!options) {\n throw new Error(\"Encryption middleware options were not provided.\");\n }\n\n const { keyProvider, customHandlers } = options;\n const failClosed = options.failClosed ?? true;\n const encryption = ctx.endpoint.encryption;\n\n if (!encryption || (!encryption.request && !encryption.response)) {\n return next();\n }\n\n const requestMethod: EncryptionMethod =\n typeof encryption.method === \"string\"\n ? encryption.method\n : (encryption.method?.request ?? \"AES\");\n\n const responseMethod: EncryptionMethod =\n typeof encryption.method === \"string\"\n ? encryption.method\n : (encryption.method?.response ?? \"AES\");\n\n const keyMaterial = await keyProvider();\n\n if (\n encryption.request &&\n typeof ctx.init.body === \"string\" &&\n ctx.init.body.length > 0\n ) {\n try {\n const parsedBody = JSON.parse(ctx.init.body);\n const bodyMap = getRequestBodyMap(encryption.request);\n\n const encryptedBody = await processDeep(\n parsedBody,\n bodyMap,\n requestMethod,\n async (value, method) => {\n const serialized =\n typeof value === \"string\" ? value : JSON.stringify(value);\n\n return encryptValue(serialized, method, keyMaterial, customHandlers);\n },\n );\n\n ctx.init.body = JSON.stringify(encryptedBody);\n\n if (ctx.request) {\n ctx.request.body = encryptedBody;\n }\n } catch (error) {\n if (failClosed) {\n throw toMiddlewareError(\n \"Encryption middleware request encryption failed\",\n error,\n );\n }\n\n console.error(\"Encryption middleware request encryption failed.\", error);\n }\n }\n\n const response = await next();\n\n if (!encryption.response) {\n return response;\n }\n\n try {\n const text = await response.clone().text();\n if (!text) return response;\n\n const parsedResponse = JSON.parse(text);\n\n const decryptedPayload = await processDeep(\n parsedResponse,\n encryption.response,\n responseMethod,\n async (value, method) => {\n if (typeof value !== \"string\") return value;\n\n const decrypted = await decryptValue(\n value,\n method,\n keyMaterial,\n customHandlers,\n );\n\n return safeJsonParse(decrypted);\n },\n );\n\n return new Response(JSON.stringify(decryptedPayload), {\n status: response.status,\n statusText: response.statusText,\n headers: response.headers,\n });\n } catch (error) {\n if (failClosed) {\n throw toMiddlewareError(\n \"Encryption middleware response decryption failed\",\n error,\n );\n }\n\n console.error(\"Encryption middleware response decryption failed.\", error);\n return response;\n }\n};\n","import { z } from \"zod\";\n\ntype OptionalUndefinedBody<T extends z.ZodTypeAny> = T extends z.ZodUndefined\n ? z.ZodOptional<T>\n : T;\n\nexport const makeRequestSchema =\n <\n TPath extends z.ZodRawShape = {},\n TQuery extends z.ZodRawShape = {},\n TBody extends z.ZodTypeAny = z.ZodUndefined,\n THeaders extends z.ZodTypeAny = z.ZodOptional<\n z.ZodRecord<z.ZodString, z.ZodString>\n >,\n >() =>\n (\n defs: {\n path?: z.ZodObject<TPath>;\n query?: z.ZodObject<TQuery>;\n body?: TBody;\n headers?: THeaders;\n } = {},\n ) => {\n const pathSchema = (defs.path ??\n z.object({})) as unknown as z.ZodObject<TPath>;\n\n const querySchema = (defs.query ??\n z.object({})) as unknown as z.ZodObject<TQuery>;\n\n const rawBodySchema = (defs.body ?? z.undefined()) as TBody;\n\n const bodySchema = (\n defs.body ? rawBodySchema : rawBodySchema.optional()\n ) as OptionalUndefinedBody<TBody>;\n\n const headersSchema = (defs.headers ??\n z.record(z.string(), z.string()).optional()) as THeaders;\n\n return z.object({\n path: pathSchema.optional(),\n query: querySchema.optional(),\n body: bodySchema,\n headers: headersSchema,\n });\n };\n"],"mappings":";AAAA,SAAS,SAAS;AAaX,IAAM,YAAN,cAAwB,MAA2B;AAAA,EACxD;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EAEA,YAAY,OAAiD;AAC3D,UAAM,MAAM,OAAO;AACnB,WAAO,OAAO,MAAM,KAAK;AAAA,EAC3B;AACF;AAUA,IAAM,oBAAoB,oBAAI,IAAI;AAAA,EAChC;AAAA,EACA;AAAA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,MACF;AACH,QAAM,aAAc,KAAK,QACvBA,GAAE,OAAO,CAAC,CAAC;AAEb,QAAM,cAAe,KAAK,SACxBA,GAAE,OAAO,CAAC,CAAC;AAEb,QAAM,gBAAiB,KAAK,QAAQA,GAAE,UAAU;AAEhD,QAAM,aACJ,KAAK,OAAO,gBAAgB,cAAc,SAAS;AAGrD,QAAM,gBAAiB,KAAK,WAC1BA,GAAE,OAAOA,GAAE,OAAO,GAAGA,GAAE,OAAO,CAAC,EAAE,SAAS;AAE5C,SAAOA,GAAE,OAAO;AAAA,IACd,MAAM,WAAW,SAAS;AAAA,IAC1B,OAAO,YAAY,SAAS;AAAA,IAC5B,MAAM;AAAA,IACN,SAAS;AAAA,EACX,CAAC;AACH;","names":["z"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@tahanabavi/typefetch",
3
- "version": "1.5.3",
3
+ "version": "1.5.6",
4
4
  "description": "A strongly typed TypeScript HTTP client powered by Zod contracts, middleware, retries, auth, mock data, response wrappers, and validation.",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -64,7 +64,7 @@
64
64
  "ts-node": "^10.9.2",
65
65
  "tsup": "^8.5.0",
66
66
  "typescript": "^5.9.2",
67
- "zod": "^3.25.76"
67
+ "zod": "^4.1.5"
68
68
  },
69
69
  "engines": {
70
70
  "node": ">=18"