@zerosumstudio/conduit 0.0.0-stage → 1.0.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 +785 -2
- package/dist/core-DXSbz15-.d.ts +142 -0
- package/dist/dev-CNYwEGcY.js +14 -0
- package/dist/devtools.d.ts +61 -0
- package/dist/devtools.js +152 -0
- package/dist/errors-DT0d6Qhy.js +85 -0
- package/dist/index.d.ts +177 -0
- package/dist/index.js +2412 -0
- package/dist/observable-LsEew2iL.d.ts +30 -0
- package/dist/query-state-BlmK3fBM.js +37 -0
- package/dist/react.d.ts +75 -0
- package/dist/react.js +331 -0
- package/dist/shared-2HssxK9p.d.ts +53 -0
- package/dist/shared-BsSjKC7q.js +118 -0
- package/dist/stores-DGXWZXXg.js +195 -0
- package/dist/testing.d.ts +88 -0
- package/dist/testing.js +224 -0
- package/dist/types-B9nuOKel.d.ts +689 -0
- package/dist/upload.d.ts +27 -0
- package/dist/upload.js +94 -0
- package/docs/migration-1.0.md +423 -0
- package/docs/threat-model.md +69 -0
- package/package.json +151 -3
|
@@ -0,0 +1,689 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Closed set of failure modes, discriminating `ConduitError`.
|
|
3
|
+
*
|
|
4
|
+
* - `HTTP_STATUS`: the server answered with a failing status.
|
|
5
|
+
* - `NETWORK`: the request never reached a server (DNS, offline, CORS, TLS).
|
|
6
|
+
* - `TIMEOUT`: the request exceeded its own deadline.
|
|
7
|
+
* - `ABORTED`: a caller, a scope, or a superseding request cancelled it.
|
|
8
|
+
* - `PARSE_FAILED`: a body arrived but could not be decoded as declared.
|
|
9
|
+
* - `VALIDATION_FAILED`: an endpoint's `response` schema or function rejected the decoded body.
|
|
10
|
+
* - `UNAUTHENTICATED`: the session is gone and could not be recovered.
|
|
11
|
+
* - `REDIRECT_BLOCKED`: a request carrying a credential was answered with a redirect.
|
|
12
|
+
* - `ORIGIN_REJECTED`: a url resolved outside the origins this client may call.
|
|
13
|
+
* - `INVALID_ARGUMENT`: conduit was used wrong. Always a developer error.
|
|
14
|
+
* - `DESTROYED`: the client was destroyed.
|
|
15
|
+
* - `DUPLICATE_PLUGIN`: a plugin was installed twice.
|
|
16
|
+
* - `EXTENSION_COLLISION`: a plugin tried to add a name the client already has.
|
|
17
|
+
* - `UNKNOWN`: something threw that conduit cannot classify.
|
|
18
|
+
*/
|
|
19
|
+
type ConduitErrorCode = "HTTP_STATUS" | "NETWORK" | "TIMEOUT" | "ABORTED" | "PARSE_FAILED" | "VALIDATION_FAILED" | "UNAUTHENTICATED" | "REDIRECT_BLOCKED" | "ORIGIN_REJECTED" | "INVALID_ARGUMENT" | "DESTROYED" | "DUPLICATE_PLUGIN" | "EXTENSION_COLLISION" | "UNKNOWN";
|
|
20
|
+
interface ConduitErrorInit {
|
|
21
|
+
code: ConduitErrorCode;
|
|
22
|
+
message: string;
|
|
23
|
+
method?: string | undefined;
|
|
24
|
+
/** Already query-redacted. Build it with `formatErrorUrl`. */
|
|
25
|
+
url?: string | undefined;
|
|
26
|
+
status?: number | undefined;
|
|
27
|
+
/** Which app or remote issued the request. Absent when conduit cannot attribute it. */
|
|
28
|
+
owner?: string | undefined;
|
|
29
|
+
/** Set by the `requestId` plugin, so a failure can be matched to a server log line. */
|
|
30
|
+
requestId?: string | undefined;
|
|
31
|
+
/** Response headers, when there was a response. Carries `Retry-After` and rate-limit hints. */
|
|
32
|
+
headers?: Headers | undefined;
|
|
33
|
+
/** Decoded response body, when the failure came from a response conduit could read. */
|
|
34
|
+
body?: unknown;
|
|
35
|
+
/** Milliseconds the server asked to wait, when the response carried `Retry-After`. */
|
|
36
|
+
retryAfterMs?: number | undefined;
|
|
37
|
+
cause?: unknown;
|
|
38
|
+
}
|
|
39
|
+
/** Log-safe projection. Omits `body`, which routinely carries user data. */
|
|
40
|
+
interface ConduitErrorJson {
|
|
41
|
+
name: string;
|
|
42
|
+
code: ConduitErrorCode;
|
|
43
|
+
message: string;
|
|
44
|
+
method: string | undefined;
|
|
45
|
+
url: string | undefined;
|
|
46
|
+
status: number | undefined;
|
|
47
|
+
owner: string | undefined;
|
|
48
|
+
requestId: string | undefined;
|
|
49
|
+
}
|
|
50
|
+
declare class ConduitError extends Error {
|
|
51
|
+
override readonly name: string;
|
|
52
|
+
/** Cross-realm brand. Two bundles carrying their own copy break `instanceof`. */
|
|
53
|
+
readonly conduitError: true;
|
|
54
|
+
readonly code: ConduitErrorCode;
|
|
55
|
+
readonly method: string | undefined;
|
|
56
|
+
/** The request url with secret query values replaced, never the raw one. */
|
|
57
|
+
readonly url: string | undefined;
|
|
58
|
+
readonly status: number | undefined;
|
|
59
|
+
/** The app or remote that issued the request, which the shared stack trace cannot say. */
|
|
60
|
+
readonly owner: string | undefined;
|
|
61
|
+
/** Milliseconds the server asked to wait, from `Retry-After`. The retry plugin fills it in. */
|
|
62
|
+
retryAfterMs: number | undefined;
|
|
63
|
+
/** The id the `requestId` plugin sent with the failing attempt. */
|
|
64
|
+
requestId: string | undefined;
|
|
65
|
+
/**
|
|
66
|
+
* Kept off {@link ConduitError.toJSON}, with `body`. Both can carry user
|
|
67
|
+
* data, so both are also non-enumerable: still readable directly, but
|
|
68
|
+
* absent from `{...error}`, `console.table`, and anything else that walks
|
|
69
|
+
* enumerable properties instead of naming them.
|
|
70
|
+
*/
|
|
71
|
+
readonly headers: Headers | undefined;
|
|
72
|
+
readonly body: unknown;
|
|
73
|
+
constructor(init: ConduitErrorInit);
|
|
74
|
+
toJSON(): ConduitErrorJson;
|
|
75
|
+
}
|
|
76
|
+
/** Brand check rather than `instanceof`, so it holds across federation boundaries. */
|
|
77
|
+
declare function isConduitError(value: unknown): value is ConduitError;
|
|
78
|
+
/** Narrows to a specific failure mode. `isConduitError(e) && e.code === 'TIMEOUT'` in one call. */
|
|
79
|
+
declare function isErrorCode<C extends ConduitErrorCode>(value: unknown, code: C): value is ConduitError & {
|
|
80
|
+
code: C;
|
|
81
|
+
};
|
|
82
|
+
/**
|
|
83
|
+
* Coerces anything thrown into a `ConduitError`. A conduit error passes through
|
|
84
|
+
* untouched unless a `code` or `message` asks for a different one, and then it is
|
|
85
|
+
* copied, with the original as its `cause`.
|
|
86
|
+
*/
|
|
87
|
+
declare function toConduitError(value: unknown, code?: ConduitErrorCode, message?: string): ConduitError;
|
|
88
|
+
interface ApiVersionMismatch {
|
|
89
|
+
/** What this bundle was built against. */
|
|
90
|
+
readonly expected: string;
|
|
91
|
+
/** What the server reported. */
|
|
92
|
+
readonly actual: string;
|
|
93
|
+
/** The request url, without its query. */
|
|
94
|
+
readonly url: string;
|
|
95
|
+
}
|
|
96
|
+
interface ApiVersionConfig {
|
|
97
|
+
/** The API version this bundle was compiled against. */
|
|
98
|
+
expected: string | number;
|
|
99
|
+
/** Response header carrying the server's version. Defaults to `x-api-version`. */
|
|
100
|
+
header?: string | undefined;
|
|
101
|
+
/** Routes the report somewhere other than the console. */
|
|
102
|
+
onMismatch?: ((report: ApiVersionMismatch) => void) | undefined;
|
|
103
|
+
}
|
|
104
|
+
/**
|
|
105
|
+
* Notices when a bundle is talking to an API it was not built against, and says
|
|
106
|
+
* so once per server version rather than once per request. Error responses
|
|
107
|
+
* count too, since a deployment that moved on often fails first.
|
|
108
|
+
*/
|
|
109
|
+
declare function apiVersion(config: ApiVersionConfig): Plugin;
|
|
110
|
+
/**
|
|
111
|
+
* The framework seam. Every piece of changing state conduit exposes is one of
|
|
112
|
+
* these, and `useSyncExternalStore` consumes the shape directly.
|
|
113
|
+
*/
|
|
114
|
+
interface ReadableStore<T> {
|
|
115
|
+
getState: () => T;
|
|
116
|
+
subscribe: (listener: (value: T) => void) => Unsubscribe;
|
|
117
|
+
}
|
|
118
|
+
interface AdapterContext {
|
|
119
|
+
/** Issues a request that bypasses this plugin, so loading a session cannot recurse into itself. */
|
|
120
|
+
request<T = unknown>(path: string, options?: RequestOptions): ConduitPromise<T>;
|
|
121
|
+
/** Aborts when the plugin is torn down. */
|
|
122
|
+
signal: AbortSignal;
|
|
123
|
+
}
|
|
124
|
+
/**
|
|
125
|
+
* Everything backend-specific about a session. A cookie backend implements
|
|
126
|
+
* `load` and `identify`. A token backend adds `authorize` and `renew`.
|
|
127
|
+
*/
|
|
128
|
+
interface SessionAdapter<S = unknown> {
|
|
129
|
+
/** Reads the current session. `null` means signed out, which is not an error. */
|
|
130
|
+
load(ctx: AdapterContext): Promise<S | null>;
|
|
131
|
+
/**
|
|
132
|
+
* A stable id for whoever is signed in. Compared on every successful read;
|
|
133
|
+
* a change resets everything identity-scoped, so one user never sees the
|
|
134
|
+
* cache of the one before.
|
|
135
|
+
*/
|
|
136
|
+
identify(session: S): string;
|
|
137
|
+
/**
|
|
138
|
+
* Attaches credentials to an outgoing request, and is only called with a live
|
|
139
|
+
* session. Every header it adds or changes counts as a credential: it reads
|
|
140
|
+
* `[redacted]` in events, and a request carrying it is not sent through a redirect.
|
|
141
|
+
*/
|
|
142
|
+
authorize?(request: ConduitRequest, session: S): ConduitRequest;
|
|
143
|
+
/** Whether a failure means the session is at fault. Defaults to HTTP 401. */
|
|
144
|
+
isUnauthenticated?(error: ConduitError, request: ConduitRequest): boolean;
|
|
145
|
+
/** Epoch milliseconds, driving a re-read before the session lapses. */
|
|
146
|
+
expiresAt?(session: S): number | undefined;
|
|
147
|
+
/** Attempts recovery. `false` gives up. Absent means a rejected session is lost. */
|
|
148
|
+
renew?(ctx: AdapterContext): Promise<boolean>;
|
|
149
|
+
/** Called after `clear()` and after a session is lost, once local state is already gone. */
|
|
150
|
+
onClear?(): void;
|
|
151
|
+
}
|
|
152
|
+
type SessionStatus = "unknown" | "loading" | "authenticated" | "anonymous" | "error";
|
|
153
|
+
/**
|
|
154
|
+
* - `unknown`: never read, or `clear()` ran.
|
|
155
|
+
* - `loading`: a read is in flight. It keeps the previous session and error.
|
|
156
|
+
* - `authenticated`: a read found a session.
|
|
157
|
+
* - `anonymous`: a read found nobody, or the session was lost, in which case `error` is `UNAUTHENTICATED`.
|
|
158
|
+
* - `error`: a read failed. A previous session is kept, so requests keep using it.
|
|
159
|
+
*/
|
|
160
|
+
type SessionState<S> = {
|
|
161
|
+
readonly status: "unknown";
|
|
162
|
+
readonly session: null;
|
|
163
|
+
readonly error: null;
|
|
164
|
+
readonly updatedAt: number;
|
|
165
|
+
} | {
|
|
166
|
+
readonly status: "loading";
|
|
167
|
+
readonly session: S | null;
|
|
168
|
+
readonly error: ConduitError | null;
|
|
169
|
+
readonly updatedAt: number;
|
|
170
|
+
} | {
|
|
171
|
+
readonly status: "authenticated";
|
|
172
|
+
readonly session: S;
|
|
173
|
+
readonly error: null;
|
|
174
|
+
readonly updatedAt: number;
|
|
175
|
+
} | {
|
|
176
|
+
readonly status: "anonymous";
|
|
177
|
+
readonly session: null;
|
|
178
|
+
readonly error: ConduitError | null;
|
|
179
|
+
readonly updatedAt: number;
|
|
180
|
+
} | {
|
|
181
|
+
readonly status: "error";
|
|
182
|
+
readonly session: S | null;
|
|
183
|
+
readonly error: ConduitError;
|
|
184
|
+
readonly updatedAt: number;
|
|
185
|
+
};
|
|
186
|
+
interface SessionHandle<S> extends ReadableStore<SessionState<S>> {
|
|
187
|
+
/**
|
|
188
|
+
* Returns the session once it is known. A read already in flight is joined,
|
|
189
|
+
* and a known session, signed in or not, resolves without a request.
|
|
190
|
+
*/
|
|
191
|
+
load: () => Promise<S | null>;
|
|
192
|
+
/** Always starts a new read. The latest read wins and older results are dropped. */
|
|
193
|
+
reload: () => Promise<S | null>;
|
|
194
|
+
/** Drops local state without telling the server. */
|
|
195
|
+
clear: () => void;
|
|
196
|
+
}
|
|
197
|
+
interface SessionApi<S = unknown> {
|
|
198
|
+
session: SessionHandle<S>;
|
|
199
|
+
}
|
|
200
|
+
interface SessionConfig<S = unknown> {
|
|
201
|
+
adapter: SessionAdapter<S>;
|
|
202
|
+
/** Called once per lost session, after in-flight credentialed requests were cancelled and cached data dropped. */
|
|
203
|
+
onUnauthenticated?: ((error: ConduitError) => void) | undefined;
|
|
204
|
+
/** Read the session as soon as the plugin installs. Defaults to false. */
|
|
205
|
+
autoLoad?: boolean | undefined;
|
|
206
|
+
/** Re-read this long before `expiresAt`. Defaults to 60 seconds. */
|
|
207
|
+
refreshLeewayMs?: number | undefined;
|
|
208
|
+
/**
|
|
209
|
+
* Extra origins, beyond the client's own, that also receive credentials, as
|
|
210
|
+
* `https://host`. They have to be in the client's `origins` too, or every
|
|
211
|
+
* request to them is rejected anyway.
|
|
212
|
+
*/
|
|
213
|
+
origins?: readonly string[] | undefined;
|
|
214
|
+
/**
|
|
215
|
+
* Names a `BroadcastChannel` that tells other tabs, and other bundles on the
|
|
216
|
+
* page, to re-read when this one signs out, loses the session or sees another
|
|
217
|
+
* user. Without it each tab learns on its next rejected request.
|
|
218
|
+
*/
|
|
219
|
+
channel?: string | undefined;
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* One session for every bundle on the page. Reads and recovery are
|
|
223
|
+
* single-flight, and losing the session runs once however many requests failed
|
|
224
|
+
* at the same moment.
|
|
225
|
+
*
|
|
226
|
+
* Nothing about the session is sticky. A lost session is `anonymous`, and every
|
|
227
|
+
* later request goes out without credentials until a read finds one again.
|
|
228
|
+
*/
|
|
229
|
+
declare function session<S = unknown>(config: SessionConfig<S>): Plugin<SessionApi<S>>;
|
|
230
|
+
/** What `ClientConfig.logger` must implement. Defaults to `console`. */
|
|
231
|
+
interface ConduitLogger {
|
|
232
|
+
warn(message: string): void;
|
|
233
|
+
error(message: string): void;
|
|
234
|
+
}
|
|
235
|
+
interface RequestStartEvent {
|
|
236
|
+
readonly type: "request:start";
|
|
237
|
+
/** The request as issued. Middleware may rewrite it further in; see `response.request`. */
|
|
238
|
+
readonly request: ConduitRequest;
|
|
239
|
+
readonly at: number;
|
|
240
|
+
}
|
|
241
|
+
interface RequestSettleEvent {
|
|
242
|
+
readonly type: "request:settle";
|
|
243
|
+
readonly request: ConduitRequest;
|
|
244
|
+
readonly response: ConduitResponse;
|
|
245
|
+
/** Milliseconds across the whole pipeline, not just the network. */
|
|
246
|
+
readonly durationMs: number;
|
|
247
|
+
readonly at: number;
|
|
248
|
+
}
|
|
249
|
+
interface RequestErrorEvent {
|
|
250
|
+
readonly type: "request:error";
|
|
251
|
+
readonly request: ConduitRequest;
|
|
252
|
+
readonly error: ConduitError;
|
|
253
|
+
readonly durationMs: number;
|
|
254
|
+
readonly at: number;
|
|
255
|
+
}
|
|
256
|
+
interface ClientDestroyEvent {
|
|
257
|
+
readonly type: "client:destroy";
|
|
258
|
+
readonly at: number;
|
|
259
|
+
}
|
|
260
|
+
interface CacheHitEvent {
|
|
261
|
+
readonly type: "cache:hit";
|
|
262
|
+
readonly key: string;
|
|
263
|
+
readonly owner: string | undefined;
|
|
264
|
+
readonly at: number;
|
|
265
|
+
}
|
|
266
|
+
interface CacheMissEvent {
|
|
267
|
+
readonly type: "cache:miss";
|
|
268
|
+
readonly key: string;
|
|
269
|
+
readonly owner: string | undefined;
|
|
270
|
+
readonly at: number;
|
|
271
|
+
}
|
|
272
|
+
interface CacheStaleEvent {
|
|
273
|
+
readonly type: "cache:stale";
|
|
274
|
+
readonly key: string;
|
|
275
|
+
readonly owner: string | undefined;
|
|
276
|
+
/** Whether a background refresh was started, or one was already running. */
|
|
277
|
+
readonly isRevalidating: boolean;
|
|
278
|
+
readonly at: number;
|
|
279
|
+
}
|
|
280
|
+
interface CacheInvalidateEvent {
|
|
281
|
+
readonly type: "cache:invalidate";
|
|
282
|
+
/** A key, a `tag:name`, or `*` for a full clear. */
|
|
283
|
+
readonly target: string;
|
|
284
|
+
readonly removed: number;
|
|
285
|
+
readonly at: number;
|
|
286
|
+
}
|
|
287
|
+
interface CacheSetEvent {
|
|
288
|
+
readonly type: "cache:set";
|
|
289
|
+
readonly key: string;
|
|
290
|
+
readonly data: unknown;
|
|
291
|
+
readonly at: number;
|
|
292
|
+
}
|
|
293
|
+
interface DedupeJoinEvent {
|
|
294
|
+
readonly type: "dedupe:join";
|
|
295
|
+
readonly key: string;
|
|
296
|
+
/** The remote that joined an existing flight rather than starting one. */
|
|
297
|
+
readonly owner: string | undefined;
|
|
298
|
+
readonly at: number;
|
|
299
|
+
}
|
|
300
|
+
interface QueueEnqueueEvent {
|
|
301
|
+
readonly type: "queue:enqueue";
|
|
302
|
+
readonly key: string;
|
|
303
|
+
readonly owner: string | undefined;
|
|
304
|
+
readonly lane: Lane;
|
|
305
|
+
/** How many were already waiting when this one joined. */
|
|
306
|
+
readonly depth: number;
|
|
307
|
+
readonly at: number;
|
|
308
|
+
}
|
|
309
|
+
interface SessionChangeEvent {
|
|
310
|
+
readonly type: "session:change";
|
|
311
|
+
readonly status: SessionStatus;
|
|
312
|
+
/** True when the session was lost: signed out by a failed renewal, not by a read that found nobody. */
|
|
313
|
+
readonly isLost: boolean;
|
|
314
|
+
readonly at: number;
|
|
315
|
+
}
|
|
316
|
+
interface ApiVersionMismatchEvent extends ApiVersionMismatch {
|
|
317
|
+
readonly type: "api-version:mismatch";
|
|
318
|
+
readonly at: number;
|
|
319
|
+
}
|
|
320
|
+
interface RetryAttemptEvent {
|
|
321
|
+
readonly type: "retry:attempt";
|
|
322
|
+
readonly key: string;
|
|
323
|
+
readonly owner: string | undefined;
|
|
324
|
+
/** The attempt that just failed. */
|
|
325
|
+
readonly attempt: number;
|
|
326
|
+
readonly delayMs: number;
|
|
327
|
+
readonly code: ConduitErrorCode;
|
|
328
|
+
readonly at: number;
|
|
329
|
+
}
|
|
330
|
+
/**
|
|
331
|
+
* The event surface. Plugins extend it by declaration merging:
|
|
332
|
+
*
|
|
333
|
+
* ```ts
|
|
334
|
+
* declare module '@zerosumstudio/conduit' {
|
|
335
|
+
* interface ConduitEventMap {
|
|
336
|
+
* 'cache:hit': { type: 'cache:hit'; key: string; at: number }
|
|
337
|
+
* }
|
|
338
|
+
* }
|
|
339
|
+
* ```
|
|
340
|
+
*/
|
|
341
|
+
interface ConduitEventMap {
|
|
342
|
+
"request:start": RequestStartEvent;
|
|
343
|
+
"request:settle": RequestSettleEvent;
|
|
344
|
+
"request:error": RequestErrorEvent;
|
|
345
|
+
"client:destroy": ClientDestroyEvent;
|
|
346
|
+
"cache:hit": CacheHitEvent;
|
|
347
|
+
"cache:miss": CacheMissEvent;
|
|
348
|
+
"cache:stale": CacheStaleEvent;
|
|
349
|
+
"cache:invalidate": CacheInvalidateEvent;
|
|
350
|
+
"cache:set": CacheSetEvent;
|
|
351
|
+
"dedupe:join": DedupeJoinEvent;
|
|
352
|
+
"retry:attempt": RetryAttemptEvent;
|
|
353
|
+
"queue:enqueue": QueueEnqueueEvent;
|
|
354
|
+
"session:change": SessionChangeEvent;
|
|
355
|
+
"api-version:mismatch": ApiVersionMismatchEvent;
|
|
356
|
+
}
|
|
357
|
+
type ConduitEventType = keyof ConduitEventMap;
|
|
358
|
+
type ConduitEvent = ConduitEventMap[ConduitEventType];
|
|
359
|
+
type Unsubscribe = () => void;
|
|
360
|
+
/** What a remote sees of the bus: it can listen, and nothing else. Plugins get the whole `EventBus`. */
|
|
361
|
+
type ClientEvents = Pick<EventBus, "active" | "on" | "onAny">;
|
|
362
|
+
interface EventBus {
|
|
363
|
+
/** Whether anything is listening. Guard emission with it, rather than building events for nobody. */
|
|
364
|
+
readonly active: boolean;
|
|
365
|
+
on<K extends ConduitEventType>(type: K, listener: (event: ConduitEventMap[K]) => void): Unsubscribe;
|
|
366
|
+
/** Every event, whatever its type. What devtools and telemetry bridges want. */
|
|
367
|
+
onAny(listener: (event: ConduitEvent) => void): Unsubscribe;
|
|
368
|
+
emit<K extends ConduitEventType>(type: K, event: ConduitEventMap[K]): void;
|
|
369
|
+
clear(): void;
|
|
370
|
+
}
|
|
371
|
+
interface RedactRules {
|
|
372
|
+
/** Header names, matched case-insensitively. */
|
|
373
|
+
readonly headers: readonly string[];
|
|
374
|
+
/** Query parameter names, matched case-insensitively. A trailing `*` matches a prefix. */
|
|
375
|
+
readonly query: readonly string[];
|
|
376
|
+
}
|
|
377
|
+
/** What `ClientConfig.redact` falls back to. Spread it to widen the lists rather than replace them. */
|
|
378
|
+
declare const DEFAULT_REDACT: RedactRules;
|
|
379
|
+
type NoExtension = Record<never, never>;
|
|
380
|
+
/** A union that still autocompletes, where `T | string` would collapse to `string`. */
|
|
381
|
+
type LiteralUnion<T extends string> = T | (string & Record<never, never>);
|
|
382
|
+
type HttpMethod = "GET" | "HEAD" | "POST" | "PUT" | "PATCH" | "DELETE" | "OPTIONS";
|
|
383
|
+
/** Scheduling priority for the queue plugin. The three shipped are a suggestion, not a limit. */
|
|
384
|
+
type Lane = LiteralUnion<"critical" | "default" | "prefetch">;
|
|
385
|
+
/**
|
|
386
|
+
* Which headers take part in a request's identity. `'*'` is every header, `[]`
|
|
387
|
+
* is none. Headers a session attaches never take part, since an identity change
|
|
388
|
+
* already clears everything held for the previous one.
|
|
389
|
+
*
|
|
390
|
+
* A header that is unique per request, such as a trace id, gives every request
|
|
391
|
+
* its own key under `'*'`, so nothing hits the cache or shares a flight.
|
|
392
|
+
*/
|
|
393
|
+
type Vary = "*" | readonly string[];
|
|
394
|
+
type QueryValue = string | number | boolean | null | undefined | ReadonlyArray<string | number | boolean>;
|
|
395
|
+
type Query = Readonly<Record<string, QueryValue>>;
|
|
396
|
+
type PathParams = Readonly<Record<string, string | number>>;
|
|
397
|
+
/** How to decode a response body. `auto` reads the content type. */
|
|
398
|
+
type ParseMode = "auto" | "json" | "text" | "blob" | "arrayBuffer" | "formData" | "none";
|
|
399
|
+
type Letter = "a" | "b" | "c" | "d" | "e" | "f" | "g" | "h" | "i" | "j" | "k" | "l" | "m" | "n" | "o" | "p" | "q" | "r" | "s" | "t" | "u" | "v" | "w" | "x" | "y" | "z" | "A" | "B" | "C" | "D" | "E" | "F" | "G" | "H" | "I" | "J" | "K" | "L" | "M" | "N" | "O" | "P" | "Q" | "R" | "S" | "T" | "U" | "V" | "W" | "X" | "Y" | "Z" | "_";
|
|
400
|
+
type Digit = "0" | "1" | "2" | "3" | "4" | "5" | "6" | "7" | "8" | "9";
|
|
401
|
+
type TakeName<S extends string, Name extends string = ""> = S extends `${infer C}${infer Rest}` ? C extends Letter | Digit ? TakeName<Rest, `${Name}${C}`> : Name : Name;
|
|
402
|
+
/** A name starts with a letter or an underscore, as the runtime pattern requires. */
|
|
403
|
+
type ValidName<Name extends string> = Name extends "" ? never : Name extends `${Digit}${string}` ? never : Name;
|
|
404
|
+
type SegmentParam<Segment extends string> = Segment extends `::${string}` ? never : Segment extends `:${infer Rest}` ? ValidName<TakeName<Rest>> : never;
|
|
405
|
+
/**
|
|
406
|
+
* The `:name` placeholders in a path literal. `::name` is a literal colon, and
|
|
407
|
+
* a colon in the middle of a segment is not a placeholder.
|
|
408
|
+
*/
|
|
409
|
+
type PathParamNames<P extends string> = P extends `${infer Head}?${string}` ? PathParamNames<Head> : P extends `${infer Segment}/${infer Rest}` ? SegmentParam<Segment> | PathParamNames<Rest> : SegmentParam<P>;
|
|
410
|
+
/** `params` for a path literal: `PathParamsOf<'/users/:id'>` is `{ id: string | number }`. */
|
|
411
|
+
type PathParamsOf<P extends string> = string extends P ? PathParams : { readonly [K in PathParamNames<P>]: string | number; };
|
|
412
|
+
/**
|
|
413
|
+
* The trailing arguments of a verb. A literal path with placeholders makes the
|
|
414
|
+
* options, and `params` inside them, required. Anything else keeps them optional.
|
|
415
|
+
*
|
|
416
|
+
* TypeScript cannot infer the path when the result type is given explicitly, as
|
|
417
|
+
* in `get<User>('/users/:id')`, so `params` stays loose there.
|
|
418
|
+
*/
|
|
419
|
+
type OptionsArgs<P extends string, O extends {
|
|
420
|
+
params?: PathParams | undefined;
|
|
421
|
+
}> = string extends P ? [options?: O] : [PathParamNames<P>] extends [never] ? [options?: Omit<O, "params"> & {
|
|
422
|
+
params?: undefined;
|
|
423
|
+
}] : [options: Omit<O, "params"> & {
|
|
424
|
+
params: PathParamsOf<P>;
|
|
425
|
+
}];
|
|
426
|
+
/**
|
|
427
|
+
* Plugin scratch space, carried through the pipeline untouched by the core.
|
|
428
|
+
* Declaration-merge to give your own keys a real type instead of `unknown`:
|
|
429
|
+
*
|
|
430
|
+
* ```ts
|
|
431
|
+
* declare module '@zerosumstudio/conduit' {
|
|
432
|
+
* interface ConduitMeta {
|
|
433
|
+
* 'my-plugin.skip'?: boolean
|
|
434
|
+
* }
|
|
435
|
+
* }
|
|
436
|
+
* ```
|
|
437
|
+
*/
|
|
438
|
+
interface ConduitMeta {
|
|
439
|
+
/** `bypass` skips the cache. `refresh` skips a stored entry and replaces it. */
|
|
440
|
+
cache?: "bypass" | "refresh" | undefined;
|
|
441
|
+
/** `bypass` skips flight sharing. */
|
|
442
|
+
dedupe?: "bypass" | undefined;
|
|
443
|
+
/** `bypass` skips the queue. */
|
|
444
|
+
queue?: "bypass" | undefined;
|
|
445
|
+
/** `bypass` skips authorize, and 401 handling. Use it for sign-in calls. */
|
|
446
|
+
session?: "bypass" | undefined;
|
|
447
|
+
/** Overrides the timeout plugin's default for one request. `0` turns it off. */
|
|
448
|
+
timeoutMs?: number | undefined;
|
|
449
|
+
/** Which attempt this is. Written by the retry plugin. */
|
|
450
|
+
attempt?: number | undefined;
|
|
451
|
+
/** Set by the `requestId` plugin: the id this attempt went out with. */
|
|
452
|
+
requestId?: string | undefined;
|
|
453
|
+
/** Header names the session attached, which the transport treats as credentials. */
|
|
454
|
+
credentialHeaders?: readonly string[] | undefined;
|
|
455
|
+
/** Sends this one request through another fetch. `/upload` uses it for XHR progress. */
|
|
456
|
+
fetch?: FetchLike | undefined;
|
|
457
|
+
[key: string]: unknown;
|
|
458
|
+
}
|
|
459
|
+
/**
|
|
460
|
+
* `RequestInit` fields conduit passes straight through rather than deriving
|
|
461
|
+
* itself. Shared by `ClientConfig` and `RequestOptions`; a request sets a
|
|
462
|
+
* field, the client supplies a default. `duplex` is excluded: it is inferred
|
|
463
|
+
* from the body, not something a caller sets.
|
|
464
|
+
*/
|
|
465
|
+
interface RequestInitPassthrough {
|
|
466
|
+
mode?: RequestMode | undefined;
|
|
467
|
+
/**
|
|
468
|
+
* Conduit sends a request that carries a credential the platform will not
|
|
469
|
+
* strip itself (an `x-api-key`, a session header) with `manual`, and fails it
|
|
470
|
+
* with `REDIRECT_BLOCKED` when the answer is a redirect. Set this to opt out.
|
|
471
|
+
*/
|
|
472
|
+
redirect?: RequestRedirect | undefined;
|
|
473
|
+
cache?: RequestCache | undefined;
|
|
474
|
+
keepalive?: boolean | undefined;
|
|
475
|
+
priority?: RequestPriority | undefined;
|
|
476
|
+
referrerPolicy?: ReferrerPolicy | undefined;
|
|
477
|
+
integrity?: string | undefined;
|
|
478
|
+
}
|
|
479
|
+
interface RequestOptions extends RequestInitPassthrough {
|
|
480
|
+
method?: HttpMethod | undefined;
|
|
481
|
+
/** Fills `:name` placeholders. A missing one is an `INVALID_ARGUMENT`, not a 404. */
|
|
482
|
+
params?: PathParams | undefined;
|
|
483
|
+
query?: Query | undefined;
|
|
484
|
+
/** JSON-encoded with a matching content type unless it is already a `BodyInit`. */
|
|
485
|
+
body?: unknown;
|
|
486
|
+
headers?: HeadersInit | undefined;
|
|
487
|
+
signal?: AbortSignal | undefined;
|
|
488
|
+
/** Overrides the derived cache and dedupe key. */
|
|
489
|
+
key?: string | undefined;
|
|
490
|
+
lane?: Lane | undefined;
|
|
491
|
+
owner?: string | undefined;
|
|
492
|
+
/** Labels for `invalidateTag`. They never switch caching on, `cacheable` does. */
|
|
493
|
+
tags?: readonly string[] | undefined;
|
|
494
|
+
/** Whether this request reads, so cache and dedupe may serve it. Defaults to `GET` and `HEAD`. */
|
|
495
|
+
cacheable?: boolean | undefined;
|
|
496
|
+
parse?: ParseMode | undefined;
|
|
497
|
+
credentials?: RequestCredentials | undefined;
|
|
498
|
+
meta?: ConduitMeta | undefined;
|
|
499
|
+
}
|
|
500
|
+
/** `RequestOptions` minus the parts a method helper already decides for you. */
|
|
501
|
+
type MethodOptions = Omit<RequestOptions, "method" | "body">;
|
|
502
|
+
/** The resolved request every middleware sees. */
|
|
503
|
+
interface ConduitRequest {
|
|
504
|
+
/** Always absolute: it is what the transport sends. */
|
|
505
|
+
readonly url: string;
|
|
506
|
+
readonly method: HttpMethod;
|
|
507
|
+
readonly headers: Headers;
|
|
508
|
+
readonly body: BodyInit | null;
|
|
509
|
+
readonly signal: AbortSignal;
|
|
510
|
+
readonly key: string;
|
|
511
|
+
/** Pre-hashed identity beyond method, url and body, so a rewrite can recompute its key. */
|
|
512
|
+
readonly variance: string;
|
|
513
|
+
readonly lane: Lane;
|
|
514
|
+
readonly owner: string | undefined;
|
|
515
|
+
readonly tags: readonly string[];
|
|
516
|
+
/** Whether cache and dedupe may serve this request. */
|
|
517
|
+
readonly cacheable: boolean;
|
|
518
|
+
readonly parse: ParseMode;
|
|
519
|
+
readonly credentials: RequestCredentials | undefined;
|
|
520
|
+
readonly mode: RequestMode | undefined;
|
|
521
|
+
readonly redirect: RequestRedirect | undefined;
|
|
522
|
+
readonly cache: RequestCache | undefined;
|
|
523
|
+
readonly keepalive: boolean | undefined;
|
|
524
|
+
readonly priority: RequestPriority | undefined;
|
|
525
|
+
readonly referrerPolicy: ReferrerPolicy | undefined;
|
|
526
|
+
readonly integrity: string | undefined;
|
|
527
|
+
/** Mutable by design: plugins stash state here across the onion. */
|
|
528
|
+
readonly meta: ConduitMeta;
|
|
529
|
+
/** Hides this client's secret query values in a url, for messages and logs. */
|
|
530
|
+
readonly redactUrl: (url: string) => string;
|
|
531
|
+
}
|
|
532
|
+
/**
|
|
533
|
+
* Fields a middleware may rewrite before passing the request on.
|
|
534
|
+
*
|
|
535
|
+
* Patching `url`, `method`, `body`, `variance` or `parse` re-derives `key`
|
|
536
|
+
* unless the patch sets one. `meta` is replaced wholesale rather than merged.
|
|
537
|
+
*/
|
|
538
|
+
type RequestPatch = Partial<Pick<ConduitRequest, "url" | "method" | "body" | "signal" | "key" | "variance" | "lane" | "owner" | "tags" | "cacheable" | "parse" | "meta">> & {
|
|
539
|
+
headers?: Headers;
|
|
540
|
+
};
|
|
541
|
+
/**
|
|
542
|
+
* Where an answer came from. `stale` is a stored entry served past its ttl
|
|
543
|
+
* while a refresh runs behind it, and `cache` is a fresh one.
|
|
544
|
+
*/
|
|
545
|
+
type ResponseSource = "network" | "cache" | "stale" | "dedupe";
|
|
546
|
+
interface ConduitResponse<T = unknown> {
|
|
547
|
+
readonly status: number;
|
|
548
|
+
readonly headers: Headers;
|
|
549
|
+
readonly data: T;
|
|
550
|
+
/** Absent for anything served from cache or dedupe. */
|
|
551
|
+
readonly raw: Response | undefined;
|
|
552
|
+
readonly from: ResponseSource;
|
|
553
|
+
/** 1 for a first attempt. The retry plugin raises it on each replay. */
|
|
554
|
+
readonly attempt: number;
|
|
555
|
+
readonly request: ConduitRequest;
|
|
556
|
+
}
|
|
557
|
+
/** Discriminated on `error`, so `error === null` narrows `data` to non-null. */
|
|
558
|
+
type SafeResult<T> = {
|
|
559
|
+
readonly data: T;
|
|
560
|
+
readonly error: null;
|
|
561
|
+
} | {
|
|
562
|
+
readonly data: null;
|
|
563
|
+
readonly error: ConduitError;
|
|
564
|
+
};
|
|
565
|
+
type Next = (request: ConduitRequest) => Promise<ConduitResponse>;
|
|
566
|
+
/** An onion layer. Return without calling `next` to short-circuit. */
|
|
567
|
+
type Middleware = (request: ConduitRequest, next: Next) => Promise<ConduitResponse>;
|
|
568
|
+
interface Plugin<Ext extends object = NoExtension> {
|
|
569
|
+
readonly name: string;
|
|
570
|
+
readonly middleware?: Middleware | undefined;
|
|
571
|
+
/** Merged onto the client by `.with()`, and shows up in its type. */
|
|
572
|
+
onInit?(ctx: PluginContext): Ext | void;
|
|
573
|
+
onDestroy?(): void;
|
|
574
|
+
}
|
|
575
|
+
type FetchLike = (input: string, init: RequestInit) => Promise<Response>;
|
|
576
|
+
interface RedactConfig {
|
|
577
|
+
/** Header names hidden from `.response()`, events and devtools. Defaults to `DEFAULT_REDACT.headers`. */
|
|
578
|
+
headers?: readonly string[] | undefined;
|
|
579
|
+
/** Query parameters whose values are hidden in errors, events and `.response()`. Defaults to `DEFAULT_REDACT.query`. */
|
|
580
|
+
query?: readonly string[] | undefined;
|
|
581
|
+
}
|
|
582
|
+
interface ClientConfig extends RequestInitPassthrough {
|
|
583
|
+
/**
|
|
584
|
+
* Prefixed to every relative path. A relative `baseUrl` (`''`, `'/api'`) means
|
|
585
|
+
* the page's own origin and needs a page, so pass an absolute one on a server.
|
|
586
|
+
*/
|
|
587
|
+
baseUrl?: string | undefined;
|
|
588
|
+
/** Pass a function for anything that changes at runtime. It is read per request. */
|
|
589
|
+
headers?: HeadersInit | (() => HeadersInit) | undefined;
|
|
590
|
+
credentials?: RequestCredentials | undefined;
|
|
591
|
+
/** Which headers take part in request identity. Defaults to `'*'`, see {@link Vary}. */
|
|
592
|
+
vary?: Vary | undefined;
|
|
593
|
+
/** Names the app or remote issuing requests, in devtools and on errors. */
|
|
594
|
+
owner?: string | undefined;
|
|
595
|
+
lane?: Lane | undefined;
|
|
596
|
+
parse?: ParseMode | undefined;
|
|
597
|
+
/** Swap the network implementation, for tests, instrumentation or a non-browser host. */
|
|
598
|
+
fetch?: FetchLike | undefined;
|
|
599
|
+
/**
|
|
600
|
+
* Extra origins this client may call besides its own, as `https://host` with no
|
|
601
|
+
* path. `baseUrl`'s origin is always allowed. Every other url is rejected with
|
|
602
|
+
* `ORIGIN_REJECTED` before any plugin runs.
|
|
603
|
+
*/
|
|
604
|
+
origins?: readonly string[] | undefined;
|
|
605
|
+
/** What is hidden from errors, events and `.response()`. Spread `DEFAULT_REDACT` to widen it. */
|
|
606
|
+
redact?: RedactConfig | undefined;
|
|
607
|
+
/** Where conduit's own diagnostics go. Defaults to `console`. */
|
|
608
|
+
logger?: ConduitLogger | undefined;
|
|
609
|
+
}
|
|
610
|
+
interface ResolvedClientConfig {
|
|
611
|
+
readonly baseUrl: string;
|
|
612
|
+
readonly headers: (() => HeadersInit) | undefined;
|
|
613
|
+
readonly credentials: RequestCredentials | undefined;
|
|
614
|
+
readonly vary: Vary;
|
|
615
|
+
readonly owner: string | undefined;
|
|
616
|
+
readonly lane: Lane;
|
|
617
|
+
readonly parse: ParseMode;
|
|
618
|
+
readonly fetch: FetchLike;
|
|
619
|
+
readonly mode: RequestMode | undefined;
|
|
620
|
+
readonly redirect: RequestRedirect | undefined;
|
|
621
|
+
readonly cache: RequestCache | undefined;
|
|
622
|
+
readonly keepalive: boolean | undefined;
|
|
623
|
+
readonly priority: RequestPriority | undefined;
|
|
624
|
+
readonly referrerPolicy: ReferrerPolicy | undefined;
|
|
625
|
+
readonly integrity: string | undefined;
|
|
626
|
+
/** `origins`, normalised to bare origins. */
|
|
627
|
+
readonly origins: readonly string[];
|
|
628
|
+
/** What events and `.response()` hide. Setting `redact` replaces the defaults here. */
|
|
629
|
+
readonly redact: RedactRules;
|
|
630
|
+
/**
|
|
631
|
+
* Header names that count as credentials for the redirect and upload guards:
|
|
632
|
+
* the defaults plus anything configured, always. Narrowing `redact` cannot shrink it.
|
|
633
|
+
*/
|
|
634
|
+
readonly credentialHeaders: readonly string[];
|
|
635
|
+
readonly logger: ConduitLogger;
|
|
636
|
+
}
|
|
637
|
+
/** A change to what the cache holds, for the plugins that mirror it. */
|
|
638
|
+
type CacheChange = {
|
|
639
|
+
readonly type: "invalidate";
|
|
640
|
+
/** A key, a `tag:name`, or `*` for everything. */
|
|
641
|
+
readonly target: string;
|
|
642
|
+
} | {
|
|
643
|
+
readonly type: "set";
|
|
644
|
+
readonly key: string;
|
|
645
|
+
readonly data: unknown;
|
|
646
|
+
readonly at: number;
|
|
647
|
+
};
|
|
648
|
+
/** What a plugin is handed at install time. */
|
|
649
|
+
interface PluginContext {
|
|
650
|
+
readonly config: ResolvedClientConfig;
|
|
651
|
+
readonly events: EventBus;
|
|
652
|
+
/** Re-enters the full pipeline from a path. Guard against recursion via `meta`. */
|
|
653
|
+
request<T = unknown>(path: string, options?: RequestOptions): ConduitPromise<T>;
|
|
654
|
+
/**
|
|
655
|
+
* Re-enters the pipeline from the outside with a request that already exists,
|
|
656
|
+
* so layers above yours see the response. Mark it or your middleware loops.
|
|
657
|
+
*/
|
|
658
|
+
readonly dispatch: Next;
|
|
659
|
+
/** Whether an absolute url sits on the client's own API origin. */
|
|
660
|
+
isApiOrigin(url: string): boolean;
|
|
661
|
+
/**
|
|
662
|
+
* Drops everything held on behalf of whoever was signed in. Identity is
|
|
663
|
+
* derived before credentials are attached, so cached responses outlive them.
|
|
664
|
+
*/
|
|
665
|
+
resetIdentity(): void;
|
|
666
|
+
/** Registers state to drop when {@link PluginContext.resetIdentity} runs. */
|
|
667
|
+
onResetIdentity(listener: () => void): Unsubscribe;
|
|
668
|
+
/** Tells the plugins that mirror the cache about a change to it. */
|
|
669
|
+
notifyCacheChange(change: CacheChange): void;
|
|
670
|
+
/** Registers for {@link PluginContext.notifyCacheChange}. */
|
|
671
|
+
onCacheChange(listener: (change: CacheChange) => void): Unsubscribe;
|
|
672
|
+
}
|
|
673
|
+
/** A promise of the decoded body, with two other ways to take the same outcome. */
|
|
674
|
+
interface ConduitPromise<T> extends Promise<T> {
|
|
675
|
+
/** The full response record rather than just the body. */
|
|
676
|
+
response(): Promise<ConduitResponse<T>>;
|
|
677
|
+
/** Never rejects. Returns the failure as a value instead. */
|
|
678
|
+
safe(): Promise<SafeResult<T>>;
|
|
679
|
+
}
|
|
680
|
+
interface RequestMethods {
|
|
681
|
+
request<T = unknown, const P extends string = string>(path: P, ...args: OptionsArgs<P, RequestOptions>): ConduitPromise<T>;
|
|
682
|
+
get<T = unknown, const P extends string = string>(path: P, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
|
|
683
|
+
head<T = unknown, const P extends string = string>(path: P, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
|
|
684
|
+
delete<T = unknown, const P extends string = string>(path: P, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
|
|
685
|
+
post<T = unknown, const P extends string = string>(path: P, body?: unknown, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
|
|
686
|
+
put<T = unknown, const P extends string = string>(path: P, body?: unknown, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
|
|
687
|
+
patch<T = unknown, const P extends string = string>(path: P, body?: unknown, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
|
|
688
|
+
}
|
|
689
|
+
export { Unsubscribe as $, SafeResult as A, ClientDestroyEvent as B, RedactConfig as C, RequestPatch as D, RequestOptions as E, CacheHitEvent as F, DedupeJoinEvent as G, ConduitEvent as H, CacheInvalidateEvent as I, RequestErrorEvent as J, EventBus as K, CacheMissEvent as L, DEFAULT_REDACT as M, RedactRules as N, ResolvedClientConfig as O, ApiVersionMismatchEvent as P, SessionChangeEvent as Q, CacheSetEvent as R, QueryValue as S, RequestMethods as T, ConduitEventMap as U, ClientEvents as V, ConduitEventType as W, RequestStartEvent as X, RequestSettleEvent as Y, RetryAttemptEvent as Z, PathParams as _, isConduitError as _t, ConduitRequest as a, SessionHandle as at, PluginContext as b, HttpMethod as c, session as ct, Middleware as d, ApiVersionMismatch as dt, ConduitLogger as et, Next as f, apiVersion as ft, PathParamNames as g, ConduitErrorJson as gt, ParseMode as h, ConduitErrorInit as ht, ConduitPromise as i, SessionConfig as it, Vary as j, ResponseSource as k, Lane as l, ReadableStore as lt, OptionsArgs as m, ConduitErrorCode as mt, ClientConfig as n, SessionAdapter as nt, ConduitResponse as o, SessionState as ot, NoExtension as p, ConduitError as pt, QueueEnqueueEvent as q, ConduitMeta as r, SessionApi as rt, FetchLike as s, SessionStatus as st, CacheChange as t, AdapterContext as tt, MethodOptions as u, ApiVersionConfig as ut, PathParamsOf as v, isErrorCode as vt, RequestInitPassthrough as w, Query as x, Plugin as y, toConduitError as yt, CacheStaleEvent as z };
|