@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.
@@ -0,0 +1,142 @@
1
+ import { E as RequestOptions, O as ResolvedClientConfig, T as RequestMethods, V as ClientEvents, c as HttpMethod, g as PathParamNames, i as ConduitPromise, m as OptionsArgs, n as ClientConfig, u as MethodOptions, v as PathParamsOf, x as Query, y as Plugin } from "./types-B9nuOKel.js";
2
+ /**
3
+ * The subset of the Standard Schema contract (https://standardschema.dev)
4
+ * conduit needs. Duplicated rather than depended on, since conduit ships zero
5
+ * dependencies, and any validator that implements the real spec satisfies this too.
6
+ */
7
+ interface StandardSchemaV1<Input = unknown, Output = Input> {
8
+ readonly "~standard": {
9
+ readonly version: 1;
10
+ readonly vendor: string;
11
+ validate(value: unknown): {
12
+ readonly value: Output;
13
+ } | {
14
+ readonly issues: ReadonlyArray<{
15
+ readonly message: string;
16
+ }>;
17
+ } | Promise<{
18
+ readonly value: Output;
19
+ } | {
20
+ readonly issues: ReadonlyArray<{
21
+ readonly message: string;
22
+ }>;
23
+ }>;
24
+ };
25
+ }
26
+ interface EndpointDefinition<Vars = void, Result = unknown> {
27
+ method: HttpMethod;
28
+ /** May contain `:name` placeholders, filled from `vars` by name. */
29
+ path: string;
30
+ /** Validates and reshapes the decoded body. A plain function works too. */
31
+ response?: StandardSchemaV1<unknown, Result> | ((data: unknown) => Result) | undefined;
32
+ query?: ((vars: Vars) => Query) | undefined;
33
+ /** Write methods only: JSON-encoded unless it is already a `BodyInit`. */
34
+ body?: ((vars: Vars) => unknown) | undefined;
35
+ /** Labels for `invalidateTag`. They never switch caching on, `cacheable` does. */
36
+ tags?: readonly string[] | ((vars: Vars) => readonly string[]) | undefined;
37
+ invalidates?: readonly string[] | ((vars: Vars) => readonly string[]) | undefined;
38
+ /** Whether this endpoint reads, so cache and dedupe may serve it. Defaults to `GET` and `HEAD`. */
39
+ cacheable?: boolean | undefined;
40
+ options?: Partial<RequestOptions> | undefined;
41
+ }
42
+ /** Branded so a call site can tell an endpoint from a bare `RequestOptions` object. */
43
+ type Endpoint<Vars = void, Result = unknown> = EndpointDefinition<Vars, Result> & {
44
+ readonly kind: "conduit.endpoint";
45
+ };
46
+ /** `vars` for a path literal: its `:name` placeholders, or `void` when it has none. */
47
+ type PathVars<P extends string> = [PathParamNames<P>] extends [never] ? void : PathParamsOf<P>;
48
+ /**
49
+ * Names a request once, so it can be called and keyed without repeating its
50
+ * shape. `defineEndpoint` does no work beyond branding, so everything it
51
+ * describes runs when `client.call()` reads it.
52
+ *
53
+ * Without type arguments, `vars` is read from the path literal, so
54
+ * `/users/:id` asks for `{ id }`. Give `Vars` and `Result` yourself when the
55
+ * variables carry more than the path params.
56
+ *
57
+ * ```ts
58
+ * const getUser = defineEndpoint({
59
+ * method: 'GET',
60
+ * path: '/users/:id',
61
+ * response: userSchema,
62
+ * tags: ['users'],
63
+ * })
64
+ *
65
+ * const user = await api.call(getUser, { id: '7' })
66
+ * ```
67
+ */
68
+ declare function defineEndpoint<const P extends string, Result = unknown>(def: EndpointDefinition<PathVars<P>, Result> & {
69
+ path: P;
70
+ }): Endpoint<PathVars<P>, Result>;
71
+ declare function defineEndpoint<Vars = void, Result = unknown>(def: EndpointDefinition<Vars, Result>): Endpoint<Vars, Result>;
72
+ /**
73
+ * A cancellation boundary with the client's full request surface. Hand one to a
74
+ * remote on mount and dispose it on unmount, and nothing it started outlives it.
75
+ */
76
+ interface Scope extends RequestMethods {
77
+ readonly name: string;
78
+ /** The signal of the current generation. It changes each time {@link Scope.abort} runs. */
79
+ readonly signal: AbortSignal;
80
+ /** Cancels everything in flight through this scope. The scope stays usable. */
81
+ abort(reason?: string): void;
82
+ /** Cancels everything in flight and ends the scope for good. Safe to call twice. */
83
+ dispose(): void;
84
+ }
85
+ declare class Client implements RequestMethods {
86
+ #private;
87
+ constructor(config?: ClientConfig);
88
+ get config(): ResolvedClientConfig;
89
+ /** Whether {@link Client.destroy} has run. */
90
+ isDestroyed(): boolean;
91
+ /** Every request start, settle and failure, plus whatever plugins publish. */
92
+ get events(): ClientEvents;
93
+ /**
94
+ * The key a request would get, without issuing it.
95
+ *
96
+ * ```ts
97
+ * api.invalidate(api.getKey('/users/:id', { params: { id } }))
98
+ * api.invalidate(api.getKey(getUser, { id: '7' }))
99
+ * ```
100
+ */
101
+ getKey(path: string, options?: RequestOptions): string;
102
+ getKey<Vars, Result>(endpoint: Endpoint<Vars, Result>, vars: Vars): string;
103
+ /**
104
+ * Installs a plugin and merges what it returns onto the client, so the
105
+ * extension shows up in the type. `client.invalidate()` does not compile
106
+ * until `cache()` is installed.
107
+ */
108
+ with<Ext extends object>(plugin: Plugin<Ext>): this & Ext;
109
+ request<T = unknown, const P extends string = string>(path: P, ...args: OptionsArgs<P, RequestOptions>): ConduitPromise<T>;
110
+ get<T = unknown, const P extends string = string>(path: P, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
111
+ head<T = unknown, const P extends string = string>(path: P, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
112
+ delete<T = unknown, const P extends string = string>(path: P, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
113
+ post<T = unknown, const P extends string = string>(path: P, body?: unknown, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
114
+ put<T = unknown, const P extends string = string>(path: P, body?: unknown, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
115
+ patch<T = unknown, const P extends string = string>(path: P, body?: unknown, ...args: OptionsArgs<P, MethodOptions>): ConduitPromise<T>;
116
+ /**
117
+ * Runs a {@link defineEndpoint | typed endpoint}: `vars` fill its path
118
+ * params, build its query and body, and its `response` schema, if it has
119
+ * one, validates the decoded body before this resolves. A failing schema
120
+ * rejects with code `VALIDATION_FAILED`, carrying the issues as `body`.
121
+ *
122
+ * ```ts
123
+ * const user = await api.call(getUser, { id: '7' })
124
+ * ```
125
+ */
126
+ call<Vars, Result>(endpoint: Endpoint<Vars, Result>, vars: Vars, options?: Partial<RequestOptions>): ConduitPromise<Result>;
127
+ /**
128
+ * Posts a `FormData` or `Blob`, with no default timeout, since a slow
129
+ * connection is not a hung one. It is a `post` that defaults its method and
130
+ * skips the timeout, and it runs through the same middleware stack as
131
+ * everything else. For progress events use `uploadWithProgress` from the
132
+ * `/upload` entry.
133
+ */
134
+ upload<T = unknown>(path: string, body: FormData | Blob, options?: MethodOptions): ConduitPromise<T>;
135
+ /** Opens a cancellation boundary. Requests made through it carry `name` as their owner. */
136
+ scope(name: string): Scope;
137
+ /** Cancels everything in flight, across every scope. The client and its scopes stay usable. */
138
+ abortAll(reason?: string): void;
139
+ destroy(): void;
140
+ }
141
+ declare function createClient(config?: ClientConfig): Client;
142
+ export { EndpointDefinition as a, defineEndpoint as c, Endpoint as i, createClient as n, PathVars as o, Scope as r, StandardSchemaV1 as s, Client as t };
@@ -0,0 +1,14 @@
1
+ // src/primitives/dev.ts
2
+ /**
3
+ * False wherever `process` is missing, which is the safe side: devtools exposure
4
+ * is `expose ?? IS_DEVELOPMENT`, so an unknown environment never exposes itself.
5
+ */
6
+ const IS_DEVELOPMENT = (() => {
7
+ try {
8
+ return process.env.NODE_ENV !== "production";
9
+ } catch {
10
+ return false;
11
+ }
12
+ })();
13
+
14
+ export { IS_DEVELOPMENT as t };
@@ -0,0 +1,61 @@
1
+ import { t as Client } from "./core-DXSbz15-.js";
2
+ import { c as HttpMethod, k as ResponseSource, l as Lane, lt as ReadableStore, mt as ConduitErrorCode, st as SessionStatus } from "./types-B9nuOKel.js";
3
+ export interface DevtoolsEntry {
4
+ readonly id: number;
5
+ readonly key: string;
6
+ readonly method: HttpMethod;
7
+ readonly url: string;
8
+ /** Which app or remote issued it. */
9
+ readonly owner: string | undefined;
10
+ readonly lane: Lane;
11
+ readonly state: "pending" | "success" | "error";
12
+ readonly from: ResponseSource | undefined;
13
+ readonly status: number | undefined;
14
+ readonly code: ConduitErrorCode | undefined;
15
+ /** The id the `requestId` plugin sent, when it is installed. */
16
+ readonly requestId: string | undefined;
17
+ readonly durationMs: number | undefined;
18
+ readonly startedAt: number;
19
+ }
20
+ export interface DevtoolsCounters {
21
+ readonly requests: number;
22
+ readonly failures: number;
23
+ readonly cacheHits: number;
24
+ readonly cacheMisses: number;
25
+ readonly cacheStale: number;
26
+ readonly dedupeJoins: number;
27
+ readonly retries: number;
28
+ readonly queued: number;
29
+ }
30
+ export interface DevtoolsState {
31
+ /** Most recent first. */
32
+ readonly entries: readonly DevtoolsEntry[];
33
+ readonly inFlight: number;
34
+ readonly counters: DevtoolsCounters;
35
+ readonly session: SessionStatus | undefined;
36
+ /** Set once the session is gone and cannot be recovered. */
37
+ readonly isSessionLost: boolean;
38
+ }
39
+ export interface DevtoolsConfig {
40
+ /** How many finished requests to keep. Defaults to 100. */
41
+ max?: number | undefined;
42
+ /**
43
+ * Hang the handle on `globalThis.__CONDUIT_DEVTOOLS__` for console access.
44
+ * Defaults to `IS_DEVELOPMENT`, so a production build never exposes it unasked.
45
+ */
46
+ expose?: boolean | undefined;
47
+ }
48
+ export interface Devtools {
49
+ readonly store: ReadableStore<DevtoolsState>;
50
+ /** Drops the log and zeroes the counters. In-flight requests keep reporting. */
51
+ clear(): void;
52
+ /** Unsubscribes from the client and removes the global handle. */
53
+ detach(): void;
54
+ }
55
+ /**
56
+ * Watches one client through its event stream and nothing else, so a shared
57
+ * client shows traffic from every remote on the page, attributed by owner.
58
+ */
59
+ export declare function attachDevtools(client: Client, config?: DevtoolsConfig): Devtools;
60
+ /** Reads the handle a previous {@link attachDevtools} exposed, if any. */
61
+ export declare function getDevtools(): Devtools | undefined;
@@ -0,0 +1,152 @@
1
+ import { d as stripQuery, t as createStore } from "./stores-DGXWZXXg.js";
2
+ import { t as IS_DEVELOPMENT } from "./dev-CNYwEGcY.js";
3
+
4
+ // src/devtools.ts
5
+ const EMPTY_COUNTERS = {
6
+ requests: 0,
7
+ failures: 0,
8
+ cacheHits: 0,
9
+ cacheMisses: 0,
10
+ cacheStale: 0,
11
+ dedupeJoins: 0,
12
+ retries: 0,
13
+ queued: 0
14
+ };
15
+ const DEFAULT_MAX_ENTRIES = 100;
16
+ const GLOBAL_KEY = "__CONDUIT_DEVTOOLS__";
17
+ /**
18
+ * Watches one client through its event stream and nothing else, so a shared
19
+ * client shows traffic from every remote on the page, attributed by owner.
20
+ */
21
+ function attachDevtools(client, config = {}) {
22
+ const max = config.max ?? DEFAULT_MAX_ENTRIES;
23
+ const store = createStore({
24
+ entries: [],
25
+ inFlight: 0,
26
+ counters: EMPTY_COUNTERS,
27
+ session: void 0,
28
+ isSessionLost: false
29
+ });
30
+ const pending = /* @__PURE__ */ new Map();
31
+ let nextId = 0;
32
+ const bump = (counter) => {
33
+ store.update((current) => ({
34
+ ...current,
35
+ counters: {
36
+ ...current.counters,
37
+ [counter]: current.counters[counter] + 1
38
+ }
39
+ }));
40
+ };
41
+ const complete = (request, patch) => {
42
+ const id = pending.get(request);
43
+ if (id === void 0) return;
44
+ pending.delete(request);
45
+ store.update((current) => ({
46
+ ...current,
47
+ inFlight: pending.size,
48
+ entries: current.entries.map((entry) => entry.id === id ? {
49
+ ...entry,
50
+ ...patch
51
+ } : entry)
52
+ }));
53
+ };
54
+ const unsubscribe = client.events.onAny((event) => {
55
+ switch (event.type) {
56
+ case "request:start": {
57
+ const id = nextId++;
58
+ pending.set(event.request, id);
59
+ store.update((current) => ({
60
+ ...current,
61
+ inFlight: pending.size,
62
+ counters: {
63
+ ...current.counters,
64
+ requests: current.counters.requests + 1
65
+ },
66
+ entries: [{
67
+ id,
68
+ key: stripQuery(event.request.key),
69
+ method: event.request.method,
70
+ url: stripQuery(event.request.url),
71
+ owner: event.request.owner,
72
+ lane: event.request.lane,
73
+ state: "pending",
74
+ from: void 0,
75
+ status: void 0,
76
+ code: void 0,
77
+ requestId: void 0,
78
+ durationMs: void 0,
79
+ startedAt: event.at
80
+ }, ...current.entries.slice(0, max - 1)]
81
+ }));
82
+ break;
83
+ }
84
+ case "request:settle":
85
+ complete(event.request, {
86
+ state: "success",
87
+ from: event.response.from,
88
+ status: event.response.status,
89
+ requestId: event.request.meta.requestId,
90
+ durationMs: event.durationMs
91
+ });
92
+ break;
93
+ case "request:error":
94
+ complete(event.request, {
95
+ state: "error",
96
+ status: event.error.status,
97
+ code: event.error.code,
98
+ requestId: event.error.requestId ?? event.request.meta.requestId,
99
+ durationMs: event.durationMs
100
+ });
101
+ bump("failures");
102
+ break;
103
+ case "cache:hit":
104
+ bump("cacheHits");
105
+ break;
106
+ case "cache:miss":
107
+ bump("cacheMisses");
108
+ break;
109
+ case "cache:stale":
110
+ bump("cacheStale");
111
+ break;
112
+ case "dedupe:join":
113
+ bump("dedupeJoins");
114
+ break;
115
+ case "retry:attempt":
116
+ bump("retries");
117
+ break;
118
+ case "queue:enqueue":
119
+ bump("queued");
120
+ break;
121
+ case "session:change": store.update((current) => ({
122
+ ...current,
123
+ session: event.status,
124
+ isSessionLost: event.isLost
125
+ }));
126
+ }
127
+ });
128
+ const devtools = {
129
+ store,
130
+ clear: () => {
131
+ store.update((current) => ({
132
+ ...current,
133
+ entries: [],
134
+ counters: EMPTY_COUNTERS
135
+ }));
136
+ },
137
+ detach: () => {
138
+ unsubscribe();
139
+ pending.clear();
140
+ const scope = globalThis;
141
+ if (scope[GLOBAL_KEY] === devtools) Reflect.deleteProperty(scope, GLOBAL_KEY);
142
+ }
143
+ };
144
+ if (config.expose ?? IS_DEVELOPMENT) globalThis[GLOBAL_KEY] = devtools;
145
+ return devtools;
146
+ }
147
+ /** Reads the handle a previous {@link attachDevtools} exposed, if any. */
148
+ function getDevtools() {
149
+ return globalThis[GLOBAL_KEY];
150
+ }
151
+
152
+ export { attachDevtools, getDevtools };
@@ -0,0 +1,85 @@
1
+ // src/primitives/errors.ts
2
+ var ConduitError = class extends Error {
3
+ name = "ConduitError";
4
+ /** Cross-realm brand. Two bundles carrying their own copy break `instanceof`. */
5
+ conduitError = true;
6
+ code;
7
+ method;
8
+ /** The request url with secret query values replaced, never the raw one. */
9
+ url;
10
+ status;
11
+ /** The app or remote that issued the request, which the shared stack trace cannot say. */
12
+ owner;
13
+ /** Milliseconds the server asked to wait, from `Retry-After`. The retry plugin fills it in. */
14
+ retryAfterMs;
15
+ /** The id the `requestId` plugin sent with the failing attempt. */
16
+ requestId;
17
+ constructor(init) {
18
+ super(init.message, init.cause === void 0 ? void 0 : { cause: init.cause });
19
+ this.code = init.code;
20
+ this.method = init.method;
21
+ this.url = init.url;
22
+ this.status = init.status;
23
+ this.owner = init.owner;
24
+ this.retryAfterMs = init.retryAfterMs;
25
+ this.requestId = init.requestId;
26
+ Object.defineProperty(this, "headers", {
27
+ value: init.headers,
28
+ configurable: true
29
+ });
30
+ Object.defineProperty(this, "body", {
31
+ value: init.body,
32
+ configurable: true
33
+ });
34
+ }
35
+ toJSON() {
36
+ return {
37
+ name: this.name,
38
+ code: this.code,
39
+ message: this.message,
40
+ method: this.method,
41
+ url: this.url,
42
+ status: this.status,
43
+ owner: this.owner,
44
+ requestId: this.requestId
45
+ };
46
+ }
47
+ };
48
+ /** Brand check rather than `instanceof`, so it holds across federation boundaries. */
49
+ function isConduitError(value) {
50
+ return typeof value === "object" && value !== null && "conduitError" in value;
51
+ }
52
+ /** Narrows to a specific failure mode. `isConduitError(e) && e.code === 'TIMEOUT'` in one call. */
53
+ function isErrorCode(value, code) {
54
+ return isConduitError(value) && value.code === code;
55
+ }
56
+ /**
57
+ * Coerces anything thrown into a `ConduitError`. A conduit error passes through
58
+ * untouched unless a `code` or `message` asks for a different one, and then it is
59
+ * copied, with the original as its `cause`.
60
+ */
61
+ function toConduitError(value, code, message) {
62
+ if (isConduitError(value)) {
63
+ if (code === void 0 && message === void 0) return value;
64
+ return new ConduitError({
65
+ code: code ?? value.code,
66
+ message: message ?? value.message,
67
+ method: value.method,
68
+ url: value.url,
69
+ status: value.status,
70
+ owner: value.owner,
71
+ requestId: value.requestId,
72
+ headers: value.headers,
73
+ body: value.body,
74
+ cause: value
75
+ });
76
+ }
77
+ const detail = value instanceof Error ? value.message : String(value);
78
+ return new ConduitError({
79
+ code: code ?? "UNKNOWN",
80
+ message: message ?? detail,
81
+ cause: value
82
+ });
83
+ }
84
+
85
+ export { toConduitError as i, isConduitError as n, isErrorCode as r, ConduitError as t };
@@ -0,0 +1,177 @@
1
+ import { a as EndpointDefinition, c as defineEndpoint, i as Endpoint, n as createClient, o as PathVars, r as Scope, s as StandardSchemaV1, t as Client } from "./core-DXSbz15-.js";
2
+ import { $ as Unsubscribe, A as SafeResult, B as ClientDestroyEvent, C as RedactConfig, D as RequestPatch, E as RequestOptions, F as CacheHitEvent, G as DedupeJoinEvent, H as ConduitEvent, I as CacheInvalidateEvent, J as RequestErrorEvent, K as EventBus, L as CacheMissEvent, M as DEFAULT_REDACT, N as RedactRules, O as ResolvedClientConfig, P as ApiVersionMismatchEvent, Q as SessionChangeEvent, R as CacheSetEvent, S as QueryValue, T as RequestMethods, U as ConduitEventMap, V as ClientEvents, W as ConduitEventType, X as RequestStartEvent, Y as RequestSettleEvent, Z as RetryAttemptEvent, _ as PathParams, _t as isConduitError, a as ConduitRequest, at as SessionHandle, b as PluginContext, c as HttpMethod, ct as session, d as Middleware, dt as ApiVersionMismatch, et as ConduitLogger, f as Next, ft as apiVersion, g as PathParamNames, gt as ConduitErrorJson, h as ParseMode, ht as ConduitErrorInit, i as ConduitPromise, it as SessionConfig, j as Vary, k as ResponseSource, l as Lane, lt as ReadableStore, m as OptionsArgs, mt as ConduitErrorCode, n as ClientConfig, nt as SessionAdapter, o as ConduitResponse, ot as SessionState, p as NoExtension, pt as ConduitError, q as QueueEnqueueEvent, r as ConduitMeta, rt as SessionApi, s as FetchLike, st as SessionStatus, t as CacheChange, tt as AdapterContext, u as MethodOptions, ut as ApiVersionConfig, v as PathParamsOf, vt as isErrorCode, w as RequestInitPassthrough, x as Query, y as Plugin, yt as toConduitError, z as CacheStaleEvent } from "./types-B9nuOKel.js";
3
+ import { a as QueryStatus, i as QueryState, n as ObservableConfig, r as observable, t as ObservableApi } from "./observable-LsEew2iL.js";
4
+ import { c as sharedClient, i as SharedMismatchKind, n as SharedClientConfig, o as getSharedClient, r as SharedMismatch, s as releaseSharedClient, t as HotContext } from "./shared-2HssxK9p.js";
5
+ interface CacheConfig {
6
+ /** How long a stored response counts as fresh. Defaults to 30 seconds. */
7
+ ttlMs?: number | undefined;
8
+ /**
9
+ * How long past `ttlMs` a stale response may still be served while a refresh
10
+ * runs behind it. `Infinity` means indefinitely, and the default 0 means never.
11
+ */
12
+ staleMs?: number | undefined;
13
+ /** Entry cap. Defaults to 200. The oldest read is evicted first. */
14
+ max?: number | undefined;
15
+ }
16
+ interface CacheApi {
17
+ /**
18
+ * Drops one entry and suppresses any read of that key already in flight.
19
+ * `false` means nothing was stored, not that the in-flight read survives.
20
+ */
21
+ invalidate(key: string): boolean;
22
+ /** Drops every entry carrying a tag. Returns how many went. */
23
+ invalidateTag(tag: string): number;
24
+ clearCache(): void;
25
+ getCacheSize(): number;
26
+ /**
27
+ * Writes a value directly, for an optimistic update, without a network
28
+ * round trip. Also reaches any mounted `useRequest` watching the same key.
29
+ * Returns the previous value, so a failed mutation can roll back to it.
30
+ */
31
+ setData<T = unknown>(key: string, data: T | ((previous: T | undefined) => T)): T | undefined;
32
+ }
33
+ /**
34
+ * A response cache shared by every bundle, so a remote that mounts second reads
35
+ * what the first already fetched. A hit costs a map lookup and nothing else.
36
+ *
37
+ * It stores what `request.cacheable` allows, which is `GET` and `HEAD` unless a
38
+ * request or endpoint says otherwise. Tags only label entries for `invalidateTag`.
39
+ */
40
+ export declare function cache(config?: CacheConfig): Plugin<CacheApi>;
41
+ interface DedupeApi {
42
+ /** Distinct requests currently in flight and shareable. */
43
+ getInFlightCount(): number;
44
+ }
45
+ /**
46
+ * One request per key, however many callers ask for it. It shares a flight for
47
+ * every request that is `cacheable`.
48
+ *
49
+ * Cancellation is reference-counted. The flight runs on its own controller and
50
+ * aborts when the last participant leaves, so one remote unmounting cancels its
51
+ * own wait and nobody else's.
52
+ */
53
+ export declare function dedupe(): Plugin<DedupeApi>;
54
+ interface QueueConfig {
55
+ /** How many requests may be in flight at once. Defaults to 6. */
56
+ concurrency?: number | undefined;
57
+ /** Lanes in priority order, most urgent first. */
58
+ lanes?: readonly Lane[] | undefined;
59
+ /** Per-lane ceilings, so one lane cannot take the whole pool. Minimum 1. */
60
+ limits?: Readonly<Record<string, number>> | undefined;
61
+ }
62
+ interface QueueApi {
63
+ /** Requests waiting for a slot, optionally in one lane. */
64
+ getQueueDepth(lane?: Lane): number;
65
+ /** Requests currently holding a slot. */
66
+ getActiveCount(): number;
67
+ }
68
+ /**
69
+ * Bounded concurrency with priority lanes, so a remote's speculative
70
+ * prefetching cannot queue ahead of the host's boot path down in the browser's
71
+ * connection pool.
72
+ */
73
+ export declare function queue(config?: QueueConfig): Plugin<QueueApi>;
74
+ interface RetryInfo {
75
+ readonly request: ConduitRequest;
76
+ readonly error: ConduitError;
77
+ /** The attempt that just failed. */
78
+ readonly attempt: number;
79
+ readonly delayMs: number;
80
+ }
81
+ interface RetryConfig {
82
+ /** Total attempts including the first. Defaults to 3. */
83
+ attempts?: number | undefined;
84
+ /** First backoff step in milliseconds. Defaults to 300. */
85
+ baseDelayMs?: number | undefined;
86
+ /** Ceiling for a single backoff step. Defaults to 5000. */
87
+ maxDelayMs?: number | undefined;
88
+ /**
89
+ * The longest `Retry-After` that is honoured. A server asking for more gets
90
+ * no retry rather than a clamped one. Defaults to 30 seconds.
91
+ */
92
+ maxRetryAfterMs?: number | undefined;
93
+ /** Spread retries across the window instead of stacking them. Defaults to true. */
94
+ jitter?: boolean | undefined;
95
+ /**
96
+ * Refuse to replay `POST` and `PATCH`, except a request marked `cacheable`,
97
+ * which only reads. Defaults to true.
98
+ */
99
+ idempotentOnly?: boolean | undefined;
100
+ /** Response statuses worth another attempt. */
101
+ statuses?: readonly number[] | undefined;
102
+ /** Replaces the built-in decision entirely. */
103
+ shouldRetry?: ((error: ConduitError, request: ConduitRequest, attempt: number) => boolean) | undefined;
104
+ onRetry?: ((info: RetryInfo) => void) | undefined;
105
+ }
106
+ /**
107
+ * Replays a failed request with exponential backoff. Install it outside the
108
+ * queue so a replay waits its turn instead of amplifying a failing endpoint.
109
+ */
110
+ export declare function retry(config?: RetryConfig): Plugin;
111
+ /** A per-request override goes through `meta: { timeoutMs }`, and `0` turns the timeout off. */
112
+ interface TimeoutConfig {
113
+ /** Milliseconds before a request is cancelled. Defaults to 15 seconds. */
114
+ ms?: number | undefined;
115
+ }
116
+ /**
117
+ * Cancels a request that has taken too long, with code `TIMEOUT` rather than a
118
+ * generic abort. Install it innermost so the clock covers one network attempt
119
+ * rather than a whole retry sequence.
120
+ */
121
+ export declare function timeout(config?: TimeoutConfig): Plugin;
122
+ interface DefaultsConfig {
123
+ observable?: ObservableConfig | undefined;
124
+ cache?: CacheConfig | undefined;
125
+ queue?: QueueConfig | undefined;
126
+ /** `false` leaves retry out. */
127
+ retry?: RetryConfig | false | undefined;
128
+ /** `false` leaves the timeout out. */
129
+ timeout?: TimeoutConfig | false | undefined;
130
+ }
131
+ interface DefaultsWithSession<S> extends DefaultsConfig {
132
+ session: SessionConfig<S>;
133
+ }
134
+ type DefaultClient = Client & ObservableApi & CacheApi & DedupeApi & QueueApi;
135
+ /**
136
+ * Installs the standard stack, in the order the layers need to be in.
137
+ *
138
+ * ```
139
+ * observable → cache → dedupe → session → retry → queue → timeout → transport
140
+ * ```
141
+ *
142
+ * Only `retry` and `timeout` can be left out. The rest add methods to the
143
+ * client, so a preset that sometimes returned them would lie in its own type.
144
+ * Compose `.with()` by hand for a stack this cannot express. Install
145
+ * `requestId()` after this, so it sits innermost.
146
+ *
147
+ * ```ts
148
+ * const api = defaults(createClient({ baseUrl: '/api' }), {
149
+ * cache: { ttlMs: 30_000, staleMs: Infinity },
150
+ * session: { adapter: mySessionAdapter },
151
+ * })
152
+ * ```
153
+ */
154
+ export declare function defaults<S>(client: Client, config: DefaultsWithSession<S>): DefaultClient & SessionApi<S>;
155
+ export declare function defaults(client: Client, config?: DefaultsConfig): DefaultClient;
156
+ interface RequestIdConfig {
157
+ /** The header that carries the id. Defaults to `x-request-id`. */
158
+ header?: string | undefined;
159
+ /** Makes an id. Defaults to `crypto.randomUUID()`. */
160
+ generate?: (() => string) | undefined;
161
+ }
162
+ /**
163
+ * Sends an id with every attempt, and records it on `ConduitError.requestId`,
164
+ * on `response.request.meta.requestId` and on devtools entries, so a failure in
165
+ * the UI leads straight to the server's log line.
166
+ *
167
+ * Install it last, inside cache and dedupe. The id then never reaches a key,
168
+ * and each retry goes out with an id of its own. A header the caller already
169
+ * set is kept and reported as it is.
170
+ */
171
+ export declare function requestId(config?: RequestIdConfig): Plugin;
172
+ /**
173
+ * A copy with the given fields replaced. Rewriting what a request is re-derives
174
+ * what it is identified by, unless the patch names a key itself.
175
+ */
176
+ export declare function withRequest(request: ConduitRequest, patch: RequestPatch): ConduitRequest;
177
+ export { type AdapterContext, type ApiVersionConfig, type ApiVersionMismatch, type ApiVersionMismatchEvent, type CacheApi, type CacheChange, type CacheConfig, type CacheHitEvent, type CacheInvalidateEvent, type CacheMissEvent, type CacheSetEvent, type CacheStaleEvent, type Client, type ClientConfig, type ClientDestroyEvent, type ClientEvents, ConduitError, type ConduitErrorCode, type ConduitErrorInit, type ConduitErrorJson, type ConduitEvent, type ConduitEventMap, type ConduitEventType, type ConduitLogger, type ConduitMeta, type ConduitPromise, type ConduitRequest, type ConduitResponse, DEFAULT_REDACT, type DedupeApi, type DedupeJoinEvent, type DefaultClient, type DefaultsConfig, type DefaultsWithSession, type Endpoint, type EndpointDefinition, type EventBus, type FetchLike, type HotContext, type HttpMethod, type Lane, type MethodOptions, type Middleware, type Next, type NoExtension, type ObservableApi, type ObservableConfig, type OptionsArgs, type ParseMode, type PathParamNames, type PathParams, type PathParamsOf, type PathVars, type Plugin, type PluginContext, type Query, type QueryState, type QueryStatus, type QueryValue, type QueueApi, type QueueConfig, type QueueEnqueueEvent, type ReadableStore, type RedactConfig, type RedactRules, type RequestErrorEvent, type RequestIdConfig, type RequestInitPassthrough, type RequestMethods, type RequestOptions, type RequestPatch, type RequestSettleEvent, type RequestStartEvent, type ResolvedClientConfig, type ResponseSource, type RetryAttemptEvent, type RetryConfig, type RetryInfo, type SafeResult, type Scope, type SessionAdapter, type SessionApi, type SessionChangeEvent, type SessionConfig, type SessionHandle, type SessionState, type SessionStatus, type SharedClientConfig, type SharedMismatch, type SharedMismatchKind, type StandardSchemaV1, type TimeoutConfig, type Unsubscribe, type Vary, apiVersion, createClient, defineEndpoint, getSharedClient, isConduitError, isErrorCode, observable, releaseSharedClient, session, sharedClient, toConduitError };