@celljs/http 4.3.0 → 4.4.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 (55) hide show
  1. package/README.md +66 -1
  2. package/cell.schema.json +17 -0
  3. package/cell.yml +4 -5
  4. package/esm/common/client/client-protocol.d.ts +51 -5
  5. package/esm/common/client/client-protocol.js.map +1 -1
  6. package/esm/common/client/default-rest-operations.d.ts +30 -0
  7. package/esm/common/client/default-rest-operations.js +224 -0
  8. package/esm/common/client/default-rest-operations.js.map +1 -0
  9. package/esm/common/client/http-client-error.d.ts +25 -0
  10. package/esm/common/client/http-client-error.js +22 -0
  11. package/esm/common/client/http-client-error.js.map +1 -0
  12. package/esm/common/client/index.d.ts +3 -0
  13. package/esm/common/client/index.js +3 -0
  14. package/esm/common/client/index.js.map +1 -1
  15. package/esm/common/client/interceptor-manager.d.ts +14 -0
  16. package/esm/common/client/interceptor-manager.js +27 -0
  17. package/esm/common/client/interceptor-manager.js.map +1 -0
  18. package/esm/common/client/rest-operations-factory.d.ts +2 -3
  19. package/esm/common/client/rest-operations-factory.js +4 -4
  20. package/esm/common/client/rest-operations-factory.js.map +1 -1
  21. package/lib/common/client/client-protocol.d.ts +51 -5
  22. package/lib/common/client/client-protocol.d.ts.map +1 -1
  23. package/lib/common/client/client-protocol.js.map +1 -1
  24. package/lib/common/client/default-rest-operations.d.ts +31 -0
  25. package/lib/common/client/default-rest-operations.d.ts.map +1 -0
  26. package/lib/common/client/default-rest-operations.js +228 -0
  27. package/lib/common/client/default-rest-operations.js.map +1 -0
  28. package/lib/common/client/default-rest-operations.spec.d.ts +2 -0
  29. package/lib/common/client/default-rest-operations.spec.d.ts.map +1 -0
  30. package/lib/common/client/default-rest-operations.spec.js +168 -0
  31. package/lib/common/client/default-rest-operations.spec.js.map +1 -0
  32. package/lib/common/client/http-client-error.d.ts +26 -0
  33. package/lib/common/client/http-client-error.d.ts.map +1 -0
  34. package/lib/common/client/http-client-error.js +26 -0
  35. package/lib/common/client/http-client-error.js.map +1 -0
  36. package/lib/common/client/index.d.ts +3 -0
  37. package/lib/common/client/index.d.ts.map +1 -1
  38. package/lib/common/client/index.js +3 -0
  39. package/lib/common/client/index.js.map +1 -1
  40. package/lib/common/client/interceptor-manager.d.ts +15 -0
  41. package/lib/common/client/interceptor-manager.d.ts.map +1 -0
  42. package/lib/common/client/interceptor-manager.js +31 -0
  43. package/lib/common/client/interceptor-manager.js.map +1 -0
  44. package/lib/common/client/rest-operations-factory.d.ts +2 -3
  45. package/lib/common/client/rest-operations-factory.d.ts.map +1 -1
  46. package/lib/common/client/rest-operations-factory.js +4 -7
  47. package/lib/common/client/rest-operations-factory.js.map +1 -1
  48. package/package.json +4 -4
  49. package/src/common/client/client-protocol.ts +53 -5
  50. package/src/common/client/default-rest-operations.spec.ts +190 -0
  51. package/src/common/client/default-rest-operations.ts +237 -0
  52. package/src/common/client/http-client-error.ts +31 -0
  53. package/src/common/client/index.ts +3 -0
  54. package/src/common/client/interceptor-manager.ts +33 -0
  55. package/src/common/client/rest-operations-factory.ts +5 -5
@@ -0,0 +1,237 @@
1
+ import type { RequestConfig, RestOperations, RestResponse } from './client-protocol';
2
+ import { HttpClientError } from './http-client-error';
3
+ import { InterceptorManager } from './interceptor-manager';
4
+
5
+ const ABSOLUTE_URL = /^([a-z][a-z\d+\-.]*:)?\/\//i;
6
+
7
+ /** `RestOperations` on the global `fetch` of the runtime (Node.js 18+, Bun, Deno, workerd, browsers). */
8
+ export class DefaultRestOperations implements RestOperations {
9
+ readonly interceptors = {
10
+ request: new InterceptorManager<RequestConfig>(),
11
+ response: new InterceptorManager<RestResponse>()
12
+ };
13
+
14
+ constructor(readonly defaults: RequestConfig = {}) {}
15
+
16
+ request<T = any>(config: RequestConfig): Promise<RestResponse<T>> {
17
+ const sent = this.interceptors.request.apply(Promise.resolve(this.merge(config))).then(merged => this.send(merged));
18
+ return this.interceptors.response.apply(sent);
19
+ }
20
+
21
+ get<T = any>(url: string, config?: RequestConfig): Promise<RestResponse<T>> {
22
+ return this.request({ ...config, url, method: 'GET' });
23
+ }
24
+
25
+ delete<T = any>(url: string, config?: RequestConfig): Promise<RestResponse<T>> {
26
+ return this.request({ ...config, url, method: 'DELETE' });
27
+ }
28
+
29
+ head<T = any>(url: string, config?: RequestConfig): Promise<RestResponse<T>> {
30
+ return this.request({ ...config, url, method: 'HEAD' });
31
+ }
32
+
33
+ options<T = any>(url: string, config?: RequestConfig): Promise<RestResponse<T>> {
34
+ return this.request({ ...config, url, method: 'OPTIONS' });
35
+ }
36
+
37
+ post<T = any>(url: string, data?: unknown, config?: RequestConfig): Promise<RestResponse<T>> {
38
+ return this.request({ ...config, url, data, method: 'POST' });
39
+ }
40
+
41
+ put<T = any>(url: string, data?: unknown, config?: RequestConfig): Promise<RestResponse<T>> {
42
+ return this.request({ ...config, url, data, method: 'PUT' });
43
+ }
44
+
45
+ patch<T = any>(url: string, data?: unknown, config?: RequestConfig): Promise<RestResponse<T>> {
46
+ return this.request({ ...config, url, data, method: 'PATCH' });
47
+ }
48
+
49
+ protected merge(config: RequestConfig): RequestConfig {
50
+ return { ...this.defaults, ...config, headers: { ...this.defaults.headers, ...config.headers } };
51
+ }
52
+
53
+ protected async send(config: RequestConfig): Promise<RestResponse> {
54
+ const method = (config.method || 'GET').toUpperCase();
55
+ const url = this.buildURL(config);
56
+ const headers = this.buildHeaders(config);
57
+ const init: RequestInit & { duplex?: 'half' } = { method, headers };
58
+ if (method !== 'GET' && method !== 'HEAD') {
59
+ init.body = this.serialize(config.data, headers);
60
+ if (typeof ReadableStream !== 'undefined' && init.body instanceof ReadableStream) {
61
+ init.duplex = 'half';
62
+ }
63
+ }
64
+ // Only browsers send cookies by credentials; some server runtimes (workerd) reject the field.
65
+ if (config.withCredentials !== undefined && typeof window !== 'undefined') {
66
+ init.credentials = config.withCredentials ? 'include' : 'same-origin';
67
+ }
68
+
69
+ const controller = config.timeout ? new AbortController() : undefined;
70
+ let timedOut = false;
71
+ const timer = controller && setTimeout(() => {
72
+ timedOut = true;
73
+ controller.abort();
74
+ }, config.timeout);
75
+ const forward = () => controller?.abort();
76
+ if (controller && config.signal) {
77
+ if (config.signal.aborted) {
78
+ controller.abort();
79
+ } else {
80
+ config.signal.addEventListener('abort', forward, { once: true });
81
+ }
82
+ }
83
+ init.signal = controller?.signal ?? config.signal;
84
+
85
+ try {
86
+ const response = await fetch(url, init);
87
+ const result: RestResponse = {
88
+ status: response.status,
89
+ statusText: response.statusText,
90
+ headers: this.readHeaders(response.headers),
91
+ data: await this.parse(response, config),
92
+ config
93
+ };
94
+ const validate = config.validateStatus === undefined ? DefaultRestOperations.isSuccess : config.validateStatus;
95
+ if (validate && !validate(result.status)) {
96
+ throw new HttpClientError({
97
+ code: 'CELL_HTTP_BAD_STATUS',
98
+ message: `${method} ${url} answered ${result.status} ${result.statusText}`.trimEnd(),
99
+ hint: 'error.response holds the status, headers and body of the answer; pass validateStatus to resolve such statuses instead.',
100
+ config,
101
+ response: result
102
+ });
103
+ }
104
+ return result;
105
+ } catch (error) {
106
+ throw this.toError(error, config, `${method} ${url}`, timedOut);
107
+ } finally {
108
+ clearTimeout(timer);
109
+ config.signal?.removeEventListener('abort', forward);
110
+ }
111
+ }
112
+
113
+ protected toError(error: unknown, config: RequestConfig, request: string, timedOut: boolean): HttpClientError {
114
+ if (error instanceof HttpClientError) {
115
+ return error;
116
+ }
117
+ if (timedOut) {
118
+ return new HttpClientError({
119
+ code: 'CELL_HTTP_TIMEOUT',
120
+ message: `${request} took longer than ${config.timeout} ms`,
121
+ hint: 'Raise timeout in the request config or http.client in cell.yml, or check why the server is slow.',
122
+ config,
123
+ cause: error
124
+ });
125
+ }
126
+ if (config.signal?.aborted) {
127
+ return new HttpClientError({
128
+ code: 'CELL_HTTP_ABORTED',
129
+ message: `${request} was aborted`,
130
+ hint: 'The signal passed in the request config was aborted; nothing to fix unless that was not intended.',
131
+ config,
132
+ cause: error
133
+ });
134
+ }
135
+ return new HttpClientError({
136
+ code: 'CELL_HTTP_NETWORK',
137
+ message: `${request} failed: ${(error as Error)?.message ?? error}`,
138
+ hint: 'Check that the host is reachable and, on the server, that the URL is absolute; behind a proxy, Node.js uses HTTP_PROXY / HTTPS_PROXY only with NODE_USE_ENV_PROXY=1.',
139
+ config,
140
+ cause: error
141
+ });
142
+ }
143
+
144
+ protected buildURL(config: RequestConfig): string {
145
+ let url = config.url || '';
146
+ if (config.baseURL && !ABSOLUTE_URL.test(url)) {
147
+ url = url ? `${config.baseURL.replace(/\/+$/, '')}/${url.replace(/^\/+/, '')}` : config.baseURL;
148
+ }
149
+ const query = this.serializeParams(config.params);
150
+ if (!query) {
151
+ return url;
152
+ }
153
+ const hash = url.indexOf('#');
154
+ if (hash !== -1) {
155
+ url = url.slice(0, hash);
156
+ }
157
+ return url + (url.includes('?') ? '&' : '?') + query;
158
+ }
159
+
160
+ protected serializeParams(params: RequestConfig['params']): string {
161
+ if (!params) {
162
+ return '';
163
+ }
164
+ if (params instanceof URLSearchParams) {
165
+ return params.toString();
166
+ }
167
+ const search = new URLSearchParams();
168
+ for (const [key, value] of Object.entries(params)) {
169
+ for (const item of Array.isArray(value) ? value : [ value ]) {
170
+ if (item !== undefined && item !== null) {
171
+ search.append(key, item instanceof Date ? item.toISOString() : typeof item === 'object' ? JSON.stringify(item) : String(item));
172
+ }
173
+ }
174
+ }
175
+ return search.toString();
176
+ }
177
+
178
+ protected buildHeaders(config: RequestConfig): Headers {
179
+ const headers = new Headers();
180
+ for (const [name, value] of Object.entries(config.headers || {})) {
181
+ if (value !== undefined && value !== null) {
182
+ headers.set(name, String(value));
183
+ }
184
+ }
185
+ return headers;
186
+ }
187
+
188
+ protected serialize(data: unknown, headers: Headers): BodyInit | undefined {
189
+ if (data === undefined || data === null) {
190
+ return undefined;
191
+ }
192
+ if (typeof data === 'string' || data instanceof URLSearchParams || data instanceof ArrayBuffer || ArrayBuffer.isView(data)
193
+ || (typeof FormData !== 'undefined' && data instanceof FormData)
194
+ || (typeof Blob !== 'undefined' && data instanceof Blob)
195
+ || (typeof ReadableStream !== 'undefined' && data instanceof ReadableStream)) {
196
+ return data as BodyInit;
197
+ }
198
+ if (!headers.has('content-type')) {
199
+ headers.set('content-type', 'application/json');
200
+ }
201
+ return JSON.stringify(data);
202
+ }
203
+
204
+ protected async parse(response: Response, config: RequestConfig): Promise<any> {
205
+ switch (config.responseType) {
206
+ case 'stream':
207
+ return response.body;
208
+ case 'arraybuffer':
209
+ return response.arrayBuffer();
210
+ case 'blob':
211
+ return response.blob();
212
+ case 'text':
213
+ return response.text();
214
+ }
215
+ const text = await response.text();
216
+ if (!text) {
217
+ return text;
218
+ }
219
+ try {
220
+ return JSON.parse(text);
221
+ } catch {
222
+ return text;
223
+ }
224
+ }
225
+
226
+ protected readHeaders(headers: Headers): Record<string, string> {
227
+ const result: Record<string, string> = {};
228
+ headers.forEach((value, name) => {
229
+ result[name] = result[name] === undefined ? value : `${result[name]}, ${value}`;
230
+ });
231
+ return result;
232
+ }
233
+
234
+ protected static isSuccess(status: number): boolean {
235
+ return status >= 200 && status < 300;
236
+ }
237
+ }
@@ -0,0 +1,31 @@
1
+ import type { RequestConfig, RestResponse } from './client-protocol';
2
+
3
+ /**
4
+ * Why a request of `RestOperations` failed. `code` is stable and `hint` says how to fix it in one
5
+ * sentence (docs/design/agent-first.md R5); `response` is there when the server answered.
6
+ */
7
+ export class HttpClientError extends Error {
8
+ override readonly name = 'HttpClientError';
9
+ readonly code: HttpClientError.Code;
10
+ readonly hint: string;
11
+ readonly config: RequestConfig;
12
+ readonly response?: RestResponse;
13
+ override readonly cause?: unknown;
14
+
15
+ constructor(options: { code: HttpClientError.Code; message: string; hint: string; config: RequestConfig; response?: RestResponse; cause?: unknown }) {
16
+ super(options.message);
17
+ this.code = options.code;
18
+ this.hint = options.hint;
19
+ this.config = options.config;
20
+ this.response = options.response;
21
+ this.cause = options.cause;
22
+ }
23
+ }
24
+
25
+ export namespace HttpClientError {
26
+ export type Code = 'CELL_HTTP_BAD_STATUS' | 'CELL_HTTP_TIMEOUT' | 'CELL_HTTP_ABORTED' | 'CELL_HTTP_NETWORK';
27
+
28
+ export function is(error: unknown, code?: Code): error is HttpClientError {
29
+ return error instanceof HttpClientError && (code === undefined || error.code === code);
30
+ }
31
+ }
@@ -1,2 +1,5 @@
1
1
  export * from './client-protocol';
2
+ export * from './interceptor-manager';
3
+ export * from './http-client-error';
4
+ export * from './default-rest-operations';
2
5
  export * from './rest-operations-factory';
@@ -0,0 +1,33 @@
1
+ export interface Interceptor<V> {
2
+ fulfilled?: (value: V) => V | Promise<V>;
3
+ rejected?: (error: any) => any;
4
+ }
5
+
6
+ /** Interceptors run in the order they were added, each one on the result of the previous one. */
7
+ export class InterceptorManager<V> {
8
+ protected readonly handlers = new Map<number, Interceptor<V>>();
9
+ protected nextId = 0;
10
+
11
+ /** Returns the id to `eject` the interceptor with. */
12
+ use(fulfilled?: Interceptor<V>['fulfilled'], rejected?: Interceptor<V>['rejected']): number {
13
+ const id = this.nextId++;
14
+ this.handlers.set(id, { fulfilled, rejected });
15
+ return id;
16
+ }
17
+
18
+ eject(id: number): void {
19
+ this.handlers.delete(id);
20
+ }
21
+
22
+ clear(): void {
23
+ this.handlers.clear();
24
+ }
25
+
26
+ apply(value: Promise<V>): Promise<V> {
27
+ let result = value;
28
+ for (const { fulfilled, rejected } of this.handlers.values()) {
29
+ result = result.then(fulfilled, rejected);
30
+ }
31
+ return result;
32
+ }
33
+ }
@@ -1,15 +1,15 @@
1
- import { RestOperationsFactory, RestOperations } from './client-protocol';
2
- import axios, { AxiosRequestConfig } from 'axios';
3
1
  import { Component, Value } from '@celljs/core';
2
+ import { RequestConfig, RestOperations, RestOperationsFactory } from './client-protocol';
3
+ import { DefaultRestOperations } from './default-rest-operations';
4
4
 
5
5
  @Component(RestOperationsFactory)
6
6
  export class DefaultRestOperationsFactory implements RestOperationsFactory {
7
7
 
8
- @Value('cell.client.config')
9
- protected readonly clientConfig: AxiosRequestConfig;
8
+ @Value('http.client')
9
+ protected readonly clientConfig?: RequestConfig;
10
10
 
11
11
  create(): RestOperations {
12
- return axios.create(this.clientConfig);
12
+ return new DefaultRestOperations(this.clientConfig);
13
13
  }
14
14
 
15
15
  }