@hyper-fetch/core 8.1.0 → 8.2.0

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.
Files changed (51) hide show
  1. package/README.md +137 -52
  2. package/__tests__/features/sdk/sdk.base.spec.ts +7 -11
  3. package/__tests__/features/sdk/sdk.configuration.spec.ts +5 -7
  4. package/__tests__/features/sdk/sdk.types.spec.ts +284 -0
  5. package/dist/adapter/adapter.d.ts +18 -1
  6. package/dist/adapter/adapter.d.ts.map +1 -1
  7. package/dist/adapter/adapter.types.d.ts +8 -0
  8. package/dist/adapter/adapter.types.d.ts.map +1 -1
  9. package/dist/cache/cache.d.ts +3 -6
  10. package/dist/cache/cache.d.ts.map +1 -1
  11. package/dist/cache/cache.events.d.ts +5 -2
  12. package/dist/cache/cache.events.d.ts.map +1 -1
  13. package/dist/cache/cache.types.d.ts +1 -0
  14. package/dist/cache/cache.types.d.ts.map +1 -1
  15. package/dist/client/client.d.ts +5 -1
  16. package/dist/client/client.d.ts.map +1 -1
  17. package/dist/dispatcher/dispatcher.d.ts +1 -1
  18. package/dist/index.mjs +74 -9
  19. package/dist/index.mjs.map +1 -1
  20. package/dist/managers/app/app.manager.events.d.ts +9 -0
  21. package/dist/managers/app/app.manager.events.d.ts.map +1 -1
  22. package/dist/managers/request/request.manager.events.d.ts +12 -1
  23. package/dist/managers/request/request.manager.events.d.ts.map +1 -1
  24. package/dist/mocker/mocker.types.d.ts +1 -0
  25. package/dist/mocker/mocker.types.d.ts.map +1 -1
  26. package/dist/plugin/plugin.d.ts +16 -0
  27. package/dist/plugin/plugin.d.ts.map +1 -1
  28. package/dist/plugin/plugin.types.d.ts +1 -0
  29. package/dist/plugin/plugin.types.d.ts.map +1 -1
  30. package/dist/request/request.d.ts +28 -0
  31. package/dist/request/request.d.ts.map +1 -1
  32. package/dist/request/request.types.d.ts +89 -2
  33. package/dist/request/request.types.d.ts.map +1 -1
  34. package/dist/sdk/sdk.d.ts +25 -5
  35. package/dist/sdk/sdk.d.ts.map +1 -1
  36. package/package.json +1 -1
  37. package/src/adapter/adapter.ts +18 -1
  38. package/src/adapter/adapter.types.ts +8 -0
  39. package/src/cache/cache.events.ts +5 -2
  40. package/src/cache/cache.ts +3 -6
  41. package/src/cache/cache.types.ts +1 -0
  42. package/src/client/client.ts +5 -1
  43. package/src/dispatcher/dispatcher.ts +1 -1
  44. package/src/managers/app/app.manager.events.ts +9 -0
  45. package/src/managers/request/request.manager.events.ts +12 -9
  46. package/src/mocker/mocker.types.ts +1 -0
  47. package/src/plugin/plugin.ts +16 -0
  48. package/src/plugin/plugin.types.ts +1 -0
  49. package/src/request/request.ts +28 -0
  50. package/src/request/request.types.ts +103 -2
  51. package/src/sdk/sdk.ts +55 -6
package/README.md CHANGED
@@ -1,6 +1,10 @@
1
1
  # ⚡ Hyper Fetch
2
2
 
3
- <p>
3
+ <p align="center">
4
+ <b>One SDK for every API. The type-safe API layer for TypeScript apps — REST, GraphQL, WebSockets, SSE, Firebase, and more.</b>
5
+ </p>
6
+
7
+ <p align="center">
4
8
  <a href="https://bettertyped.com/">
5
9
  <img src="https://custom-icon-badges.demolab.com/static/v1?label=&message=BetterTyped&color=333&logo=BT" />
6
10
  </a>
@@ -13,61 +17,142 @@
13
17
  <a href="https://www.npmjs.com/package/@hyper-fetch/core">
14
18
  <img src="https://custom-icon-badges.demolab.com/npm/v/@hyper-fetch/core.svg?logo=npm&color=e76f51" />
15
19
  </a>
20
+ <a href="https://www.npmjs.com/package/@hyper-fetch/core">
21
+ <img src="https://custom-icon-badges.demolab.com/npm/dm/@hyper-fetch/core?logoColor=fff&logo=trending-up" />
22
+ </a>
16
23
  <a href="https://github.com/BetterTyped/hyper-fetch">
17
24
  <img src="https://custom-icon-badges.demolab.com/badge/typescript-%23007ACC.svg?logo=typescript&logoColor=white" />
18
25
  </a>
19
- <a href="https://www.npmjs.com/package/@hyper-fetch/core">
26
+ <a href="https://bundlephobia.com/package/@hyper-fetch/core">
20
27
  <img src="https://custom-icon-badges.demolab.com/bundlephobia/minzip/@hyper-fetch/core?color=64BC4B&logo=package" />
21
28
  </a>
22
29
  </p>
23
30
 
24
- ## About
25
-
26
- **`Hyper Fetch`** is a data-exchange framework. What makes it unique is the **typesafe design** and the **ease of use**.
27
- This library is `backend and framework agnostic`, with aim to provide as many great and useful features as possible. In
28
- particular `caching`, `queuing`, `persistence`, `offline first support`, `request deduplication`, `authentication`,
29
- `progress tracking`, `structure and architecture` guidelines.
30
-
31
- ## Features
32
-
33
- 🔮 **Simple setup** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/basic/setup)
34
-
35
- 🎯 **Request cancellation** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/cancellation)
36
-
37
- ✨ **Window Focus/Blur Events** -
38
- [Read more](https://hyperfetch.bettertyped.com/docs/guides/react/core/window-focus-blur)
39
-
40
- 🚀 **Queueing** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/queueing)
41
-
42
- 💎 **Automatic caching** - [Read more](https://hyperfetch.bettertyped.com/docs/core/cache)
43
-
44
- 🪄 **Persistence** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/persistence)
45
-
46
- 🎊 **SSR Support** - [Read more](https://hyperfetch.bettertyped.com/docs/getting-started/environment)
47
-
48
- 🔋 **Offline First** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/offline)
49
-
50
- 📡 **Built-in adapter** - [Read more](https://hyperfetch.bettertyped.com/docs/core/adapter)
51
-
52
- 🧪 **Easy to test** - [Read more](https://hyperfetch.bettertyped.com/docs/getting-started/testing)
53
-
54
- 🎟 **Authentication** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/basic/authentication)
55
-
56
- 💡 **Prefetching** - [Read more](https://hyperfetch.bettertyped.com/docs/guides/advanced/prefetching)
57
-
58
- ## Help me keep working on this project ❤️
59
-
60
- - [Become a Sponsor on GitHub](https://github.com/sponsors/prc5)
61
-
62
- ## Sources
63
-
64
- - #### [Installation](https://hyperfetch.bettertyped.com/docs/getting-started/installation)
65
- - #### [Docs](https://hyperfetch.bettertyped.com/)
66
- - #### [API](https://hyperfetch.bettertyped.com/api/)
67
- - #### [NPM](https://www.npmjs.com/package/@hyper-fetch/core)
68
- - #### [Guides](https://hyperfetch.bettertyped.com/guides/Basic/Setup)
69
-
70
- ## Other Packages
71
-
72
- - #### [Hyper Fetch Sockets](https://github.com/BetterTyped/hyper-fetch/tree/main/packages/sockets)
73
- - #### [React Hyper Fetch](https://github.com/BetterTyped/hyper-fetch/tree/main/packages/react)
31
+ ## 📖 About
32
+
33
+ HyperFetch Core is the foundation of the HyperFetch ecosystem. Every API call is a typed, immutable request object with built-in caching, queuing, retries, and offline support. It works in any JavaScript environment — browser, server, or edge — and connects to any API through pluggable adapters.
34
+
35
+ ## 🎯 Key Capabilities
36
+
37
+ - 🔮 **Zero guesswork** — Full autocompletion for every request, response, param, and error. Never cast to `any` again
38
+ - 📡 **One interface for everything** — REST, GraphQL, Firebase, WebSockets, SSE — switch APIs without rewriting a line
39
+ - 💾 **Stop re-fetching what you already have** — Smart cache with TTL and invalidation out of the box
40
+ - 🔁 **Failed requests retry themselves** — Configurable retry with backoff so users never see random failures
41
+ - 📴 **Works without internet** — Queues requests offline and replays them when connection returns
42
+ - 🚫 **No duplicate requests** — Concurrent identical calls are deduplicated automatically
43
+ - ⏱️ **Know exactly what's happening** — Upload and download progress with time estimates for every request
44
+ - 🎯 **Cancel anything, anytime** — Kill pending requests individually or by group with one call
45
+ - 🔌 **Swap engines without touching your code** — Switch between Axios, GraphQL, Firebase adapters in one line
46
+ - 🪄 **Generate your SDK** — Point CLI at an OpenAPI schema and get a fully typed client instantly
47
+
48
+ ## 🚀 Quick Start
49
+
50
+ ```bash
51
+ npm install @hyper-fetch/core
52
+ ```
53
+
54
+ ```ts
55
+ import { createClient } from "@hyper-fetch/core";
56
+
57
+ // Single entry point — all requests inherit this base URL
58
+ const client = createClient({ url: "https://api.example.com" });
59
+
60
+ // Define a request with typed response — :userId becomes a required param
61
+ const getUser = client.createRequest<{ response: { id: number; name: string } }>()({
62
+ endpoint: "/users/:userId",
63
+ method: "GET",
64
+ });
65
+
66
+ // setParams is typed from the endpoint string, send() returns typed data
67
+ const { data, error } = await getUser.setParams({ userId: 1 }).send();
68
+ ```
69
+
70
+ ## 📚 Documentation
71
+
72
+ - [Getting Started](https://hyperfetch.bettertyped.com/docs/getting-started/quick-start)
73
+ - [Core Overview](https://hyperfetch.bettertyped.com/docs/core/overview)
74
+ - [API Reference](https://hyperfetch.bettertyped.com/api/)
75
+
76
+ ## 💡 Examples
77
+
78
+ ### Typed requests with params, payload, and query params
79
+
80
+ ```ts
81
+ interface User {
82
+ id: number;
83
+ name: string;
84
+ email: string;
85
+ }
86
+
87
+ // GET request — only response type needed, params inferred from :userId
88
+ const getUser = client.createRequest<{ response: User }>()({
89
+ endpoint: "/users/:userId",
90
+ method: "GET",
91
+ });
92
+
93
+ // POST request — define both response and payload types
94
+ const createUser = client.createRequest<{
95
+ response: User;
96
+ payload: { name: string; email: string };
97
+ }>()({
98
+ endpoint: "/users",
99
+ method: "POST",
100
+ });
101
+
102
+ // Params are type-checked: { userId: number } required here
103
+ const { data } = await getUser.setParams({ userId: 1 }).send();
104
+
105
+ // Payload is type-checked: { name, email } required here
106
+ const { data: newUser } = await createUser.send({
107
+ data: { name: "Jane", email: "jane@example.com" },
108
+ });
109
+ ```
110
+
111
+ ### Dynamic data with query params
112
+
113
+ ```ts
114
+ // Define allowed query params — all are optional and type-checked
115
+ const listUsers = client.createRequest<{
116
+ response: User[];
117
+ queryParams: { page?: number; limit?: number; search?: string };
118
+ }>()({
119
+ endpoint: "/users",
120
+ method: "GET",
121
+ });
122
+
123
+ // Query params are appended to the URL: /users?page=1&limit=20&search=john
124
+ const { data } = await listUsers
125
+ .setQueryParams({ page: 1, limit: 20, search: "john" })
126
+ .send();
127
+ ```
128
+
129
+ ### Lifecycle callbacks
130
+
131
+ ```ts
132
+ // Hook into the request lifecycle — track progress, log events, handle responses
133
+ const { data } = await getUser.setParams({ userId: 1 }).send({
134
+ onStart: ({ requestId }) => console.log(`Request ${requestId} started`),
135
+ onResponse: ({ response }) => console.log("Got data:", response.data),
136
+ onUploadProgress: ({ progress }) => console.log(`Upload: ${progress}%`),
137
+ onDownloadProgress: ({ progress }) => console.log(`Download: ${progress}%`),
138
+ });
139
+ ```
140
+
141
+ ### Response mapping
142
+
143
+ ```ts
144
+ // Transform the response before it reaches your code
145
+ const getUser = client
146
+ .createRequest<{ response: User }>()({
147
+ endpoint: "/users/:userId",
148
+ method: "GET",
149
+ })
150
+ .setResponseMapper((response) => ({
151
+ ...response,
152
+ data: { ...response.data, name: response.data.name.toUpperCase() },
153
+ }));
154
+ ```
155
+
156
+ ## License
157
+
158
+ [MIT](https://github.com/BetterTyped/hyper-fetch/blob/main/License.md)
@@ -3,7 +3,7 @@ import { createHttpMockingServer } from "@hyper-fetch/testing";
3
3
  import type { Client } from "client";
4
4
  import { createClient } from "client";
5
5
  import type { HttpAdapterType } from "http-adapter";
6
- import type { RequestInstance } from "request";
6
+ import type { RequestModel } from "request";
7
7
  import { Request } from "request";
8
8
  import { createSdk } from "sdk";
9
9
 
@@ -11,28 +11,25 @@ const { resetMocks, startServer, stopServer } = createHttpMockingServer();
11
11
 
12
12
  type TestClient = Client<Error, HttpAdapterType>;
13
13
 
14
+ // Schema does not need to declare `client` per request - the SDK injects it from createSdk(client).
14
15
  type TestSchema = {
15
16
  users: {
16
- $get: RequestInstance<{
17
- client: TestClient;
17
+ $get: RequestModel<{
18
18
  queryParams: { page: number; limit: number };
19
19
  endpoint: "/users";
20
20
  }>;
21
21
  $userId: {
22
- $get: RequestInstance<{
23
- client: TestClient;
22
+ $get: RequestModel<{
24
23
  response: { id: string; name: string };
25
24
  endpoint: "/users/:userId";
26
25
  }>;
27
- $delete: RequestInstance<{
28
- client: TestClient;
26
+ $delete: RequestModel<{
29
27
  response: { id: string; name: string };
30
28
  endpoint: "/users/:userId";
31
29
  }>;
32
30
  posts: {
33
31
  $postId: {
34
- $delete: RequestInstance<{
35
- client: TestClient;
32
+ $delete: RequestModel<{
36
33
  response: { id: string; title: string };
37
34
  endpoint: "/users/:userId/posts/:postId";
38
35
  }>;
@@ -41,8 +38,7 @@ type TestSchema = {
41
38
  };
42
39
  };
43
40
  acceptInvitation: {
44
- $post: RequestInstance<{
45
- client: TestClient;
41
+ $post: RequestModel<{
46
42
  endpoint: "/accept-invitation";
47
43
  }>;
48
44
  };
@@ -1,29 +1,27 @@
1
1
  import type { Client } from "client";
2
2
  import { createClient } from "client";
3
3
  import type { HttpAdapterType } from "http-adapter";
4
- import type { RequestInstance } from "request";
4
+ import type { RequestInstance, RequestModel } from "request";
5
5
  import { Request } from "request";
6
6
  import { createSdk, createConfiguration } from "sdk";
7
7
 
8
8
  type TestClient = Client<Error, HttpAdapterType>;
9
9
 
10
+ // Schema does not need to declare `client` per request - the SDK injects it from createSdk(client).
10
11
  type TestSchema = {
11
12
  users: {
12
- $get: RequestInstance<{
13
- client: TestClient;
13
+ $get: RequestModel<{
14
14
  endpoint: "/users";
15
15
  }>;
16
16
  $userId: {
17
- $get: RequestInstance<{
18
- client: TestClient;
17
+ $get: RequestModel<{
19
18
  response: { id: string; name: string };
20
19
  endpoint: "/users/:userId";
21
20
  }>;
22
21
  };
23
22
  };
24
23
  posts: {
25
- $get: RequestInstance<{
26
- client: TestClient;
24
+ $get: RequestModel<{
27
25
  endpoint: "/posts";
28
26
  }>;
29
27
  };
@@ -0,0 +1,284 @@
1
+ import { describe, it, expect, expectTypeOf } from "vitest";
2
+
3
+ import { createClient } from "client";
4
+ import type { ClientInstance, Client } from "client";
5
+ import type { Request, RequestInstance, RequestModel } from "request";
6
+ import type { HttpAdapterType } from "http-adapter";
7
+ import { createSdk } from "sdk";
8
+ import type { InjectClient } from "sdk";
9
+
10
+ /**
11
+ * Type-only tests for the SDK type surface.
12
+ *
13
+ * These tests do not exercise runtime behaviour - they verify that the type system narrows,
14
+ * defaults, and propagates types as designed. Each `it` block contains a static
15
+ * `expectTypeOf` assertion plus a trivial runtime `expect(true).toBe(true)` placeholder so
16
+ * the test shows up in the Vitest report.
17
+ */
18
+
19
+ type TestClient = Client<Error, HttpAdapterType>;
20
+ type CustomError = { code: string; message: string };
21
+ type User = { id: string; name: string };
22
+
23
+ describe("RequestModel - defaults for omitted fields", () => {
24
+ it("should default response to unknown", () => {
25
+ type R = RequestModel<{ endpoint: "/users" }>;
26
+ type Response = R extends Request<infer Resp, any, any, any, any, any, any, any, any, any> ? Resp : never;
27
+ expectTypeOf<Response>().toEqualTypeOf<unknown>();
28
+ expect(true).toBe(true);
29
+ });
30
+
31
+ it("should default payload to undefined", () => {
32
+ type R = RequestModel<{ endpoint: "/users" }>;
33
+ type Payload = R extends Request<any, infer P, any, any, any, any, any, any, any, any> ? P : never;
34
+ expectTypeOf<Payload>().toEqualTypeOf<undefined>();
35
+ expect(true).toBe(true);
36
+ });
37
+
38
+ it("should default queryParams to undefined", () => {
39
+ type R = RequestModel<{ endpoint: "/users" }>;
40
+ type Query = R extends Request<any, any, infer Q, any, any, any, any, any, any, any> ? Q : never;
41
+ expectTypeOf<Query>().toEqualTypeOf<undefined>();
42
+ expect(true).toBe(true);
43
+ });
44
+
45
+ it("should default localError to Error", () => {
46
+ type R = RequestModel<{ endpoint: "/users" }>;
47
+ type LocalError = R extends Request<any, any, any, infer E, any, any, any, any, any, any> ? E : never;
48
+ expectTypeOf<LocalError>().toEqualTypeOf<Error>();
49
+ expect(true).toBe(true);
50
+ });
51
+
52
+ it("should default endpoint to string when not provided", () => {
53
+ type R = RequestModel<{ response: User }>;
54
+ type Endpoint = R extends Request<any, any, any, any, infer E, any, any, any, any, any> ? E : never;
55
+ expectTypeOf<Endpoint>().toEqualTypeOf<string>();
56
+ expect(true).toBe(true);
57
+ });
58
+
59
+ it("should default client to ClientInstance when not provided", () => {
60
+ type R = RequestModel<{ endpoint: "/users" }>;
61
+ type ClientType = R extends Request<any, any, any, any, any, infer C, any, any, any, any> ? C : never;
62
+ expectTypeOf<ClientType>().toEqualTypeOf<ClientInstance>();
63
+ expect(true).toBe(true);
64
+ });
65
+
66
+ it("should default hasPayload, hasParams, hasQueryParams to false", () => {
67
+ type R = RequestModel<{ endpoint: "/users" }>;
68
+ type HasPayload = R extends Request<any, any, any, any, any, any, infer Hp, any, any, any> ? Hp : never;
69
+ type HasParams = R extends Request<any, any, any, any, any, any, any, infer Hpa, any, any> ? Hpa : never;
70
+ type HasQuery = R extends Request<any, any, any, any, any, any, any, any, infer Hq, any> ? Hq : never;
71
+ expectTypeOf<HasPayload>().toEqualTypeOf<false>();
72
+ expectTypeOf<HasParams>().toEqualTypeOf<false>();
73
+ expectTypeOf<HasQuery>().toEqualTypeOf<false>();
74
+ expect(true).toBe(true);
75
+ });
76
+
77
+ it("should default mutationContext to undefined", () => {
78
+ type R = RequestModel<{ endpoint: "/users" }>;
79
+ type Ctx = R extends Request<any, any, any, any, any, any, any, any, any, infer C> ? C : never;
80
+ expectTypeOf<Ctx>().toEqualTypeOf<undefined>();
81
+ expect(true).toBe(true);
82
+ });
83
+ });
84
+
85
+ describe("RequestModel - user-provided fields override defaults", () => {
86
+ it("should narrow response when provided", () => {
87
+ type R = RequestModel<{ response: User; endpoint: "/users/:userId" }>;
88
+ type Response = R extends Request<infer Resp, any, any, any, any, any, any, any, any, any> ? Resp : never;
89
+ expectTypeOf<Response>().toEqualTypeOf<User>();
90
+ expect(true).toBe(true);
91
+ });
92
+
93
+ it("should narrow payload, queryParams, error when provided", () => {
94
+ type R = RequestModel<{
95
+ payload: { name: string };
96
+ queryParams: { page: number };
97
+ error: CustomError;
98
+ endpoint: "/users";
99
+ }>;
100
+ type Payload = R extends Request<any, infer P, any, any, any, any, any, any, any, any> ? P : never;
101
+ type Query = R extends Request<any, any, infer Q, any, any, any, any, any, any, any> ? Q : never;
102
+ type LocalError = R extends Request<any, any, any, infer E, any, any, any, any, any, any> ? E : never;
103
+
104
+ expectTypeOf<Payload>().toEqualTypeOf<{ name: string }>();
105
+ expectTypeOf<Query>().toEqualTypeOf<{ page: number }>();
106
+ expectTypeOf<LocalError>().toEqualTypeOf<CustomError>();
107
+ expect(true).toBe(true);
108
+ });
109
+
110
+ it("should narrow endpoint to its literal type", () => {
111
+ type R = RequestModel<{ response: User; endpoint: "/users/:userId" }>;
112
+ type Endpoint = R extends Request<any, any, any, any, infer E, any, any, any, any, any> ? E : never;
113
+ expectTypeOf<Endpoint>().toEqualTypeOf<"/users/:userId">();
114
+ expect(true).toBe(true);
115
+ });
116
+ });
117
+
118
+ describe("RequestInstance - keeps `any` defaults (regression check for constraint use)", () => {
119
+ it("should default every slot to any so any concrete Request is assignable", () => {
120
+ // RequestInstance with no args must remain wide so it acts as the "any Request" constraint
121
+ type RI = RequestInstance;
122
+ type Response = RI extends Request<infer R, any, any, any, any, any, any, any, any, any> ? R : never;
123
+ type Payload = RI extends Request<any, infer P, any, any, any, any, any, any, any, any> ? P : never;
124
+ type Query = RI extends Request<any, any, infer Q, any, any, any, any, any, any, any> ? Q : never;
125
+
126
+ expectTypeOf<Response>().toEqualTypeOf<any>();
127
+ expectTypeOf<Payload>().toEqualTypeOf<any>();
128
+ expectTypeOf<Query>().toEqualTypeOf<any>();
129
+ expect(true).toBe(true);
130
+ });
131
+
132
+ it("should accept a concrete RequestModel as a RequestInstance via constraint", () => {
133
+ type ConcreteRequest = RequestModel<{ response: User; endpoint: "/users" }>;
134
+ expectTypeOf<ConcreteRequest>().toMatchTypeOf<RequestInstance>();
135
+ expect(true).toBe(true);
136
+ });
137
+ });
138
+
139
+ describe("InjectClient - schema-level client injection", () => {
140
+ it("should replace the Client slot on a single Request leaf with the SDK client", () => {
141
+ type Schema = {
142
+ $get: RequestModel<{ response: User; endpoint: "/users" }>;
143
+ };
144
+ type Injected = InjectClient<Schema, TestClient>;
145
+ type ResolvedRequest = Injected["$get"];
146
+ type ResolvedClient =
147
+ ResolvedRequest extends Request<any, any, any, any, any, infer C, any, any, any, any> ? C : never;
148
+ expectTypeOf<ResolvedClient>().toEqualTypeOf<TestClient>();
149
+ expect(true).toBe(true);
150
+ });
151
+
152
+ it("should walk nested schema objects and inject into every leaf", () => {
153
+ type Schema = {
154
+ users: {
155
+ $get: RequestModel<{ response: User[]; endpoint: "/users" }>;
156
+ $userId: {
157
+ $get: RequestModel<{ response: User; endpoint: "/users/:userId" }>;
158
+ };
159
+ };
160
+ };
161
+ type Injected = InjectClient<Schema, TestClient>;
162
+
163
+ type FlatRequest = Injected["users"]["$get"];
164
+ type NestedRequest = Injected["users"]["$userId"]["$get"];
165
+
166
+ type FlatClient = FlatRequest extends Request<any, any, any, any, any, infer C, any, any, any, any> ? C : never;
167
+ type NestedClient = NestedRequest extends Request<any, any, any, any, any, infer C, any, any, any, any> ? C : never;
168
+
169
+ expectTypeOf<FlatClient>().toEqualTypeOf<TestClient>();
170
+ expectTypeOf<NestedClient>().toEqualTypeOf<TestClient>();
171
+ expect(true).toBe(true);
172
+ });
173
+
174
+ it("should preserve response, endpoint and other fields after injection", () => {
175
+ type Schema = {
176
+ $get: RequestModel<{ response: User; endpoint: "/users/:userId" }>;
177
+ };
178
+ type Injected = InjectClient<Schema, TestClient>;
179
+ type R = Injected["$get"];
180
+
181
+ type Response = R extends Request<infer Resp, any, any, any, any, any, any, any, any, any> ? Resp : never;
182
+ type Endpoint = R extends Request<any, any, any, any, infer E, any, any, any, any, any> ? E : never;
183
+
184
+ expectTypeOf<Response>().toEqualTypeOf<User>();
185
+ expectTypeOf<Endpoint>().toEqualTypeOf<"/users/:userId">();
186
+ expect(true).toBe(true);
187
+ });
188
+
189
+ it("should override an explicitly-passed client in the schema", () => {
190
+ // Edge case: schema declares client (e.g. a placeholder ClientInstance) - SDK still wins
191
+ type SchemaWithExplicitClient = {
192
+ $get: RequestModel<{ client: ClientInstance; response: User; endpoint: "/users" }>;
193
+ };
194
+ type Injected = InjectClient<SchemaWithExplicitClient, TestClient>;
195
+ type R = Injected["$get"];
196
+ type ResolvedClient = R extends Request<any, any, any, any, any, infer C, any, any, any, any> ? C : never;
197
+ expectTypeOf<ResolvedClient>().toEqualTypeOf<TestClient>();
198
+ expect(true).toBe(true);
199
+ });
200
+ });
201
+
202
+ describe("createSdk - produces a fully resolved SDK type", () => {
203
+ type Schema = {
204
+ users: {
205
+ $get: RequestModel<{ response: User[]; endpoint: "/users" }>;
206
+ $userId: {
207
+ $get: RequestModel<{ response: User; endpoint: "/users/:userId" }>;
208
+ };
209
+ };
210
+ };
211
+
212
+ it("should type sdk.users.$get with the SDK client injected", () => {
213
+ const client = createClient<{ error: Error }>({ url: "http://localhost" });
214
+ const sdk = createSdk<typeof client, Schema>(client);
215
+
216
+ type UsersGet = typeof sdk.users.$get;
217
+ type ResolvedClient = UsersGet extends Request<any, any, any, any, any, infer C, any, any, any, any> ? C : never;
218
+ type ResolvedResponse = UsersGet extends Request<infer R, any, any, any, any, any, any, any, any, any> ? R : never;
219
+ type ResolvedEndpoint = UsersGet extends Request<any, any, any, any, infer E, any, any, any, any, any> ? E : never;
220
+
221
+ expectTypeOf<ResolvedClient>().toEqualTypeOf<typeof client>();
222
+ expectTypeOf<ResolvedResponse>().toEqualTypeOf<User[]>();
223
+ expectTypeOf<ResolvedEndpoint>().toEqualTypeOf<"/users">();
224
+ expect(true).toBe(true);
225
+ });
226
+
227
+ it("should type nested sdk.users.$userId.$get with the SDK client injected", () => {
228
+ const client = createClient<{ error: Error }>({ url: "http://localhost" });
229
+ const sdk = createSdk<typeof client, Schema>(client);
230
+
231
+ type NestedGet = typeof sdk.users.$userId.$get;
232
+ type ResolvedClient = NestedGet extends Request<any, any, any, any, any, infer C, any, any, any, any> ? C : never;
233
+ type ResolvedResponse = NestedGet extends Request<infer R, any, any, any, any, any, any, any, any, any> ? R : never;
234
+
235
+ expectTypeOf<ResolvedClient>().toEqualTypeOf<typeof client>();
236
+ expectTypeOf<ResolvedResponse>().toEqualTypeOf<User>();
237
+ expect(true).toBe(true);
238
+ });
239
+
240
+ it("should expose $configure on the SDK type", () => {
241
+ const client = createClient<{ error: Error }>({ url: "http://localhost" });
242
+ const sdk = createSdk<typeof client, Schema>(client);
243
+
244
+ expectTypeOf(sdk.$configure).toBeFunction();
245
+ expect(true).toBe(true);
246
+ });
247
+ });
248
+
249
+ describe("$configure - dot-path callback narrowing", () => {
250
+ type Schema = {
251
+ users: {
252
+ $get: RequestModel<{ response: User[]; endpoint: "/users" }>;
253
+ };
254
+ };
255
+
256
+ it("should accept a function value matching the SDK request type for a dot-path key", () => {
257
+ const client = createClient<{ error: Error }>({ url: "http://localhost" });
258
+ const sdk = createSdk<typeof client, Schema>(client);
259
+
260
+ // The configure call must accept a function whose parameter is assignable from any Request.
261
+ // Stronger narrowing happens at the configuration value level via SocketSdkConfigurationMap.
262
+ sdk.$configure({
263
+ "users.$get": (request) => {
264
+ expectTypeOf(request).toMatchTypeOf<RequestInstance>();
265
+ return request;
266
+ },
267
+ });
268
+
269
+ expect(true).toBe(true);
270
+ });
271
+
272
+ it("should accept a plain-object value for an endpoint group key", () => {
273
+ const client = createClient<{ error: Error }>({ url: "http://localhost" });
274
+ const sdk = createSdk<typeof client, Schema>(client);
275
+
276
+ // Compile-time only: just verify the call typechecks.
277
+ sdk.$configure({
278
+ "*": { retry: 3 },
279
+ "/users": { cache: true, cacheTime: 30000 },
280
+ });
281
+
282
+ expect(true).toBe(true);
283
+ });
284
+ });
@@ -6,6 +6,11 @@ import { LoggerMethods } from '../managers';
6
6
  import { getErrorMessage } from './adapter.utils';
7
7
  export type DefaultMapperType = <V, C>(value: V, config: C) => V;
8
8
  export declare const defaultMapper: DefaultMapperType;
9
+ /**
10
+ * Base adapter class responsible for executing HTTP requests. Adapters handle endpoint resolution,
11
+ * header/payload/query-params mapping, and the actual fetch call. Extend or configure this class
12
+ * to integrate custom transport layers (e.g., axios, graphql, firebase).
13
+ */
9
14
  export declare class Adapter<AdapterOptions, MethodType extends string, StatusType extends number | string, Extra extends Record<string, any>, QueryParams = QueryParamsType | string | EmptyTypes, DefaultQueryParams = undefined, EndpointType = string, EndpointMapperType extends EndpointMapper<EndpointType> | DefaultMapperType = DefaultMapperType, QueryParamsMapperType extends QueryParamsMapper<QueryParams> | DefaultMapperType = DefaultMapperType, HeaderMapperType extends HeaderMappingType | DefaultMapperType = DefaultMapperType, PayloadMapperType extends AdapterPayloadMappingType | DefaultMapperType = DefaultMapperType> {
10
15
  options: {
11
16
  name: string;
@@ -46,7 +51,9 @@ export declare class Adapter<AdapterOptions, MethodType extends string, StatusTy
46
51
  systemErrorExtra: Extra;
47
52
  defaultRequestOptions?: RequestOptionsType<EndpointType, AdapterOptions, MethodType>;
48
53
  });
54
+ /** Initialize the adapter with a client reference and set up logging. Called automatically when the client is created. */
49
55
  initialize: (client: ClientInstance) => this;
56
+ /** Register a callback invoked once the adapter is initialized with a client. */
50
57
  onInitialize: (callback: (options: {
51
58
  client: ClientInstance;
52
59
  }) => void) => this;
@@ -80,8 +87,11 @@ export declare class Adapter<AdapterOptions, MethodType extends string, StatusTy
80
87
  * Methods
81
88
  * ********************
82
89
  */
90
+ /** Set the default HTTP method used when a request does not specify one. */
83
91
  setDefaultMethod: (method: MethodType) => this;
92
+ /** Set the default extra metadata attached to every request response (e.g., headers, status). */
84
93
  setDefaultExtra: (extra: Extra) => this;
94
+ /** Set a function that formats the endpoint string for display in devtools. */
85
95
  setDevtoolsEndpointGetter: (callback: (endpoint: string) => string) => this;
86
96
  /**
87
97
  * This method allows to configure global defaults for the request configuration like method, auth, deduplication etc.
@@ -93,6 +103,7 @@ export declare class Adapter<AdapterOptions, MethodType extends string, StatusTy
93
103
  setAdapterDefaults: (callback: (request: ExtendRequest<RequestInstance, {
94
104
  client: Client<any, Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>>;
95
105
  }>) => AdapterOptions) => this;
106
+ /** Set a custom mapping for internal adapter errors before they are returned in the response. */
96
107
  setInternalErrorMapping: (callback: (error: ReturnType<typeof getErrorMessage>) => any) => this;
97
108
  /**
98
109
  * Set the custom header mapping function
@@ -103,23 +114,29 @@ export declare class Adapter<AdapterOptions, MethodType extends string, StatusTy
103
114
  */
104
115
  setPayloadMapper: <NewMapper extends AdapterPayloadMappingType>(payloadMapper: NewMapper) => Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, NewMapper>;
105
116
  /**
106
- * Set the request payload mapping function which get triggered before request get sent
117
+ * Set the endpoint mapping function which transforms the endpoint string before the request is sent
107
118
  */
108
119
  setEndpointMapper: <NewEndpointMapper extends EndpointMapper<EndpointType>>(endpointMapper: NewEndpointMapper) => Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, NewEndpointMapper, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>;
109
120
  /**
110
121
  * Set the query params mapping function which get triggered before request get sent
111
122
  */
112
123
  setQueryParamsMapper: <NewQueryParamsMapper extends QueryParamsMapper<QueryParams>>(queryParamsMapper: NewQueryParamsMapper) => Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, NewQueryParamsMapper, HeaderMapperType, PayloadMapperType>;
124
+ /** Set the configuration object passed as the second argument to the query params mapper. */
113
125
  setQueryParamsMapperConfig: <NewQueryParamsMapperConfig extends Parameters<QueryParamsMapperType>[1]>(config: NewQueryParamsMapperConfig) => this;
126
+ /** Set the configuration object passed as the second argument to the header mapper. */
114
127
  setHeaderMapperConfig: <NewHeaderMapperConfig extends Parameters<HeaderMapperType>[1]>(config: NewHeaderMapperConfig) => this;
128
+ /** Set the configuration object passed as the second argument to the endpoint mapper. */
115
129
  setEndpointMapperConfig: <NewEndpointMapperConfig extends Parameters<EndpointMapperType>[1]>(config: NewEndpointMapperConfig) => this;
130
+ /** Set the configuration object passed as the second argument to the payload mapper. */
116
131
  setPayloadMapperConfig: <NewPayloadMapperConfig extends Parameters<PayloadMapperType>[1]>(config: NewPayloadMapperConfig) => this;
117
132
  /**
118
133
  * ********************
119
134
  * Fetching
120
135
  * ********************
121
136
  */
137
+ /** Set the fetcher function that performs the actual network request. Must be called before any request can be executed. */
122
138
  setFetcher(fetcher: AdapterFetcherType<Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>>): this;
139
+ /** Execute a request through the adapter pipeline: maps endpoint/headers/payload, runs plugins, then calls the fetcher. */
123
140
  fetch(request: ExtendRequest<RequestInstance, {
124
141
  client: Client<any, Adapter<AdapterOptions, MethodType, StatusType, Extra, QueryParams, DefaultQueryParams, EndpointType, EndpointMapperType, QueryParamsMapperType, HeaderMapperType, PayloadMapperType>>;
125
142
  }>, requestId: string): Promise<RequestResponseType<RequestInstance>>;