@akilin/api-kit 0.0.0-stage → 0.1.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.
- package/LICENSE +21 -0
- package/README.md +277 -2
- package/dist/api-error.d.ts +100 -0
- package/dist/api-error.js +30 -0
- package/dist/body.d.ts +2 -0
- package/dist/body.js +20 -0
- package/dist/create-api.d.ts +65 -0
- package/dist/create-api.js +48 -0
- package/dist/deadline.d.ts +16 -0
- package/dist/deadline.js +56 -0
- package/dist/index.d.ts +8 -0
- package/dist/index.js +2 -0
- package/dist/paged-data.d.ts +4 -0
- package/dist/paged-data.js +1 -0
- package/dist/query.d.ts +5 -0
- package/dist/query.js +22 -0
- package/dist/request.d.ts +80 -0
- package/dist/request.js +179 -0
- package/dist/response.d.ts +17 -0
- package/dist/response.js +79 -0
- package/dist/send.d.ts +50 -0
- package/dist/send.js +68 -0
- package/dist/telemetry.d.ts +15 -0
- package/dist/telemetry.js +67 -0
- package/dist/url.d.ts +10 -0
- package/dist/url.js +39 -0
- package/package.json +41 -4
package/dist/index.d.ts
ADDED
|
@@ -0,0 +1,8 @@
|
|
|
1
|
+
export { createApi, type Api, type ApiOptions, type RequestOptions } from './create-api.js';
|
|
2
|
+
export { ApiError, type AbortedError, type ApiErrorInit, type CodeOf, type FieldError, type NetworkError, type ProblemError, type UnexpectedError, } from './api-error.js';
|
|
3
|
+
export type { PagedData } from './paged-data.js';
|
|
4
|
+
export type { Query, QueryValue } from './query.js';
|
|
5
|
+
export type { Fetch, RequestDefaults, RequestHeaders } from './send.js';
|
|
6
|
+
export type { ApiResult, ResponseInfo } from './response.js';
|
|
7
|
+
export type { TelemetryOptions } from './telemetry.js';
|
|
8
|
+
export type { ApiRequest, Policies, StatusError } from './request.js';
|
package/dist/index.js
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
export {};
|
package/dist/query.d.ts
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
/** Objects aren't allowed, so nothing gets sent as `[object Object]` by accident. */
|
|
2
|
+
export type QueryValue = string | number | boolean | Date | null | undefined;
|
|
3
|
+
/** Arrays become repeated keys (`tags=a&tags=b`). */
|
|
4
|
+
export type Query = Readonly<Record<string, QueryValue | readonly QueryValue[]>>;
|
|
5
|
+
export declare function withQuery(url: string, query: Query | undefined): string;
|
package/dist/query.js
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
1
|
+
// Encoded by hand with `encodeURIComponent`: the platform's URL helpers are incomplete in React Native.
|
|
2
|
+
export function withQuery(url, query) {
|
|
3
|
+
if (!query)
|
|
4
|
+
return url;
|
|
5
|
+
const pairs = [];
|
|
6
|
+
for (const [key, value] of Object.entries(query)) {
|
|
7
|
+
for (const item of Array.isArray(value) ? value : [value]) {
|
|
8
|
+
if (item === null || item === undefined)
|
|
9
|
+
continue;
|
|
10
|
+
const text = item instanceof Date ? item.toISOString() : String(item);
|
|
11
|
+
pairs.push(`${encodeURIComponent(key)}=${encodeURIComponent(text)}`);
|
|
12
|
+
}
|
|
13
|
+
}
|
|
14
|
+
if (pairs.length === 0)
|
|
15
|
+
return url;
|
|
16
|
+
// Before the fragment, if any: a query after `#` would be part of the fragment, never sent.
|
|
17
|
+
const hash = url.indexOf('#');
|
|
18
|
+
const path = hash < 0 ? url : url.slice(0, hash);
|
|
19
|
+
const fragment = hash < 0 ? '' : url.slice(hash);
|
|
20
|
+
const separator = !path.includes('?') ? '?' : /[?&]$/.test(path) ? '' : '&';
|
|
21
|
+
return `${path}${separator}${pairs.join('&')}${fragment}`;
|
|
22
|
+
}
|
|
@@ -0,0 +1,80 @@
|
|
|
1
|
+
import { type ApiError, type CodeOf, type AbortedError, type FieldError, type NetworkError, type ProblemError, type UnexpectedError } from './api-error.js';
|
|
2
|
+
import type { ApiResult, Outcome, ResponseInfo } from './response.js';
|
|
3
|
+
/** The three app-wide error policies of {@link ApiOptions}, all required. */
|
|
4
|
+
export interface Policies<E extends object = {}> {
|
|
5
|
+
/**
|
|
6
|
+
* A 401 no per-call handler claimed: a problem, or a 401 without one (an auth proxy's). No other policy gets
|
|
7
|
+
* it. An app without auth passes `() => {}`.
|
|
8
|
+
*/
|
|
9
|
+
readonly onUnauthorized: Handler<ProblemError<E> | UnexpectedError>;
|
|
10
|
+
/**
|
|
11
|
+
* An unexpected response no per-call handler claimed (a crash, say; a 401 goes to `onUnauthorized`), or a network
|
|
12
|
+
* failure, which no per-call handler can claim.
|
|
13
|
+
*/
|
|
14
|
+
readonly onUnexpected: Handler<UnexpectedError | NetworkError>;
|
|
15
|
+
/**
|
|
16
|
+
* A problem (an error with a `code`) no per-call handler claimed, e.g. to toast its translated code. It gets no
|
|
17
|
+
* 401, which goes to `onUnauthorized`, and no 5xx, which is kind `unexpected` and goes to `onUnexpected`. A call
|
|
18
|
+
* opts out with `.skipDefaultErrorCodeHandler()`.
|
|
19
|
+
*/
|
|
20
|
+
readonly defaultErrorCodeHandler: Handler<ProblemError<E>>;
|
|
21
|
+
}
|
|
22
|
+
/** What it returns is ignored; a promise (or any thenable) is awaited first. */
|
|
23
|
+
type Handler<A> = (arg: A) => unknown;
|
|
24
|
+
export declare class ApiRequest<T, E extends object = {}> implements PromiseLike<T> {
|
|
25
|
+
#private;
|
|
26
|
+
constructor(dispatch: () => Promise<Outcome<T>>, policies: Policies<E>);
|
|
27
|
+
/**
|
|
28
|
+
* Only 4xx problems reach the handler: every 5xx is kind `unexpected`, so use `.onStatus(503, …)` for one, whose error
|
|
29
|
+
* keeps the `code` and `payload`.
|
|
30
|
+
*/
|
|
31
|
+
on<C extends CodeOf<E>>(code: C, fn: Handler<ProblemError<E, C>>): this;
|
|
32
|
+
/**
|
|
33
|
+
* Handles any problem about one field of the request, whatever its code. A problem reports one field. A `.on`
|
|
34
|
+
* handler for the problem's code wins over this one.
|
|
35
|
+
*/
|
|
36
|
+
onFieldError(fn: Handler<FieldError<E>>): this;
|
|
37
|
+
/**
|
|
38
|
+
* Handles any error with this HTTP status: a problem, or an unexpected response (a 500 included). Network
|
|
39
|
+
* failures have no status.
|
|
40
|
+
*/
|
|
41
|
+
onStatus(status: number, fn: Handler<StatusError<E>>): this;
|
|
42
|
+
/**
|
|
43
|
+
* Observes every failed call, whatever the kind: runs after the per-call handler or the policy that dealt with the
|
|
44
|
+
* error, and before `.finally`. It claims nothing: `handled` stays as it was, and the policies run as if it weren't
|
|
45
|
+
* registered. It doesn't run when that handler or policy throws, nor for an aborted call.
|
|
46
|
+
*/
|
|
47
|
+
onAnyError(fn: Handler<Exclude<ApiError<E>, AbortedError>>): this;
|
|
48
|
+
/**
|
|
49
|
+
* For this call, a problem no per-call handler claimed doesn't go to `defaultErrorCodeHandler`: no policy gets it,
|
|
50
|
+
* and `handled` stays `false`. Nothing else changes: a 401 still goes to `onUnauthorized`, an unexpected response or
|
|
51
|
+
* a network failure to `onUnexpected`.
|
|
52
|
+
*/
|
|
53
|
+
skipDefaultErrorCodeHandler(): this;
|
|
54
|
+
/** Runs when the call succeeds, before `await` resolves. */
|
|
55
|
+
onSuccess(fn: (data: T, response: ResponseInfo) => unknown): this;
|
|
56
|
+
/**
|
|
57
|
+
* Runs once the call settles, whatever the outcome: after `.onSuccess`, or after the error handler (or the policy)
|
|
58
|
+
* and `.onAnyError`. Awaited before `await` / `.result()` settle; if it throws, they reject with what it threw.
|
|
59
|
+
*
|
|
60
|
+
* Not `Promise.prototype.finally`: it registers a callback on this request and returns the request itself (not a new
|
|
61
|
+
* promise), so the chain goes on; it may be registered once, and only before dispatch (it throws otherwise, like the
|
|
62
|
+
* other handlers); and it runs whether or not anything awaits the call.
|
|
63
|
+
*/
|
|
64
|
+
finally(fn: () => unknown): this;
|
|
65
|
+
/**
|
|
66
|
+
* Resolves with the data, or rejects: with the {@link ApiError} of a failed call, or with what a handler, a policy,
|
|
67
|
+
* `.onSuccess`, `.onAnyError` or `.finally` threw (a bug there is not swallowed), so the reason is `unknown`; check
|
|
68
|
+
* it with `instanceof ApiError`. The rejecting promise only exists once the builder is awaited, so fire-and-forget
|
|
69
|
+
* calls never cause unhandled rejections.
|
|
70
|
+
*/
|
|
71
|
+
then<R1 = T, R2 = never>(onFulfilled?: ((data: T) => R1 | PromiseLike<R1>) | null, onRejected?: ((reason: unknown) => R2 | PromiseLike<R2>) | null): Promise<R1 | R2>;
|
|
72
|
+
/**
|
|
73
|
+
* `await` without the API rejection: same handlers, and a failed call resolves with `{ ok: false, error }`
|
|
74
|
+
* instead of rejecting. A success also gives the response's status and headers. Like `await`, it still rejects if a
|
|
75
|
+
* handler, a policy or `.finally` throws: a bug there is not swallowed.
|
|
76
|
+
*/
|
|
77
|
+
result(): Promise<ApiResult<T, E>>;
|
|
78
|
+
}
|
|
79
|
+
export type StatusError<E extends object = {}> = ProblemError<E> | UnexpectedError;
|
|
80
|
+
export {};
|
package/dist/request.js
ADDED
|
@@ -0,0 +1,179 @@
|
|
|
1
|
+
import { markHandled, } from './api-error.js';
|
|
2
|
+
export class ApiRequest {
|
|
3
|
+
#outcome;
|
|
4
|
+
#codeHandlers = new Map();
|
|
5
|
+
#fieldErrorHandler;
|
|
6
|
+
#statusHandlers = new Map();
|
|
7
|
+
#anyErrorHandler;
|
|
8
|
+
#skipsDefaultErrorCodeHandler = false;
|
|
9
|
+
#successHandler;
|
|
10
|
+
#finallyHandler;
|
|
11
|
+
#dispatched = false;
|
|
12
|
+
#policies;
|
|
13
|
+
constructor(dispatch, policies) {
|
|
14
|
+
this.#policies = policies;
|
|
15
|
+
// Dispatch on the next microtask: handlers chained synchronously onto the builder are registered first.
|
|
16
|
+
this.#outcome = Promise.resolve().then(async () => {
|
|
17
|
+
this.#dispatched = true;
|
|
18
|
+
const outcome = await dispatch();
|
|
19
|
+
// No catch: a handler that throws rejects `await` / `.result()` once `.finally` has run. A bug in a handler is
|
|
20
|
+
// not swallowed.
|
|
21
|
+
try {
|
|
22
|
+
if (outcome.ok)
|
|
23
|
+
await this.#successHandler?.(outcome.data, outcome.response);
|
|
24
|
+
else
|
|
25
|
+
await this.#handle(outcome.error);
|
|
26
|
+
}
|
|
27
|
+
finally {
|
|
28
|
+
await this.#finallyHandler?.();
|
|
29
|
+
}
|
|
30
|
+
return outcome;
|
|
31
|
+
});
|
|
32
|
+
}
|
|
33
|
+
/**
|
|
34
|
+
* Only 4xx problems reach the handler: every 5xx is kind `unexpected`, so use `.onStatus(503, …)` for one, whose error
|
|
35
|
+
* keeps the `code` and `payload`.
|
|
36
|
+
*/
|
|
37
|
+
on(code, fn) {
|
|
38
|
+
this.#assertOpen('.on');
|
|
39
|
+
if (this.#codeHandlers.has(code))
|
|
40
|
+
throw duplicate(`.on('${code}')`);
|
|
41
|
+
this.#codeHandlers.set(code, fn);
|
|
42
|
+
return this;
|
|
43
|
+
}
|
|
44
|
+
/**
|
|
45
|
+
* Handles any problem about one field of the request, whatever its code. A problem reports one field. A `.on`
|
|
46
|
+
* handler for the problem's code wins over this one.
|
|
47
|
+
*/
|
|
48
|
+
onFieldError(fn) {
|
|
49
|
+
this.#fieldErrorHandler = this.#registerOnce('.onFieldError', this.#fieldErrorHandler, fn);
|
|
50
|
+
return this;
|
|
51
|
+
}
|
|
52
|
+
/**
|
|
53
|
+
* Handles any error with this HTTP status: a problem, or an unexpected response (a 500 included). Network
|
|
54
|
+
* failures have no status.
|
|
55
|
+
*/
|
|
56
|
+
onStatus(status, fn) {
|
|
57
|
+
this.#assertOpen('.onStatus');
|
|
58
|
+
if (this.#statusHandlers.has(status))
|
|
59
|
+
throw duplicate(`.onStatus(${status})`);
|
|
60
|
+
this.#statusHandlers.set(status, fn);
|
|
61
|
+
return this;
|
|
62
|
+
}
|
|
63
|
+
/**
|
|
64
|
+
* Observes every failed call, whatever the kind: runs after the per-call handler or the policy that dealt with the
|
|
65
|
+
* error, and before `.finally`. It claims nothing: `handled` stays as it was, and the policies run as if it weren't
|
|
66
|
+
* registered. It doesn't run when that handler or policy throws, nor for an aborted call.
|
|
67
|
+
*/
|
|
68
|
+
onAnyError(fn) {
|
|
69
|
+
this.#anyErrorHandler = this.#registerOnce('.onAnyError', this.#anyErrorHandler, fn);
|
|
70
|
+
return this;
|
|
71
|
+
}
|
|
72
|
+
/**
|
|
73
|
+
* For this call, a problem no per-call handler claimed doesn't go to `defaultErrorCodeHandler`: no policy gets it,
|
|
74
|
+
* and `handled` stays `false`. Nothing else changes: a 401 still goes to `onUnauthorized`, an unexpected response or
|
|
75
|
+
* a network failure to `onUnexpected`.
|
|
76
|
+
*/
|
|
77
|
+
skipDefaultErrorCodeHandler() {
|
|
78
|
+
this.#assertOpen('.skipDefaultErrorCodeHandler');
|
|
79
|
+
this.#skipsDefaultErrorCodeHandler = true;
|
|
80
|
+
return this;
|
|
81
|
+
}
|
|
82
|
+
/** Runs when the call succeeds, before `await` resolves. */
|
|
83
|
+
onSuccess(fn) {
|
|
84
|
+
this.#successHandler = this.#registerOnce('.onSuccess', this.#successHandler, fn);
|
|
85
|
+
return this;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Runs once the call settles, whatever the outcome: after `.onSuccess`, or after the error handler (or the policy)
|
|
89
|
+
* and `.onAnyError`. Awaited before `await` / `.result()` settle; if it throws, they reject with what it threw.
|
|
90
|
+
*
|
|
91
|
+
* Not `Promise.prototype.finally`: it registers a callback on this request and returns the request itself (not a new
|
|
92
|
+
* promise), so the chain goes on; it may be registered once, and only before dispatch (it throws otherwise, like the
|
|
93
|
+
* other handlers); and it runs whether or not anything awaits the call.
|
|
94
|
+
*/
|
|
95
|
+
finally(fn) {
|
|
96
|
+
this.#finallyHandler = this.#registerOnce('.finally', this.#finallyHandler, fn);
|
|
97
|
+
return this;
|
|
98
|
+
}
|
|
99
|
+
/**
|
|
100
|
+
* Resolves with the data, or rejects: with the {@link ApiError} of a failed call, or with what a handler, a policy,
|
|
101
|
+
* `.onSuccess`, `.onAnyError` or `.finally` threw (a bug there is not swallowed), so the reason is `unknown`; check
|
|
102
|
+
* it with `instanceof ApiError`. The rejecting promise only exists once the builder is awaited, so fire-and-forget
|
|
103
|
+
* calls never cause unhandled rejections.
|
|
104
|
+
*/
|
|
105
|
+
then(onFulfilled, onRejected) {
|
|
106
|
+
return this.#outcome
|
|
107
|
+
.then((outcome) => (outcome.ok ? outcome.data : Promise.reject(outcome.error)))
|
|
108
|
+
.then(onFulfilled, onRejected);
|
|
109
|
+
}
|
|
110
|
+
/**
|
|
111
|
+
* `await` without the API rejection: same handlers, and a failed call resolves with `{ ok: false, error }`
|
|
112
|
+
* instead of rejecting. A success also gives the response's status and headers. Like `await`, it still rejects if a
|
|
113
|
+
* handler, a policy or `.finally` throws: a bug there is not swallowed.
|
|
114
|
+
*/
|
|
115
|
+
result() {
|
|
116
|
+
// The cast: `send` parses bodies untyped, so only here can the codes and payloads be read as `E`'s.
|
|
117
|
+
return this.#outcome;
|
|
118
|
+
}
|
|
119
|
+
#assertOpen(method) {
|
|
120
|
+
if (this.#dispatched) {
|
|
121
|
+
throw new Error(`${method}() was called after the request was dispatched. Chain handlers synchronously onto the request call, before any await.`);
|
|
122
|
+
}
|
|
123
|
+
}
|
|
124
|
+
#registerOnce(method, current, fn) {
|
|
125
|
+
this.#assertOpen(method);
|
|
126
|
+
if (current)
|
|
127
|
+
throw duplicate(`${method}()`);
|
|
128
|
+
return fn;
|
|
129
|
+
}
|
|
130
|
+
async #handle(error) {
|
|
131
|
+
// The caller cancelled the call: it is theirs alone, not an error for a handler or a policy to deal with.
|
|
132
|
+
if (error.kind === 'aborted')
|
|
133
|
+
return;
|
|
134
|
+
const run = this.#handlerFor(error);
|
|
135
|
+
if (run) {
|
|
136
|
+
markHandled(error);
|
|
137
|
+
await run();
|
|
138
|
+
}
|
|
139
|
+
else {
|
|
140
|
+
await this.#policyFor(error)?.();
|
|
141
|
+
}
|
|
142
|
+
await this.#anyErrorHandler?.(error);
|
|
143
|
+
}
|
|
144
|
+
#policyFor(error) {
|
|
145
|
+
const { onUnauthorized, onUnexpected, defaultErrorCodeHandler } = this.#policies;
|
|
146
|
+
switch (error.kind) {
|
|
147
|
+
case 'problem':
|
|
148
|
+
if (error.status === 401)
|
|
149
|
+
return () => onUnauthorized(error);
|
|
150
|
+
if (this.#skipsDefaultErrorCodeHandler)
|
|
151
|
+
return undefined;
|
|
152
|
+
return () => defaultErrorCodeHandler(error);
|
|
153
|
+
case 'unexpected':
|
|
154
|
+
// A 401 without a problem body (an auth proxy's, say) is still a sign-in to redo, not a crash.
|
|
155
|
+
return error.status === 401 ? () => onUnauthorized(error) : () => onUnexpected(error);
|
|
156
|
+
case 'network':
|
|
157
|
+
return () => onUnexpected(error);
|
|
158
|
+
}
|
|
159
|
+
}
|
|
160
|
+
#handlerFor(error) {
|
|
161
|
+
if (error.kind === 'problem') {
|
|
162
|
+
const onCode = this.#codeHandlers.get(error.code);
|
|
163
|
+
if (onCode)
|
|
164
|
+
return () => onCode(error);
|
|
165
|
+
const onFieldError = this.#fieldErrorHandler;
|
|
166
|
+
if (onFieldError && error.field !== undefined)
|
|
167
|
+
return () => onFieldError(error);
|
|
168
|
+
}
|
|
169
|
+
if (error.kind === 'problem' || error.kind === 'unexpected') {
|
|
170
|
+
const onStatus = this.#statusHandlers.get(error.status);
|
|
171
|
+
if (onStatus)
|
|
172
|
+
return () => onStatus(error);
|
|
173
|
+
}
|
|
174
|
+
return undefined;
|
|
175
|
+
}
|
|
176
|
+
}
|
|
177
|
+
function duplicate(registration) {
|
|
178
|
+
return new Error(`${registration} was already registered for this request. Register each handler once.`);
|
|
179
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import { ApiError, type UntypedErrors } from './api-error.js';
|
|
2
|
+
export interface ResponseInfo {
|
|
3
|
+
readonly status: number;
|
|
4
|
+
readonly headers: Headers;
|
|
5
|
+
}
|
|
6
|
+
/** What `.result()` resolves with. `E` is the app's error map, as for {@link ApiError}. */
|
|
7
|
+
export type ApiResult<T, E extends object = {}> = {
|
|
8
|
+
readonly ok: true;
|
|
9
|
+
readonly data: T;
|
|
10
|
+
readonly response: ResponseInfo;
|
|
11
|
+
} | {
|
|
12
|
+
readonly ok: false;
|
|
13
|
+
readonly error: ApiError<E>;
|
|
14
|
+
};
|
|
15
|
+
/** A result before it is typed as the app's error map. */
|
|
16
|
+
export type Outcome<T> = ApiResult<T, UntypedErrors>;
|
|
17
|
+
export declare function read(response: Response): Promise<Outcome<unknown>>;
|
package/dist/response.js
ADDED
|
@@ -0,0 +1,79 @@
|
|
|
1
|
+
import { ApiError } from './api-error.js';
|
|
2
|
+
export async function read(response) {
|
|
3
|
+
if (response.ok)
|
|
4
|
+
return readSuccess(response);
|
|
5
|
+
const text = await response.text();
|
|
6
|
+
const { body, cause } = parseProblem(response, text);
|
|
7
|
+
const code = body?.['code'];
|
|
8
|
+
const payload = body && payloadOf(body);
|
|
9
|
+
if (response.status >= 500 || !body || typeof code !== 'string' || !payload) {
|
|
10
|
+
return unexpected(response, text, body, cause, payload);
|
|
11
|
+
}
|
|
12
|
+
return { ok: false, error: problemError(response, body, code, payload) };
|
|
13
|
+
}
|
|
14
|
+
async function readSuccess(response) {
|
|
15
|
+
const info = { status: response.status, headers: response.headers };
|
|
16
|
+
const success = (data) => ({ ok: true, data, response: info });
|
|
17
|
+
const text = await response.text();
|
|
18
|
+
if (text.trim() === '')
|
|
19
|
+
return success(undefined);
|
|
20
|
+
try {
|
|
21
|
+
return success(JSON.parse(text));
|
|
22
|
+
}
|
|
23
|
+
catch (cause) {
|
|
24
|
+
// Typically an HTML page (a proxy, an SPA fallback) where the API should have answered.
|
|
25
|
+
return unexpected(response, text, undefined, cause);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
28
|
+
function parseProblem(response, text) {
|
|
29
|
+
const mediaType = response.headers.get('Content-Type')?.split(';')[0]?.trim().toLowerCase();
|
|
30
|
+
if (mediaType !== 'application/problem+json')
|
|
31
|
+
return {};
|
|
32
|
+
try {
|
|
33
|
+
const body = JSON.parse(text);
|
|
34
|
+
return typeof body === 'object' && body !== null ? { body: body } : {};
|
|
35
|
+
}
|
|
36
|
+
catch (cause) {
|
|
37
|
+
return { cause };
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
function unexpected(response, responseText, body, cause, payload) {
|
|
41
|
+
const code = body?.['code'];
|
|
42
|
+
const problem = typeof code === 'string' ? { code, ...(payload && { payload }) } : {};
|
|
43
|
+
return {
|
|
44
|
+
ok: false,
|
|
45
|
+
error: new ApiError({
|
|
46
|
+
kind: 'unexpected',
|
|
47
|
+
status: response.status,
|
|
48
|
+
headers: response.headers,
|
|
49
|
+
traceId: traceIdOf(body),
|
|
50
|
+
responseText,
|
|
51
|
+
cause,
|
|
52
|
+
...problem,
|
|
53
|
+
}),
|
|
54
|
+
};
|
|
55
|
+
}
|
|
56
|
+
function traceIdOf(body) {
|
|
57
|
+
const traceId = body?.['traceId'];
|
|
58
|
+
return typeof traceId === 'string' ? traceId : undefined;
|
|
59
|
+
}
|
|
60
|
+
function problemError(response, body, code, payload) {
|
|
61
|
+
const init = {
|
|
62
|
+
kind: 'problem',
|
|
63
|
+
code,
|
|
64
|
+
status: response.status,
|
|
65
|
+
headers: response.headers,
|
|
66
|
+
payload,
|
|
67
|
+
traceId: traceIdOf(body),
|
|
68
|
+
};
|
|
69
|
+
const field = body['field'];
|
|
70
|
+
return new ApiError(typeof field === 'string' ? { ...init, field } : init);
|
|
71
|
+
}
|
|
72
|
+
function payloadOf(body) {
|
|
73
|
+
const payload = body['payload'];
|
|
74
|
+
if (payload === undefined)
|
|
75
|
+
return {};
|
|
76
|
+
return typeof payload === 'object' && payload !== null && !Array.isArray(payload)
|
|
77
|
+
? payload
|
|
78
|
+
: undefined;
|
|
79
|
+
}
|
package/dist/send.d.ts
ADDED
|
@@ -0,0 +1,50 @@
|
|
|
1
|
+
import { type Outcome } from './response.js';
|
|
2
|
+
/** Names are case-insensitive: a later `content-type` replaces an earlier `Content-Type`. */
|
|
3
|
+
export type RequestHeaders = Readonly<Record<string, string>>;
|
|
4
|
+
export type Fetch = (url: string, init: RequestInit) => Promise<Response>;
|
|
5
|
+
export interface SendRequest {
|
|
6
|
+
readonly method: 'GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE';
|
|
7
|
+
readonly url: string;
|
|
8
|
+
readonly body?: RequestInit['body'];
|
|
9
|
+
readonly timeout?: number;
|
|
10
|
+
readonly headers?: RequestHeaders;
|
|
11
|
+
/** The caller's: once it aborts, the request is cancelled and fails as kind `aborted`. */
|
|
12
|
+
readonly signal?: AbortSignal;
|
|
13
|
+
/** fetch's `keepalive`: the request outlives the page (a navigation, a reload). Only telemetry traces use it. */
|
|
14
|
+
readonly keepalive?: boolean;
|
|
15
|
+
/** `url` is fetched as it is, not joined with `baseUrl`. Only telemetry traces use it: their url has its own rule. */
|
|
16
|
+
readonly unprefixed?: boolean;
|
|
17
|
+
}
|
|
18
|
+
export interface RequestDefaults {
|
|
19
|
+
/**
|
|
20
|
+
* Headers for every request to the API, telemetry traces included: an object, or a function called for each request (a bearer
|
|
21
|
+
* token that changes), possibly async (a token refresh). A call's own `headers` override these by name, whatever the
|
|
22
|
+
* case. If the function throws or rejects, nothing is sent and the call fails as kind `network`, with what it threw as
|
|
23
|
+
* `cause`. They go only to the origin of `baseUrl` (with a relative or empty `baseUrl`, the page's): an absolute
|
|
24
|
+
* per-call url on another origin gets none of them, and the function isn't called for it. Pass a call's own `headers`
|
|
25
|
+
* to send some there.
|
|
26
|
+
*/
|
|
27
|
+
readonly headers?: RequestHeaders | (() => RequestHeaders | Promise<RequestHeaders>);
|
|
28
|
+
/**
|
|
29
|
+
* fetch's `credentials` for every request, telemetry traces included. Default: fetch's own, `same-origin`, which
|
|
30
|
+
* sends no cookies to a `baseUrl` on another origin: pass `include` for cookie auth there (the server must allow
|
|
31
|
+
* credentialed CORS).
|
|
32
|
+
*/
|
|
33
|
+
readonly credentials?: 'omit' | 'same-origin' | 'include';
|
|
34
|
+
/**
|
|
35
|
+
* The `fetch` to call, e.g. a test double, a server-side one, or a wrapper that adds behaviour. Default: the global
|
|
36
|
+
* `fetch`, looked up at each request.
|
|
37
|
+
*/
|
|
38
|
+
readonly fetch?: Fetch;
|
|
39
|
+
/**
|
|
40
|
+
* How long a request may take, in ms, telemetry traces included: from the call (the `headers` function included) to
|
|
41
|
+
* the end of the response body. Default: 30 000. `0`, `Infinity` or anything from 2³¹−1 up turns the timeout off; a
|
|
42
|
+
* negative or `NaN` one throws a `RangeError` at `createApi`. A request over it is cancelled and fails as kind
|
|
43
|
+
* `network`, with a `TimeoutError` as `cause`. A call's own `timeout` overrides this one.
|
|
44
|
+
*/
|
|
45
|
+
readonly timeout?: number;
|
|
46
|
+
}
|
|
47
|
+
export interface SendConfig extends RequestDefaults {
|
|
48
|
+
readonly baseUrl: string;
|
|
49
|
+
}
|
|
50
|
+
export declare function send<T>(config: SendConfig, request: SendRequest): Promise<Outcome<T>>;
|
package/dist/send.js
ADDED
|
@@ -0,0 +1,68 @@
|
|
|
1
|
+
import { ApiError } from './api-error.js';
|
|
2
|
+
import { aborted, defaultTimeoutMs, startDeadline } from './deadline.js';
|
|
3
|
+
import { read } from './response.js';
|
|
4
|
+
import { isSameOrigin, joinUrl } from './url.js';
|
|
5
|
+
// Every request goes through here, telemetry traces included: `fetch` is called nowhere else, so every option
|
|
6
|
+
// (`headers`, `credentials`, a custom `fetch`) has one place to plug in.
|
|
7
|
+
export async function send(config, request) {
|
|
8
|
+
if (request.signal?.aborted)
|
|
9
|
+
return aborted(request.signal);
|
|
10
|
+
const deadline = startDeadline(request.timeout ?? config.timeout ?? defaultTimeoutMs, request.signal);
|
|
11
|
+
try {
|
|
12
|
+
// A race, so the call ends at its deadline or the caller's abort whatever it is waiting for: a `headers` function
|
|
13
|
+
// that never returns and a `fetch` that ignores its signal included.
|
|
14
|
+
return await Promise.race([attempt(config, request, deadline.signal), deadline.expired]);
|
|
15
|
+
}
|
|
16
|
+
finally {
|
|
17
|
+
deadline.clear();
|
|
18
|
+
}
|
|
19
|
+
}
|
|
20
|
+
async function attempt(config, request, signal) {
|
|
21
|
+
try {
|
|
22
|
+
const url = request.unprefixed ? request.url : joinUrl(config.baseUrl, request.url);
|
|
23
|
+
const init = await requestInit(config, request, url, signal);
|
|
24
|
+
// Cancelled while the `headers` function ran: the call has already failed, so send nothing.
|
|
25
|
+
if (signal?.aborted)
|
|
26
|
+
return { ok: false, error: new ApiError({ kind: 'network', cause: signal.reason }) };
|
|
27
|
+
const fetchFn = config.fetch ?? fetch;
|
|
28
|
+
const response = await fetchFn(url, init);
|
|
29
|
+
return (await read(response));
|
|
30
|
+
}
|
|
31
|
+
catch (cause) {
|
|
32
|
+
return { ok: false, error: new ApiError({ kind: 'network', cause }) };
|
|
33
|
+
}
|
|
34
|
+
}
|
|
35
|
+
async function requestInit(config, request, url, signal) {
|
|
36
|
+
const init = { method: request.method };
|
|
37
|
+
if (signal)
|
|
38
|
+
init.signal = signal;
|
|
39
|
+
if (config.credentials)
|
|
40
|
+
init.credentials = config.credentials;
|
|
41
|
+
if (request.body !== undefined)
|
|
42
|
+
init.body = request.body;
|
|
43
|
+
if (request.keepalive)
|
|
44
|
+
init.keepalive = true;
|
|
45
|
+
const headers = {};
|
|
46
|
+
// A string body is JSON that `jsonBody` serialized. Any other body (`FormData`, `Blob`, `URLSearchParams`, bytes)
|
|
47
|
+
// gets no content type: fetch sets it (the multipart boundary, the Blob's type, a form) or sends none.
|
|
48
|
+
if (typeof request.body === 'string')
|
|
49
|
+
headers['Content-Type'] = 'application/json';
|
|
50
|
+
// The client's headers (an `Authorization` token, say) are for the API: a url on another origin (a file link the
|
|
51
|
+
// server returned, a third-party URL) gets none of them, so they don't leak there.
|
|
52
|
+
if (isSameOrigin(config.baseUrl, url)) {
|
|
53
|
+
setHeaders(headers, typeof config.headers === 'function' ? await config.headers() : config.headers);
|
|
54
|
+
}
|
|
55
|
+
setHeaders(headers, request.headers);
|
|
56
|
+
if (Object.keys(headers).length > 0)
|
|
57
|
+
init.headers = headers;
|
|
58
|
+
return init;
|
|
59
|
+
}
|
|
60
|
+
function setHeaders(into, headers) {
|
|
61
|
+
for (const [name, value] of Object.entries(headers ?? {})) {
|
|
62
|
+
for (const existing of Object.keys(into)) {
|
|
63
|
+
if (existing.toLowerCase() === name.toLowerCase())
|
|
64
|
+
delete into[existing];
|
|
65
|
+
}
|
|
66
|
+
into[name] = value;
|
|
67
|
+
}
|
|
68
|
+
}
|
|
@@ -0,0 +1,15 @@
|
|
|
1
|
+
import type { UnexpectedError } from './api-error.js';
|
|
2
|
+
import { type SendConfig, type SendRequest } from './send.js';
|
|
3
|
+
export interface TelemetryOptions {
|
|
4
|
+
/** Where traces are posted. Default: `/api/client-logs`, the server's default. */
|
|
5
|
+
readonly url?: string;
|
|
6
|
+
/**
|
|
7
|
+
* Called for every trace; its result goes into the trace as `context` (app version, route, …). Keep it small: the
|
|
8
|
+
* server rejects a trace over ~16 KB, the snippet and the URL take up to 2,000 characters each, and the kit doesn't
|
|
9
|
+
* cut `context`.
|
|
10
|
+
*/
|
|
11
|
+
readonly context?: () => unknown;
|
|
12
|
+
}
|
|
13
|
+
type Reporter = (request: SendRequest, error: UnexpectedError, durationMs: number) => void;
|
|
14
|
+
export declare function createReporter(config: SendConfig, options?: TelemetryOptions): Reporter;
|
|
15
|
+
export {};
|
|
@@ -0,0 +1,67 @@
|
|
|
1
|
+
import { send } from './send.js';
|
|
2
|
+
import { isAbsoluteUrl, joinUrl, originOf } from './url.js';
|
|
3
|
+
const defaultTelemetryUrl = '/api/client-logs';
|
|
4
|
+
// For the snippet and the URL. Characters, not bytes: text that JSON escapes heavily (a binary body read as text) can
|
|
5
|
+
// still take a trace past the server's ~16 KB cap, and that trace fails like any other.
|
|
6
|
+
const maxTextLength = 2000;
|
|
7
|
+
// Capped per client: during an outage (a proxy answering every call with a 502 page) each failed call would otherwise
|
|
8
|
+
// add a telemetry request, most likely failing too. Fixed, not an option.
|
|
9
|
+
const maxTracesPerWindow = 10;
|
|
10
|
+
const traceWindowMs = 60_000;
|
|
11
|
+
export function createReporter(config, options = {}) {
|
|
12
|
+
const url = telemetryUrl(config.baseUrl, options.url ?? defaultTelemetryUrl);
|
|
13
|
+
const sentAt = [];
|
|
14
|
+
const takeSlot = () => {
|
|
15
|
+
const now = Date.now();
|
|
16
|
+
while (sentAt.length > 0 && sentAt[0] <= now - traceWindowMs)
|
|
17
|
+
sentAt.shift();
|
|
18
|
+
if (sentAt.length >= maxTracesPerWindow)
|
|
19
|
+
return false;
|
|
20
|
+
sentAt.push(now);
|
|
21
|
+
return true;
|
|
22
|
+
};
|
|
23
|
+
return (request, error, durationMs) => {
|
|
24
|
+
if (!takeSlot())
|
|
25
|
+
return;
|
|
26
|
+
let body;
|
|
27
|
+
try {
|
|
28
|
+
const trace = {
|
|
29
|
+
kind: error.kind,
|
|
30
|
+
method: request.method,
|
|
31
|
+
url: truncate(withoutQuery(joinUrl(config.baseUrl, request.url))),
|
|
32
|
+
status: error.status,
|
|
33
|
+
traceId: error.traceId,
|
|
34
|
+
responseBodySnippet: truncate(error.responseText),
|
|
35
|
+
durationMs,
|
|
36
|
+
timestamp: new Date().toISOString(),
|
|
37
|
+
context: options.context?.(),
|
|
38
|
+
};
|
|
39
|
+
// Inside the try, so a `context()` result with a BigInt or a cycle drops the trace like a throwing `context()`:
|
|
40
|
+
// telemetry never breaks the app.
|
|
41
|
+
body = JSON.stringify(trace);
|
|
42
|
+
}
|
|
43
|
+
catch {
|
|
44
|
+
return;
|
|
45
|
+
}
|
|
46
|
+
// Straight to `send`, never through an `ApiRequest`: a failing telemetry request runs no handler or policy and is
|
|
47
|
+
// never reported itself (no loop). `send` resolves with the failure rather than rejecting, so it is simply
|
|
48
|
+
// dropped. The client's config is kept, so its `headers`, `credentials` and `fetch` apply to traces too (auth for
|
|
49
|
+
// the endpoint), the headers only on the origin of `baseUrl` like any request's; `unprefixed`, as the url already
|
|
50
|
+
// has its prefix. `keepalive`, so a full-page navigation in `onUnexpected` or `onUnauthorized`, right after this,
|
|
51
|
+
// doesn't cancel the trace (a trace stays well under keepalive's 64 KB).
|
|
52
|
+
void send(config, { method: 'POST', url, body, keepalive: true, unprefixed: true });
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
function withoutQuery(url) {
|
|
56
|
+
const end = url.search(/[?#]/);
|
|
57
|
+
return end < 0 ? url : url.slice(0, end);
|
|
58
|
+
}
|
|
59
|
+
// The `replace` drops the first half of a surrogate pair the cut split.
|
|
60
|
+
function truncate(text) {
|
|
61
|
+
return text.length <= maxTextLength ? text : text.slice(0, maxTextLength).replace(/[\ud800-\udbff]$/, '');
|
|
62
|
+
}
|
|
63
|
+
// Only the origin of `baseUrl` is prefixed, not its path, so the default `/api/client-logs` reaches the API's server
|
|
64
|
+
// even when the API is on another origin than the app.
|
|
65
|
+
function telemetryUrl(baseUrl, url) {
|
|
66
|
+
return isAbsoluteUrl(url) ? url : joinUrl(originOf(baseUrl), url);
|
|
67
|
+
}
|
package/dist/url.d.ts
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
export declare function isAbsoluteUrl(url: string): boolean;
|
|
2
|
+
export declare function originOf(url: string): string;
|
|
3
|
+
/**
|
|
4
|
+
* Whether `url` is fetched from the same origin as `baseUrl`: both relative to the page (a path, `?…`, `#…`), or both
|
|
5
|
+
* absolute with the same scheme and authority as written (case-insensitive; `https://host` and `https://host:443`, or
|
|
6
|
+
* `//host` and `https://host`, differ). Anything else, a url fetch would read another way than it reads here included,
|
|
7
|
+
* is another origin.
|
|
8
|
+
*/
|
|
9
|
+
export declare function isSameOrigin(baseUrl: string, url: string): boolean;
|
|
10
|
+
export declare function joinUrl(baseUrl: string, url: string): string;
|