@tupik/client 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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Carlos Alberto Barbosa Stenzel / Tupik Contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,58 @@
1
- # Temporary Holding Version
1
+ # @tupik/client
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Type-safe RPC client for **Tupik**. `createTypedClient<typeof app>()` infers paths, params, inputs and
4
+ response `data` from the app's routes, with no code generation. Includes an SSE stream parser and a
5
+ WebSocket helper.
6
+
7
+ ## Install
8
+
9
+ ```bash
10
+ npm install @tupik/client @tupik/core
11
+ ```
12
+
13
+ ## Usage
14
+
15
+ ```ts
16
+ import { createApp, createModule } from '@tupik/core';
17
+ import { createTypedClient, streamSse } from '@tupik/client';
18
+
19
+ const app = createApp().register(
20
+ createModule('/users').get('/:id', { access: 'public', handler: (ctx) => ({ id: ctx.params.id, name: 'Ada' }) }),
21
+ );
22
+
23
+ // In production pass `baseUrl` of the server; here the client calls the app in-process.
24
+ const client = createTypedClient<typeof app>({
25
+ baseUrl: 'http://localhost',
26
+ fetch: (input, init) => app.fetch(new Request(input, init)),
27
+ });
28
+
29
+ const result = await client.get('/users/:id', { params: { id: '7' } });
30
+ if (result.ok) console.log(result.data.name); // 'Ada' (typed)
31
+ else if (result.kind === 'problem') console.log(result.error.code); // RFC 9457 problem from the API
32
+ else console.log(result.kind); // 'http', 'network', 'timeout' or 'abort'
33
+
34
+ // Server-Sent Events: parse any `text/event-stream` body.
35
+ const { body } = new Response('retry: 5000\n\nevent: tick\ndata: 1\n\n');
36
+ const onControl = (control: { id?: string; retry?: number }) => console.log(control); // { retry: 5000 }
37
+ if (body) for await (const event of streamSse(body, { onControl })) console.log(event); // { event: 'tick', data: '1' }
38
+ ```
39
+
40
+ A frame with `retry:` or `id:` and no `data` dispatches no event, but the WHATWG spec still applies it: `streamSse`
41
+ hands it to `onControl`, and `connectSse` uses it for the reconnect delay and the next `Last-Event-ID`. A server that
42
+ sends `retry: 3000` on connect no longer needs `reconnect.delayMs` to match.
43
+
44
+ ## Key API
45
+
46
+ | Export | Purpose |
47
+ | --- | --- |
48
+ | `createTypedClient<typeof app>({ baseUrl, headers?, fetch? })` | Typed `get`/`post`/`put`/`patch`/`delete`/`head`/`options`; results are `{ ok: true, data, response }` or `{ ok: false, kind, error, response }` with `kind` `'problem'`, `'http'`, `'network'`, `'timeout'` or `'abort'` |
49
+ | `createClient(options)` / `TupikClient` | Untyped client (`request(method, path, options)`) |
50
+ | `RouteErrorCode<Route>` / `AccessProblemCode` | On a typed call, a `kind: 'problem'` result types `error.code` as the route's declared `errors` codes plus `UNAUTHORIZED`/`FORBIDDEN`/`NOT_FOUND` |
51
+ | `streamSse(body, { onControl? })` | Async iterator of `{ event, data, id?, retry? }`; `onControl` gets `{ id?, retry? }` of a frame without `data` |
52
+ | `connectSse(url, { reconnect?, lastEventId?, signal?, fetch?, headers? })` | SSE over `fetch` with optional reconnect: `Last-Event-ID` and the server `retry:` (with or without data) |
53
+ | `createWebSocket(url, options?)` | WebSocket with an injectable constructor |
54
+ | `createRpcProxy(client, prefix?, method?)` | Dynamic property-path proxy |
55
+
56
+ ## License
57
+
58
+ MIT
@@ -0,0 +1,326 @@
1
+ import { HTTPMethod, StandardSchemaV1, InferOutput } from '@tupik/core';
2
+
3
+ /** Retry policy for idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS). Off unless set. */
4
+ interface RetryOptions {
5
+ /** Extra attempts after the first request. */
6
+ attempts: number;
7
+ /** First backoff delay; doubles on every retry. Default 100 ms. */
8
+ baseDelayMs?: number;
9
+ /** Backoff ceiling; a `Retry-After` longer than this ends the retries. Default 5000 ms. */
10
+ maxDelayMs?: number;
11
+ /** Statuses worth retrying. Default 408, 425, 429, 500, 502, 503, 504. */
12
+ statuses?: readonly number[];
13
+ }
14
+ /** Fetch controls set on the client (defaults) and per call (overrides; signals combine). */
15
+ interface FetchControls {
16
+ signal?: AbortSignal;
17
+ /** Milliseconds for the whole call, retries included. */
18
+ timeout?: number;
19
+ credentials?: RequestCredentials;
20
+ retry?: RetryOptions;
21
+ }
22
+ interface ClientOptions extends FetchControls {
23
+ baseUrl: string;
24
+ headers?: Record<string, string> | (() => Record<string, string>);
25
+ fetch?: typeof fetch;
26
+ }
27
+ /** Query value: arrays repeat the key (`?tag=a&tag=b`), `undefined` is omitted. */
28
+ type QueryValue = string | number | boolean | undefined | readonly (string | number | boolean)[];
29
+ interface RequestOptions extends FetchControls {
30
+ params?: Record<string, string>;
31
+ query?: Record<string, QueryValue>;
32
+ headers?: Record<string, string>;
33
+ body?: unknown;
34
+ }
35
+ /**
36
+ * RFC 9457 problem details (`application/problem+json`), extension members
37
+ * included. `code` is the Tupik error code (`ctx.fail`, access denials);
38
+ * validation problems carry none.
39
+ */
40
+ interface Problem<TCode extends string = string> {
41
+ type?: string;
42
+ title?: string;
43
+ status?: number;
44
+ detail?: string;
45
+ instance?: string;
46
+ code?: TCode;
47
+ [extension: string]: unknown;
48
+ }
49
+ /** Why a request produced no response. */
50
+ type ClientFailureKind = 'network' | 'timeout' | 'abort';
51
+ /** Error carried by a result that has no response (network failure, timeout or abort). */
52
+ declare class ClientRequestError extends Error {
53
+ readonly kind: ClientFailureKind;
54
+ constructor(kind: ClientFailureKind, cause: unknown);
55
+ }
56
+ /**
57
+ * Never rejects for HTTP, network, timeout or abort failures: branch on `ok`,
58
+ * then `kind`. `TErrorCode` types `error.code` of a problem (the typed client
59
+ * fills it from the route's `errors`).
60
+ */
61
+ type ClientResult<TData, TErrorCode extends string = string> = {
62
+ ok: true;
63
+ data: TData;
64
+ response: Response;
65
+ } | {
66
+ ok: false;
67
+ kind: 'problem';
68
+ error: Problem<TErrorCode>;
69
+ response: Response;
70
+ } | {
71
+ ok: false;
72
+ kind: 'http';
73
+ error: unknown;
74
+ response: Response;
75
+ } | {
76
+ ok: false;
77
+ kind: ClientFailureKind;
78
+ error: ClientRequestError;
79
+ response: undefined;
80
+ };
81
+ declare class TupikClient {
82
+ #private;
83
+ constructor(options: ClientOptions);
84
+ request<TData = unknown>(method: HTTPMethod, path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
85
+ get<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
86
+ post<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
87
+ put<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
88
+ patch<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
89
+ delete<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
90
+ head<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
91
+ options<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
92
+ }
93
+ declare function createClient(options: ClientOptions): TupikClient;
94
+
95
+ interface SseEvent {
96
+ event: string;
97
+ data: string;
98
+ id?: string;
99
+ retry?: number;
100
+ }
101
+ /** Maximum bytes retained for one unterminated line; a longer line is rejected. */
102
+ declare const SSE_MAX_LINE_LENGTH: number;
103
+ /** Maximum accumulated bytes for one event's fields (e.g. multi-line `data`); a larger event is rejected. */
104
+ declare const SSE_MAX_EVENT_SIZE: number;
105
+ /** Thrown when a line or event exceeds {@link SSE_MAX_LINE_LENGTH}/{@link SSE_MAX_EVENT_SIZE}. */
106
+ declare class SseOverflowError extends Error {
107
+ constructor(message: string);
108
+ }
109
+ /** `id`/`retry` of a frame without `data`: no event is dispatched, but the WHATWG spec still applies them. */
110
+ interface SseControl {
111
+ id?: string;
112
+ retry?: number;
113
+ }
114
+ interface SseStreamOptions {
115
+ /** Called for a frame that carries `id` or `retry` but no `data` (e.g. `retry: 3000` sent on connect). */
116
+ onControl?: (control: SseControl) => void;
117
+ }
118
+ /**
119
+ * Parses a Server-Sent Events byte stream. Buffering is bounded: a single
120
+ * line longer than {@link SSE_MAX_LINE_LENGTH}, or an event whose accumulated
121
+ * fields exceed {@link SSE_MAX_EVENT_SIZE}, rejects with
122
+ * {@link SseOverflowError} and the underlying reader is cancelled; memory
123
+ * never grows unbounded. As the WHATWG SSE spec requires, an event whose
124
+ * terminating blank line never arrives is discarded at end-of-stream, and a
125
+ * frame with `id`/`retry` but no `data` yields nothing but goes to `onControl`.
126
+ */
127
+ declare function streamSse(body: ReadableStream<Uint8Array>, options?: SseStreamOptions): AsyncGenerator<SseEvent>;
128
+ /** Reconnection policy for {@link connectSse}. */
129
+ interface SseReconnectOptions {
130
+ /** Delay before reconnecting until the server sends `retry:` (with or without data). Default 3000 ms. */
131
+ delayMs?: number;
132
+ /** Consecutive reconnects without a received event before giving up. Default unlimited. */
133
+ maxAttempts?: number;
134
+ }
135
+ interface SseConnectOptions {
136
+ fetch?: typeof fetch;
137
+ headers?: Record<string, string>;
138
+ credentials?: RequestCredentials;
139
+ /** Ends the stream (quietly) and stops reconnecting. */
140
+ signal?: AbortSignal;
141
+ /** Initial `Last-Event-ID`, e.g. persisted from an earlier session. */
142
+ lastEventId?: string;
143
+ /** Off by default. When on, a dropped connection is reopened with `Last-Event-ID`. */
144
+ reconnect?: boolean | SseReconnectOptions;
145
+ }
146
+ /**
147
+ * Opens an SSE stream with `fetch` (so headers and credentials work, unlike
148
+ * `EventSource`) and yields its events. An HTTP error or a response that is
149
+ * not `text/event-stream` throws and is never retried. With `reconnect`, a
150
+ * network failure or end of stream reopens the connection after the server's
151
+ * `retry:` delay, sending the last seen `id` as `Last-Event-ID`.
152
+ */
153
+ declare function connectSse(url: string, options?: SseConnectOptions): AsyncGenerator<SseEvent>;
154
+
155
+ type WebSocketEventType = 'open' | 'message' | 'close' | 'error';
156
+ type WebSocketListener = (event: unknown) => void;
157
+ interface WebSocketLike {
158
+ send(data: string): void;
159
+ close(): void;
160
+ readonly readyState: number;
161
+ /** Required only with `reconnect` (the native `WebSocket` has it). */
162
+ addEventListener?(type: WebSocketEventType, listener: WebSocketListener): void;
163
+ }
164
+ type WebSocketConstructor = new (url: string, protocols?: string | string[]) => WebSocketLike;
165
+ /** Reconnection policy: exponential backoff, reset once a socket opens. */
166
+ interface WebSocketReconnectOptions {
167
+ /** Consecutive reconnects without an `open` before giving up. Default unlimited. */
168
+ maxAttempts?: number;
169
+ /** First delay, doubled on each attempt. Default 500 ms. */
170
+ baseDelayMs?: number;
171
+ /** Delay ceiling. Default 30000 ms. */
172
+ maxDelayMs?: number;
173
+ }
174
+ interface WebSocketOptions {
175
+ protocols?: string | string[];
176
+ WebSocket?: WebSocketConstructor;
177
+ /** Off by default. When on, returns a {@link ReconnectingWebSocket}. */
178
+ reconnect?: boolean | WebSocketReconnectOptions;
179
+ }
180
+ /**
181
+ * Socket that reopens after an unexpected `close`. Listeners added here survive
182
+ * reconnects (they see every `close`, including the ones that trigger a retry);
183
+ * `close()` stops reconnecting for good. `send` goes to the current socket.
184
+ */
185
+ declare class ReconnectingWebSocket implements WebSocketLike {
186
+ #private;
187
+ constructor(open: () => WebSocketLike, options?: WebSocketReconnectOptions);
188
+ get readyState(): number;
189
+ send(data: string): void;
190
+ close(): void;
191
+ addEventListener(type: WebSocketEventType, listener: WebSocketListener): void;
192
+ removeEventListener(type: WebSocketEventType, listener: WebSocketListener): void;
193
+ }
194
+ declare function createWebSocket(url: string, options: WebSocketOptions & {
195
+ reconnect: true | WebSocketReconnectOptions;
196
+ }): ReconnectingWebSocket;
197
+ declare function createWebSocket(url: string, options?: WebSocketOptions): WebSocketLike;
198
+
199
+ /**
200
+ * CLNT-01 RPC proxy: `rpc.module.method(args)` → `client.request(method, path, args)`.
201
+ * `withMethod` switches the HTTP verb for a branch. Each property is one
202
+ * URL-encoded path segment; `.`/`..` throw a `TypeError`.
203
+ */
204
+ declare function createRpcProxy(client: TupikClient, prefix?: string, method?: HTTPMethod): unknown;
205
+
206
+ /** Route type union carried by a `TupikApp` (its phantom `~routes` member). */
207
+ type AppRoutes<TApp> = TApp extends {
208
+ readonly '~routes'?: infer TRoutes;
209
+ } ? Exclude<TRoutes, undefined> : never;
210
+ /** Standard Schema input type (`~standard.types.input`), falling back to the output type. */
211
+ type InferInput<TSchema extends StandardSchemaV1> = TSchema extends {
212
+ readonly '~standard': {
213
+ readonly types?: infer TTypes;
214
+ };
215
+ } ? NonNullable<TTypes> extends {
216
+ readonly input: infer TInput;
217
+ } ? TInput : InferOutput<TSchema> : InferOutput<TSchema>;
218
+ /**
219
+ * Routes keyed by `` `${method} ${path}` `` (e.g. `'GET /users/:id'`), built once per
220
+ * app type. Keys are unique: registering the same method + path twice already
221
+ * throws at runtime. The typed client itself uses {@link MethodRoutes} (one
222
+ * path-keyed map per method), which is cheaper to resolve than filtering these keys.
223
+ */
224
+ type RouteMap<TApp> = RouteMapOf<AppRoutes<TApp>>;
225
+ type RouteMapOf<TRoutes> = {
226
+ [TRoute in TRoutes as TRoute extends {
227
+ readonly method: infer TMethod extends string;
228
+ readonly path: infer TPath extends string;
229
+ } ? `${TMethod} ${TPath}` : never]: TRoute;
230
+ };
231
+ /**
232
+ * Routes of the union `TRoutes` registered for `TMethod`, keyed by path, e.g.
233
+ * `MethodRoutes<AppRoutes<typeof app>, 'GET'>['/users/:id']`. Built once per app
234
+ * type and method (lazily, only for methods the code calls): the typed call's
235
+ * path union is `keyof` this map and its route is a single indexed access, so
236
+ * the client's type cost stays linear in the number of routes.
237
+ */
238
+ type MethodRoutes<TRoutes, TMethod extends HTTPMethod> = {
239
+ [TRoute in TRoutes as TRoute extends {
240
+ readonly method: TMethod;
241
+ readonly path: infer TPath extends string;
242
+ } ? TPath : never]: TRoute;
243
+ };
244
+ /** `'/users/:id/*rest'` → `{ id: string; rest: string }`. */
245
+ type PathParams<TPath extends string> = TPath extends `${string}:${infer TName}/${infer TRest}` ? {
246
+ [K in TName]: string;
247
+ } & PathParams<`/${TRest}`> : TPath extends `${string}:${infer TName}` ? {
248
+ [K in TName]: string;
249
+ } : TPath extends `${string}*${infer TWildcard}` ? {
250
+ [K in TWildcard extends '' ? '*' : TWildcard]: string;
251
+ } : unknown;
252
+ type Simplify<T> = {
253
+ [K in keyof T]: T[K];
254
+ };
255
+ type SchemaOf<TRoute, TField extends 'body' | 'query' | 'params'> = TRoute extends {
256
+ readonly schema: infer TSchema;
257
+ } ? TSchema extends {
258
+ readonly [K in TField]: infer TFieldSchema extends StandardSchemaV1;
259
+ } ? TFieldSchema : never : never;
260
+ type ParamsPart<TRoute, TPath extends string> = [SchemaOf<TRoute, 'params'>] extends [never] ? unknown extends PathParams<TPath> ? {
261
+ params?: Record<string, string>;
262
+ } : {
263
+ params: Simplify<PathParams<TPath>>;
264
+ } : {
265
+ params: InferInput<SchemaOf<TRoute, 'params'>>;
266
+ };
267
+ type BodyPart<TRoute> = [SchemaOf<TRoute, 'body'>] extends [never] ? {
268
+ body?: unknown;
269
+ } : {
270
+ body: InferInput<SchemaOf<TRoute, 'body'>>;
271
+ };
272
+ type QueryPart<TRoute> = [SchemaOf<TRoute, 'query'>] extends [never] ? {
273
+ query?: Record<string, QueryValue>;
274
+ } : {
275
+ query: InferInput<SchemaOf<TRoute, 'query'>>;
276
+ };
277
+ /** Request options derived from the route contract, plus the per-call fetch controls. */
278
+ type TypedRequestOptions<TRoute, TPath extends string> = Simplify<ParamsPart<TRoute, TPath> & BodyPart<TRoute> & QueryPart<TRoute> & FetchControls & {
279
+ headers?: Record<string, string>;
280
+ }>;
281
+ type OptionsArgs<TRoute, TPath extends string> = {} extends TypedRequestOptions<TRoute, TPath> ? [options?: TypedRequestOptions<TRoute, TPath>] : [options: TypedRequestOptions<TRoute, TPath>];
282
+ type OutputOf<TRoute> = TRoute extends {
283
+ readonly output: infer TOutput;
284
+ } ? TOutput : never;
285
+ /** Codes the core answers when an access rule denies a request (`401`, `403`, `404`). */
286
+ type AccessProblemCode = 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND';
287
+ /** Codes of the `errors` a route declares (`RouteTypeInfo`'s fifth parameter). */
288
+ type RouteErrorCode<TRoute> = TRoute extends {
289
+ readonly errors: infer TErrors;
290
+ } ? TErrors extends {
291
+ readonly code: infer TCode extends string;
292
+ } ? TCode : never : never;
293
+ /**
294
+ * The route at `TPath` in a {@link MethodRoutes} map (one indexed access). The
295
+ * `` `${TPath}` `` wrapper is deliberate: a conditional checked directly on the
296
+ * type parameter (`TPath extends keyof TRoutes`) or on `TRoutes[TPath]` breaks
297
+ * non-call-site inference such as `ReturnType<typeof client.post>` (it falls
298
+ * back to `any`), while the template-literal form keeps the precise route.
299
+ */
300
+ type RouteAt<TRoutes, TPath extends string> = `${TPath}` extends keyof TRoutes ? TRoutes[`${TPath}`] : never;
301
+ type TypedMethod<TRoutes> = <TPath extends keyof TRoutes & string>(path: TPath, ...args: OptionsArgs<RouteAt<TRoutes, TPath>, TPath>) => Promise<ClientResult<OutputOf<RouteAt<TRoutes, TPath>>, RouteErrorCode<RouteAt<TRoutes, TPath>> | AccessProblemCode>>;
302
+ /**
303
+ * Client whose paths, inputs and response data are inferred from the app's
304
+ * registered routes. Build the app by chaining `register` so the route union
305
+ * accumulates: `const app = createApp().register(users)`.
306
+ */
307
+ interface TypedClient<TRoutes> {
308
+ get: TypedMethod<MethodRoutes<TRoutes, 'GET'>>;
309
+ post: TypedMethod<MethodRoutes<TRoutes, 'POST'>>;
310
+ put: TypedMethod<MethodRoutes<TRoutes, 'PUT'>>;
311
+ patch: TypedMethod<MethodRoutes<TRoutes, 'PATCH'>>;
312
+ delete: TypedMethod<MethodRoutes<TRoutes, 'DELETE'>>;
313
+ head: TypedMethod<MethodRoutes<TRoutes, 'HEAD'>>;
314
+ options: TypedMethod<MethodRoutes<TRoutes, 'OPTIONS'>>;
315
+ /** Untyped escape hatch, same as `TupikClient.request`. */
316
+ request<TData = unknown>(method: HTTPMethod, path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
317
+ }
318
+ /**
319
+ * Creates a client typed end-to-end from `typeof app`. Paths, request options
320
+ * and response data are resolved through {@link MethodRoutes} (one path-keyed
321
+ * map per method), so each call costs a key lookup rather than a scan of every route.
322
+ */
323
+ declare function createTypedClient<TApp>(options: ClientOptions): TypedClient<AppRoutes<TApp>>;
324
+
325
+ export { ClientRequestError, ReconnectingWebSocket, SSE_MAX_EVENT_SIZE, SSE_MAX_LINE_LENGTH, SseOverflowError, TupikClient, connectSse, createClient, createRpcProxy, createTypedClient, createWebSocket, streamSse };
326
+ export type { AccessProblemCode, AppRoutes, ClientFailureKind, ClientOptions, ClientResult, FetchControls, InferInput, MethodRoutes, PathParams, Problem, QueryValue, RequestOptions, RetryOptions, RouteErrorCode, RouteMap, SseConnectOptions, SseControl, SseEvent, SseReconnectOptions, SseStreamOptions, TypedClient, TypedRequestOptions, WebSocketConstructor, WebSocketEventType, WebSocketLike, WebSocketListener, WebSocketOptions, WebSocketReconnectOptions };
@@ -0,0 +1,326 @@
1
+ import { HTTPMethod, StandardSchemaV1, InferOutput } from '@tupik/core';
2
+
3
+ /** Retry policy for idempotent methods (GET, HEAD, PUT, DELETE, OPTIONS). Off unless set. */
4
+ interface RetryOptions {
5
+ /** Extra attempts after the first request. */
6
+ attempts: number;
7
+ /** First backoff delay; doubles on every retry. Default 100 ms. */
8
+ baseDelayMs?: number;
9
+ /** Backoff ceiling; a `Retry-After` longer than this ends the retries. Default 5000 ms. */
10
+ maxDelayMs?: number;
11
+ /** Statuses worth retrying. Default 408, 425, 429, 500, 502, 503, 504. */
12
+ statuses?: readonly number[];
13
+ }
14
+ /** Fetch controls set on the client (defaults) and per call (overrides; signals combine). */
15
+ interface FetchControls {
16
+ signal?: AbortSignal;
17
+ /** Milliseconds for the whole call, retries included. */
18
+ timeout?: number;
19
+ credentials?: RequestCredentials;
20
+ retry?: RetryOptions;
21
+ }
22
+ interface ClientOptions extends FetchControls {
23
+ baseUrl: string;
24
+ headers?: Record<string, string> | (() => Record<string, string>);
25
+ fetch?: typeof fetch;
26
+ }
27
+ /** Query value: arrays repeat the key (`?tag=a&tag=b`), `undefined` is omitted. */
28
+ type QueryValue = string | number | boolean | undefined | readonly (string | number | boolean)[];
29
+ interface RequestOptions extends FetchControls {
30
+ params?: Record<string, string>;
31
+ query?: Record<string, QueryValue>;
32
+ headers?: Record<string, string>;
33
+ body?: unknown;
34
+ }
35
+ /**
36
+ * RFC 9457 problem details (`application/problem+json`), extension members
37
+ * included. `code` is the Tupik error code (`ctx.fail`, access denials);
38
+ * validation problems carry none.
39
+ */
40
+ interface Problem<TCode extends string = string> {
41
+ type?: string;
42
+ title?: string;
43
+ status?: number;
44
+ detail?: string;
45
+ instance?: string;
46
+ code?: TCode;
47
+ [extension: string]: unknown;
48
+ }
49
+ /** Why a request produced no response. */
50
+ type ClientFailureKind = 'network' | 'timeout' | 'abort';
51
+ /** Error carried by a result that has no response (network failure, timeout or abort). */
52
+ declare class ClientRequestError extends Error {
53
+ readonly kind: ClientFailureKind;
54
+ constructor(kind: ClientFailureKind, cause: unknown);
55
+ }
56
+ /**
57
+ * Never rejects for HTTP, network, timeout or abort failures: branch on `ok`,
58
+ * then `kind`. `TErrorCode` types `error.code` of a problem (the typed client
59
+ * fills it from the route's `errors`).
60
+ */
61
+ type ClientResult<TData, TErrorCode extends string = string> = {
62
+ ok: true;
63
+ data: TData;
64
+ response: Response;
65
+ } | {
66
+ ok: false;
67
+ kind: 'problem';
68
+ error: Problem<TErrorCode>;
69
+ response: Response;
70
+ } | {
71
+ ok: false;
72
+ kind: 'http';
73
+ error: unknown;
74
+ response: Response;
75
+ } | {
76
+ ok: false;
77
+ kind: ClientFailureKind;
78
+ error: ClientRequestError;
79
+ response: undefined;
80
+ };
81
+ declare class TupikClient {
82
+ #private;
83
+ constructor(options: ClientOptions);
84
+ request<TData = unknown>(method: HTTPMethod, path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
85
+ get<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
86
+ post<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
87
+ put<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
88
+ patch<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
89
+ delete<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
90
+ head<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
91
+ options<TData = unknown>(path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
92
+ }
93
+ declare function createClient(options: ClientOptions): TupikClient;
94
+
95
+ interface SseEvent {
96
+ event: string;
97
+ data: string;
98
+ id?: string;
99
+ retry?: number;
100
+ }
101
+ /** Maximum bytes retained for one unterminated line; a longer line is rejected. */
102
+ declare const SSE_MAX_LINE_LENGTH: number;
103
+ /** Maximum accumulated bytes for one event's fields (e.g. multi-line `data`); a larger event is rejected. */
104
+ declare const SSE_MAX_EVENT_SIZE: number;
105
+ /** Thrown when a line or event exceeds {@link SSE_MAX_LINE_LENGTH}/{@link SSE_MAX_EVENT_SIZE}. */
106
+ declare class SseOverflowError extends Error {
107
+ constructor(message: string);
108
+ }
109
+ /** `id`/`retry` of a frame without `data`: no event is dispatched, but the WHATWG spec still applies them. */
110
+ interface SseControl {
111
+ id?: string;
112
+ retry?: number;
113
+ }
114
+ interface SseStreamOptions {
115
+ /** Called for a frame that carries `id` or `retry` but no `data` (e.g. `retry: 3000` sent on connect). */
116
+ onControl?: (control: SseControl) => void;
117
+ }
118
+ /**
119
+ * Parses a Server-Sent Events byte stream. Buffering is bounded: a single
120
+ * line longer than {@link SSE_MAX_LINE_LENGTH}, or an event whose accumulated
121
+ * fields exceed {@link SSE_MAX_EVENT_SIZE}, rejects with
122
+ * {@link SseOverflowError} and the underlying reader is cancelled; memory
123
+ * never grows unbounded. As the WHATWG SSE spec requires, an event whose
124
+ * terminating blank line never arrives is discarded at end-of-stream, and a
125
+ * frame with `id`/`retry` but no `data` yields nothing but goes to `onControl`.
126
+ */
127
+ declare function streamSse(body: ReadableStream<Uint8Array>, options?: SseStreamOptions): AsyncGenerator<SseEvent>;
128
+ /** Reconnection policy for {@link connectSse}. */
129
+ interface SseReconnectOptions {
130
+ /** Delay before reconnecting until the server sends `retry:` (with or without data). Default 3000 ms. */
131
+ delayMs?: number;
132
+ /** Consecutive reconnects without a received event before giving up. Default unlimited. */
133
+ maxAttempts?: number;
134
+ }
135
+ interface SseConnectOptions {
136
+ fetch?: typeof fetch;
137
+ headers?: Record<string, string>;
138
+ credentials?: RequestCredentials;
139
+ /** Ends the stream (quietly) and stops reconnecting. */
140
+ signal?: AbortSignal;
141
+ /** Initial `Last-Event-ID`, e.g. persisted from an earlier session. */
142
+ lastEventId?: string;
143
+ /** Off by default. When on, a dropped connection is reopened with `Last-Event-ID`. */
144
+ reconnect?: boolean | SseReconnectOptions;
145
+ }
146
+ /**
147
+ * Opens an SSE stream with `fetch` (so headers and credentials work, unlike
148
+ * `EventSource`) and yields its events. An HTTP error or a response that is
149
+ * not `text/event-stream` throws and is never retried. With `reconnect`, a
150
+ * network failure or end of stream reopens the connection after the server's
151
+ * `retry:` delay, sending the last seen `id` as `Last-Event-ID`.
152
+ */
153
+ declare function connectSse(url: string, options?: SseConnectOptions): AsyncGenerator<SseEvent>;
154
+
155
+ type WebSocketEventType = 'open' | 'message' | 'close' | 'error';
156
+ type WebSocketListener = (event: unknown) => void;
157
+ interface WebSocketLike {
158
+ send(data: string): void;
159
+ close(): void;
160
+ readonly readyState: number;
161
+ /** Required only with `reconnect` (the native `WebSocket` has it). */
162
+ addEventListener?(type: WebSocketEventType, listener: WebSocketListener): void;
163
+ }
164
+ type WebSocketConstructor = new (url: string, protocols?: string | string[]) => WebSocketLike;
165
+ /** Reconnection policy: exponential backoff, reset once a socket opens. */
166
+ interface WebSocketReconnectOptions {
167
+ /** Consecutive reconnects without an `open` before giving up. Default unlimited. */
168
+ maxAttempts?: number;
169
+ /** First delay, doubled on each attempt. Default 500 ms. */
170
+ baseDelayMs?: number;
171
+ /** Delay ceiling. Default 30000 ms. */
172
+ maxDelayMs?: number;
173
+ }
174
+ interface WebSocketOptions {
175
+ protocols?: string | string[];
176
+ WebSocket?: WebSocketConstructor;
177
+ /** Off by default. When on, returns a {@link ReconnectingWebSocket}. */
178
+ reconnect?: boolean | WebSocketReconnectOptions;
179
+ }
180
+ /**
181
+ * Socket that reopens after an unexpected `close`. Listeners added here survive
182
+ * reconnects (they see every `close`, including the ones that trigger a retry);
183
+ * `close()` stops reconnecting for good. `send` goes to the current socket.
184
+ */
185
+ declare class ReconnectingWebSocket implements WebSocketLike {
186
+ #private;
187
+ constructor(open: () => WebSocketLike, options?: WebSocketReconnectOptions);
188
+ get readyState(): number;
189
+ send(data: string): void;
190
+ close(): void;
191
+ addEventListener(type: WebSocketEventType, listener: WebSocketListener): void;
192
+ removeEventListener(type: WebSocketEventType, listener: WebSocketListener): void;
193
+ }
194
+ declare function createWebSocket(url: string, options: WebSocketOptions & {
195
+ reconnect: true | WebSocketReconnectOptions;
196
+ }): ReconnectingWebSocket;
197
+ declare function createWebSocket(url: string, options?: WebSocketOptions): WebSocketLike;
198
+
199
+ /**
200
+ * CLNT-01 RPC proxy: `rpc.module.method(args)` → `client.request(method, path, args)`.
201
+ * `withMethod` switches the HTTP verb for a branch. Each property is one
202
+ * URL-encoded path segment; `.`/`..` throw a `TypeError`.
203
+ */
204
+ declare function createRpcProxy(client: TupikClient, prefix?: string, method?: HTTPMethod): unknown;
205
+
206
+ /** Route type union carried by a `TupikApp` (its phantom `~routes` member). */
207
+ type AppRoutes<TApp> = TApp extends {
208
+ readonly '~routes'?: infer TRoutes;
209
+ } ? Exclude<TRoutes, undefined> : never;
210
+ /** Standard Schema input type (`~standard.types.input`), falling back to the output type. */
211
+ type InferInput<TSchema extends StandardSchemaV1> = TSchema extends {
212
+ readonly '~standard': {
213
+ readonly types?: infer TTypes;
214
+ };
215
+ } ? NonNullable<TTypes> extends {
216
+ readonly input: infer TInput;
217
+ } ? TInput : InferOutput<TSchema> : InferOutput<TSchema>;
218
+ /**
219
+ * Routes keyed by `` `${method} ${path}` `` (e.g. `'GET /users/:id'`), built once per
220
+ * app type. Keys are unique: registering the same method + path twice already
221
+ * throws at runtime. The typed client itself uses {@link MethodRoutes} (one
222
+ * path-keyed map per method), which is cheaper to resolve than filtering these keys.
223
+ */
224
+ type RouteMap<TApp> = RouteMapOf<AppRoutes<TApp>>;
225
+ type RouteMapOf<TRoutes> = {
226
+ [TRoute in TRoutes as TRoute extends {
227
+ readonly method: infer TMethod extends string;
228
+ readonly path: infer TPath extends string;
229
+ } ? `${TMethod} ${TPath}` : never]: TRoute;
230
+ };
231
+ /**
232
+ * Routes of the union `TRoutes` registered for `TMethod`, keyed by path, e.g.
233
+ * `MethodRoutes<AppRoutes<typeof app>, 'GET'>['/users/:id']`. Built once per app
234
+ * type and method (lazily, only for methods the code calls): the typed call's
235
+ * path union is `keyof` this map and its route is a single indexed access, so
236
+ * the client's type cost stays linear in the number of routes.
237
+ */
238
+ type MethodRoutes<TRoutes, TMethod extends HTTPMethod> = {
239
+ [TRoute in TRoutes as TRoute extends {
240
+ readonly method: TMethod;
241
+ readonly path: infer TPath extends string;
242
+ } ? TPath : never]: TRoute;
243
+ };
244
+ /** `'/users/:id/*rest'` → `{ id: string; rest: string }`. */
245
+ type PathParams<TPath extends string> = TPath extends `${string}:${infer TName}/${infer TRest}` ? {
246
+ [K in TName]: string;
247
+ } & PathParams<`/${TRest}`> : TPath extends `${string}:${infer TName}` ? {
248
+ [K in TName]: string;
249
+ } : TPath extends `${string}*${infer TWildcard}` ? {
250
+ [K in TWildcard extends '' ? '*' : TWildcard]: string;
251
+ } : unknown;
252
+ type Simplify<T> = {
253
+ [K in keyof T]: T[K];
254
+ };
255
+ type SchemaOf<TRoute, TField extends 'body' | 'query' | 'params'> = TRoute extends {
256
+ readonly schema: infer TSchema;
257
+ } ? TSchema extends {
258
+ readonly [K in TField]: infer TFieldSchema extends StandardSchemaV1;
259
+ } ? TFieldSchema : never : never;
260
+ type ParamsPart<TRoute, TPath extends string> = [SchemaOf<TRoute, 'params'>] extends [never] ? unknown extends PathParams<TPath> ? {
261
+ params?: Record<string, string>;
262
+ } : {
263
+ params: Simplify<PathParams<TPath>>;
264
+ } : {
265
+ params: InferInput<SchemaOf<TRoute, 'params'>>;
266
+ };
267
+ type BodyPart<TRoute> = [SchemaOf<TRoute, 'body'>] extends [never] ? {
268
+ body?: unknown;
269
+ } : {
270
+ body: InferInput<SchemaOf<TRoute, 'body'>>;
271
+ };
272
+ type QueryPart<TRoute> = [SchemaOf<TRoute, 'query'>] extends [never] ? {
273
+ query?: Record<string, QueryValue>;
274
+ } : {
275
+ query: InferInput<SchemaOf<TRoute, 'query'>>;
276
+ };
277
+ /** Request options derived from the route contract, plus the per-call fetch controls. */
278
+ type TypedRequestOptions<TRoute, TPath extends string> = Simplify<ParamsPart<TRoute, TPath> & BodyPart<TRoute> & QueryPart<TRoute> & FetchControls & {
279
+ headers?: Record<string, string>;
280
+ }>;
281
+ type OptionsArgs<TRoute, TPath extends string> = {} extends TypedRequestOptions<TRoute, TPath> ? [options?: TypedRequestOptions<TRoute, TPath>] : [options: TypedRequestOptions<TRoute, TPath>];
282
+ type OutputOf<TRoute> = TRoute extends {
283
+ readonly output: infer TOutput;
284
+ } ? TOutput : never;
285
+ /** Codes the core answers when an access rule denies a request (`401`, `403`, `404`). */
286
+ type AccessProblemCode = 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND';
287
+ /** Codes of the `errors` a route declares (`RouteTypeInfo`'s fifth parameter). */
288
+ type RouteErrorCode<TRoute> = TRoute extends {
289
+ readonly errors: infer TErrors;
290
+ } ? TErrors extends {
291
+ readonly code: infer TCode extends string;
292
+ } ? TCode : never : never;
293
+ /**
294
+ * The route at `TPath` in a {@link MethodRoutes} map (one indexed access). The
295
+ * `` `${TPath}` `` wrapper is deliberate: a conditional checked directly on the
296
+ * type parameter (`TPath extends keyof TRoutes`) or on `TRoutes[TPath]` breaks
297
+ * non-call-site inference such as `ReturnType<typeof client.post>` (it falls
298
+ * back to `any`), while the template-literal form keeps the precise route.
299
+ */
300
+ type RouteAt<TRoutes, TPath extends string> = `${TPath}` extends keyof TRoutes ? TRoutes[`${TPath}`] : never;
301
+ type TypedMethod<TRoutes> = <TPath extends keyof TRoutes & string>(path: TPath, ...args: OptionsArgs<RouteAt<TRoutes, TPath>, TPath>) => Promise<ClientResult<OutputOf<RouteAt<TRoutes, TPath>>, RouteErrorCode<RouteAt<TRoutes, TPath>> | AccessProblemCode>>;
302
+ /**
303
+ * Client whose paths, inputs and response data are inferred from the app's
304
+ * registered routes. Build the app by chaining `register` so the route union
305
+ * accumulates: `const app = createApp().register(users)`.
306
+ */
307
+ interface TypedClient<TRoutes> {
308
+ get: TypedMethod<MethodRoutes<TRoutes, 'GET'>>;
309
+ post: TypedMethod<MethodRoutes<TRoutes, 'POST'>>;
310
+ put: TypedMethod<MethodRoutes<TRoutes, 'PUT'>>;
311
+ patch: TypedMethod<MethodRoutes<TRoutes, 'PATCH'>>;
312
+ delete: TypedMethod<MethodRoutes<TRoutes, 'DELETE'>>;
313
+ head: TypedMethod<MethodRoutes<TRoutes, 'HEAD'>>;
314
+ options: TypedMethod<MethodRoutes<TRoutes, 'OPTIONS'>>;
315
+ /** Untyped escape hatch, same as `TupikClient.request`. */
316
+ request<TData = unknown>(method: HTTPMethod, path: string, options?: RequestOptions): Promise<ClientResult<TData>>;
317
+ }
318
+ /**
319
+ * Creates a client typed end-to-end from `typeof app`. Paths, request options
320
+ * and response data are resolved through {@link MethodRoutes} (one path-keyed
321
+ * map per method), so each call costs a key lookup rather than a scan of every route.
322
+ */
323
+ declare function createTypedClient<TApp>(options: ClientOptions): TypedClient<AppRoutes<TApp>>;
324
+
325
+ export { ClientRequestError, ReconnectingWebSocket, SSE_MAX_EVENT_SIZE, SSE_MAX_LINE_LENGTH, SseOverflowError, TupikClient, connectSse, createClient, createRpcProxy, createTypedClient, createWebSocket, streamSse };
326
+ export type { AccessProblemCode, AppRoutes, ClientFailureKind, ClientOptions, ClientResult, FetchControls, InferInput, MethodRoutes, PathParams, Problem, QueryValue, RequestOptions, RetryOptions, RouteErrorCode, RouteMap, SseConnectOptions, SseControl, SseEvent, SseReconnectOptions, SseStreamOptions, TypedClient, TypedRequestOptions, WebSocketConstructor, WebSocketEventType, WebSocketLike, WebSocketListener, WebSocketOptions, WebSocketReconnectOptions };
package/dist/index.mjs ADDED
@@ -0,0 +1,438 @@
1
+ function encodeSegment(value) {
2
+ if (value === "." || value === "..") throw new TypeError("Invalid path segment: " + JSON.stringify(value));
3
+ return encodeURIComponent(value);
4
+ }
5
+
6
+ class ClientRequestError extends Error {
7
+ kind;
8
+ constructor(kind, cause) {
9
+ super("Request failed: " + kind, { cause });
10
+ this.name = "ClientRequestError";
11
+ this.kind = kind;
12
+ }
13
+ }
14
+ const CONTENT_TYPE = "application/json; charset=utf-8";
15
+ const IDEMPOTENT = /* @__PURE__ */ new Set(["GET", "HEAD", "PUT", "DELETE", "OPTIONS"]);
16
+ const RETRY_STATUSES = [408, 425, 429, 500, 502, 503, 504];
17
+ function joinUrl(baseUrl, path) {
18
+ if (baseUrl === "") return path;
19
+ const trimmedBase = baseUrl.endsWith("/") ? baseUrl.slice(0, -1) : baseUrl;
20
+ return trimmedBase + (path.startsWith("/") ? path : "/" + path);
21
+ }
22
+ function interpolate(path, params) {
23
+ if (params === void 0) return path;
24
+ return path.replace(/:([A-Za-z0-9_]+)/g, (_match, name) => {
25
+ const value = params[name];
26
+ if (value === void 0) throw new Error("Missing route param: " + name);
27
+ return encodeSegment(value);
28
+ });
29
+ }
30
+ function applyQuery(url, query) {
31
+ if (query === void 0) return url;
32
+ const search = new URLSearchParams();
33
+ for (const key of Object.keys(query)) {
34
+ const value = query[key];
35
+ if (value === void 0) continue;
36
+ if (Array.isArray(value)) for (const item of value) search.append(key, String(item));
37
+ else search.append(key, String(value));
38
+ }
39
+ const qs = search.toString();
40
+ if (qs === "") return url;
41
+ return url + (url.includes("?") ? "&" : "?") + qs;
42
+ }
43
+ function resolveHeaders(base) {
44
+ if (base === void 0) return {};
45
+ return typeof base === "function" ? base() : base;
46
+ }
47
+ async function parseBody(response) {
48
+ const text = await response.text();
49
+ if (text === "") return void 0;
50
+ const contentType = response.headers.get("content-type") ?? "";
51
+ if (contentType.includes("json")) {
52
+ try {
53
+ return JSON.parse(text);
54
+ } catch {
55
+ return text;
56
+ }
57
+ }
58
+ return text;
59
+ }
60
+ async function toResult(response) {
61
+ const data = await parseBody(response);
62
+ if (response.ok) return { ok: true, data, response };
63
+ const isProblem = (response.headers.get("content-type") ?? "").includes("application/problem+json");
64
+ if (isProblem && typeof data === "object" && data !== null && !Array.isArray(data)) {
65
+ return { ok: false, kind: "problem", error: data, response };
66
+ }
67
+ return { ok: false, kind: "http", error: data, response };
68
+ }
69
+ function linkSignals(signals, timeout) {
70
+ const controller = new AbortController();
71
+ const cleanups = [];
72
+ const call = {
73
+ signal: controller.signal,
74
+ timedOut: false,
75
+ dispose: () => {
76
+ for (const cleanup of cleanups) cleanup();
77
+ }
78
+ };
79
+ for (const signal of signals) {
80
+ if (signal === void 0) continue;
81
+ if (signal.aborted) {
82
+ controller.abort(signal.reason);
83
+ continue;
84
+ }
85
+ const onAbort = () => controller.abort(signal.reason);
86
+ signal.addEventListener("abort", onAbort, { once: true });
87
+ cleanups.push(() => signal.removeEventListener("abort", onAbort));
88
+ }
89
+ if (timeout !== void 0 && !controller.signal.aborted) {
90
+ const timer = setTimeout(() => {
91
+ call.timedOut = true;
92
+ controller.abort(new DOMException("The operation timed out.", "TimeoutError"));
93
+ }, timeout);
94
+ cleanups.push(() => clearTimeout(timer));
95
+ }
96
+ return call;
97
+ }
98
+ function failure(call, cause) {
99
+ const kind = call.timedOut ? "timeout" : call.signal.aborted ? "abort" : "network";
100
+ return { ok: false, kind, error: new ClientRequestError(kind, cause), response: void 0 };
101
+ }
102
+ function retryAfterMs(value) {
103
+ if (value === null || value.trim() === "") return void 0;
104
+ const seconds = Number(value);
105
+ if (Number.isFinite(seconds)) return Math.max(0, seconds * 1e3);
106
+ const date = Date.parse(value);
107
+ return Number.isNaN(date) ? void 0 : Math.max(0, date - Date.now());
108
+ }
109
+ function retryDelay(retry, attempt, response) {
110
+ const maxDelay = retry.maxDelayMs ?? 5e3;
111
+ const backoff = Math.min((retry.baseDelayMs ?? 100) * 2 ** attempt, maxDelay);
112
+ if (response === void 0) return backoff;
113
+ if (!(retry.statuses ?? RETRY_STATUSES).includes(response.status)) return void 0;
114
+ const after = retryAfterMs(response.headers.get("retry-after"));
115
+ if (after === void 0) return backoff;
116
+ return after > maxDelay ? void 0 : after;
117
+ }
118
+ function sleep(ms, signal) {
119
+ return new Promise((resolve, reject) => {
120
+ if (signal.aborted) {
121
+ reject(signal.reason);
122
+ return;
123
+ }
124
+ const onAbort = () => {
125
+ clearTimeout(timer);
126
+ reject(signal.reason);
127
+ };
128
+ const timer = setTimeout(() => {
129
+ signal.removeEventListener("abort", onAbort);
130
+ resolve();
131
+ }, ms);
132
+ signal.addEventListener("abort", onAbort, { once: true });
133
+ });
134
+ }
135
+ class TupikClient {
136
+ #options;
137
+ #fetch;
138
+ constructor(options) {
139
+ this.#options = options;
140
+ this.#fetch = options.fetch ?? globalThis.fetch;
141
+ }
142
+ async request(method, path, options) {
143
+ const url = applyQuery(joinUrl(this.#options.baseUrl, interpolate(path, options?.params)), options?.query);
144
+ const headers = new Headers(resolveHeaders(this.#options.headers));
145
+ if (options?.headers !== void 0) {
146
+ for (const key of Object.keys(options.headers)) headers.set(key, options.headers[key]);
147
+ }
148
+ const call = linkSignals([this.#options.signal, options?.signal], options?.timeout ?? this.#options.timeout);
149
+ const init = { method, headers, signal: call.signal };
150
+ if (options?.body !== void 0 && method !== "GET" && method !== "HEAD") {
151
+ init.body = JSON.stringify(options.body);
152
+ if (!headers.has("content-type")) headers.set("content-type", CONTENT_TYPE);
153
+ }
154
+ const credentials = options?.credentials ?? this.#options.credentials;
155
+ if (credentials !== void 0) init.credentials = credentials;
156
+ const retry = IDEMPOTENT.has(method) ? options?.retry ?? this.#options.retry : void 0;
157
+ try {
158
+ for (let attempt = 0; ; attempt += 1) {
159
+ let response;
160
+ let error;
161
+ try {
162
+ response = await this.#fetch(new Request(url, init));
163
+ } catch (caught) {
164
+ error = caught;
165
+ }
166
+ const delay = retry !== void 0 && attempt < retry.attempts && !call.signal.aborted ? retryDelay(retry, attempt, response) : void 0;
167
+ if (delay === void 0) return response === void 0 ? failure(call, error) : await toResult(response);
168
+ await response?.body?.cancel();
169
+ await sleep(delay, call.signal);
170
+ }
171
+ } catch (error) {
172
+ return failure(call, error);
173
+ } finally {
174
+ call.dispose();
175
+ }
176
+ }
177
+ get(path, options) {
178
+ return this.request("GET", path, options);
179
+ }
180
+ post(path, options) {
181
+ return this.request("POST", path, options);
182
+ }
183
+ put(path, options) {
184
+ return this.request("PUT", path, options);
185
+ }
186
+ patch(path, options) {
187
+ return this.request("PATCH", path, options);
188
+ }
189
+ delete(path, options) {
190
+ return this.request("DELETE", path, options);
191
+ }
192
+ head(path, options) {
193
+ return this.request("HEAD", path, options);
194
+ }
195
+ options(path, options) {
196
+ return this.request("OPTIONS", path, options);
197
+ }
198
+ }
199
+ function createClient(options) {
200
+ return new TupikClient(options);
201
+ }
202
+
203
+ const SSE_MAX_LINE_LENGTH = 1024 * 1024;
204
+ const SSE_MAX_EVENT_SIZE = 1024 * 1024;
205
+ class SseOverflowError extends Error {
206
+ constructor(message) {
207
+ super(message);
208
+ this.name = "SseOverflowError";
209
+ }
210
+ }
211
+ function dispatch(pending) {
212
+ if (pending.data.length === 0) return void 0;
213
+ const event = { event: pending.event === "" ? "message" : pending.event, data: pending.data.join("\n") };
214
+ if (pending.id !== void 0) event.id = pending.id;
215
+ if (pending.retry !== void 0) event.retry = pending.retry;
216
+ return event;
217
+ }
218
+ function handleLine(line, pending) {
219
+ if (line === "") return;
220
+ if (line.startsWith(":")) return;
221
+ const colon = line.indexOf(":");
222
+ const field = colon === -1 ? line : line.slice(0, colon);
223
+ let value = colon === -1 ? "" : line.slice(colon + 1);
224
+ if (value.startsWith(" ")) value = value.slice(1);
225
+ if (field === "event") pending.event = value;
226
+ else if (field === "data") pending.data.push(value);
227
+ else if (field === "id") pending.id = value;
228
+ else if (field === "retry") {
229
+ const n = Number(value);
230
+ if (!Number.isNaN(n)) pending.retry = n;
231
+ }
232
+ }
233
+ function control(pending) {
234
+ if (pending.data.length > 0 || pending.id === void 0 && pending.retry === void 0) return void 0;
235
+ const fields = {};
236
+ if (pending.id !== void 0) fields.id = pending.id;
237
+ if (pending.retry !== void 0) fields.retry = pending.retry;
238
+ return fields;
239
+ }
240
+ function reset(pending) {
241
+ pending.event = "";
242
+ pending.data = [];
243
+ pending.id = void 0;
244
+ pending.retry = void 0;
245
+ pending.size = 0;
246
+ }
247
+ async function* streamSse(body, options = {}) {
248
+ const decoder = new TextDecoder();
249
+ const pending = { event: "", data: [], id: void 0, retry: void 0, size: 0 };
250
+ let buffer = "";
251
+ const reader = body.getReader();
252
+ try {
253
+ while (true) {
254
+ const { done, value } = await reader.read();
255
+ if (done) break;
256
+ buffer += decoder.decode(value, { stream: true });
257
+ if (buffer.indexOf("\n") === -1 && buffer.length > SSE_MAX_LINE_LENGTH) {
258
+ throw new SseOverflowError("SSE line exceeds " + SSE_MAX_LINE_LENGTH + " bytes");
259
+ }
260
+ let newlineIndex = buffer.indexOf("\n");
261
+ while (newlineIndex !== -1) {
262
+ let line = buffer.slice(0, newlineIndex);
263
+ if (line.endsWith("\r")) line = line.slice(0, -1);
264
+ buffer = buffer.slice(newlineIndex + 1);
265
+ if (line.length > SSE_MAX_LINE_LENGTH) throw new SseOverflowError("SSE line exceeds " + SSE_MAX_LINE_LENGTH + " bytes");
266
+ if (line === "") {
267
+ const event = dispatch(pending);
268
+ const fields = control(pending);
269
+ if (fields !== void 0) options.onControl?.(fields);
270
+ reset(pending);
271
+ if (event !== void 0) yield event;
272
+ } else {
273
+ handleLine(line, pending);
274
+ pending.size += line.length;
275
+ if (pending.size > SSE_MAX_EVENT_SIZE) throw new SseOverflowError("SSE event exceeds " + SSE_MAX_EVENT_SIZE + " bytes");
276
+ }
277
+ newlineIndex = buffer.indexOf("\n");
278
+ }
279
+ if (buffer.indexOf("\n") === -1 && buffer.length > SSE_MAX_LINE_LENGTH) {
280
+ throw new SseOverflowError("SSE line exceeds " + SSE_MAX_LINE_LENGTH + " bytes");
281
+ }
282
+ }
283
+ } finally {
284
+ reader.cancel().catch(() => void 0);
285
+ reader.releaseLock();
286
+ }
287
+ }
288
+ function waitFor(ms, signal) {
289
+ return new Promise((resolve) => {
290
+ const done = () => {
291
+ clearTimeout(timer);
292
+ signal?.removeEventListener("abort", done);
293
+ resolve();
294
+ };
295
+ const timer = setTimeout(done, ms);
296
+ signal?.addEventListener("abort", done, { once: true });
297
+ });
298
+ }
299
+ async function* connectSse(url, options = {}) {
300
+ const fetchImpl = options.fetch ?? globalThis.fetch;
301
+ const reconnect = options.reconnect === true ? {} : options.reconnect === false ? void 0 : options.reconnect;
302
+ const maxAttempts = reconnect?.maxAttempts ?? Infinity;
303
+ const signal = options.signal;
304
+ const aborted = () => signal?.aborted === true;
305
+ let delay = reconnect?.delayMs ?? 3e3;
306
+ let lastEventId = options.lastEventId;
307
+ let attempts = 0;
308
+ while (!aborted()) {
309
+ const headers = new Headers(options.headers);
310
+ headers.set("accept", "text/event-stream");
311
+ if (lastEventId !== void 0) headers.set("last-event-id", lastEventId);
312
+ const init = { headers };
313
+ if (signal !== void 0) init.signal = signal;
314
+ if (options.credentials !== void 0) init.credentials = options.credentials;
315
+ let lastError;
316
+ try {
317
+ const response = await fetchImpl(new Request(url, init));
318
+ if (!response.ok) throw new Error("SSE request failed with status " + response.status);
319
+ if (!(response.headers.get("content-type") ?? "").includes("text/event-stream") || response.body === null) {
320
+ throw new Error("SSE response is not text/event-stream");
321
+ }
322
+ const apply = (fields) => {
323
+ if (fields.id !== void 0) lastEventId = fields.id;
324
+ if (fields.retry !== void 0) delay = fields.retry;
325
+ };
326
+ try {
327
+ for await (const event of streamSse(response.body, { onControl: apply })) {
328
+ attempts = 0;
329
+ apply(event);
330
+ yield event;
331
+ }
332
+ } catch (error) {
333
+ if (error instanceof SseOverflowError) throw error;
334
+ lastError = error;
335
+ }
336
+ } catch (error) {
337
+ if (aborted()) return;
338
+ if (!(error instanceof TypeError) || reconnect === void 0) throw error;
339
+ lastError = error;
340
+ }
341
+ if (aborted() || reconnect === void 0) {
342
+ if (lastError !== void 0 && !aborted()) throw lastError;
343
+ return;
344
+ }
345
+ attempts += 1;
346
+ if (attempts > maxAttempts) throw lastError ?? new Error("SSE reconnect attempts exhausted");
347
+ await waitFor(delay, signal);
348
+ }
349
+ }
350
+
351
+ const EVENT_TYPES = ["open", "message", "close", "error"];
352
+ class ReconnectingWebSocket {
353
+ #open;
354
+ #options;
355
+ #listeners = /* @__PURE__ */ new Map();
356
+ #socket;
357
+ #attempts = 0;
358
+ #closed = false;
359
+ #timer;
360
+ constructor(open, options = {}) {
361
+ this.#open = open;
362
+ this.#options = options;
363
+ this.#socket = this.#connect();
364
+ }
365
+ get readyState() {
366
+ return this.#socket.readyState;
367
+ }
368
+ send(data) {
369
+ this.#socket.send(data);
370
+ }
371
+ close() {
372
+ this.#closed = true;
373
+ clearTimeout(this.#timer);
374
+ this.#socket.close();
375
+ }
376
+ addEventListener(type, listener) {
377
+ const set = this.#listeners.get(type) ?? /* @__PURE__ */ new Set();
378
+ set.add(listener);
379
+ this.#listeners.set(type, set);
380
+ }
381
+ removeEventListener(type, listener) {
382
+ this.#listeners.get(type)?.delete(listener);
383
+ }
384
+ #connect() {
385
+ const socket = this.#open();
386
+ if (socket.addEventListener === void 0) throw new TypeError("WebSocket reconnect needs addEventListener");
387
+ for (const type of EVENT_TYPES) {
388
+ socket.addEventListener(type, (event) => {
389
+ if (type === "open") this.#attempts = 0;
390
+ for (const listener of this.#listeners.get(type) ?? []) listener(event);
391
+ if (type === "close") this.#schedule();
392
+ });
393
+ }
394
+ return socket;
395
+ }
396
+ #schedule() {
397
+ if (this.#closed || this.#attempts >= (this.#options.maxAttempts ?? Infinity)) return;
398
+ const delay = Math.min((this.#options.baseDelayMs ?? 500) * 2 ** this.#attempts, this.#options.maxDelayMs ?? 3e4);
399
+ this.#attempts += 1;
400
+ this.#timer = setTimeout(() => {
401
+ this.#socket = this.#connect();
402
+ }, delay);
403
+ }
404
+ }
405
+ function createWebSocket(url, options) {
406
+ const WS = options?.WebSocket ?? globalThis.WebSocket;
407
+ if (WS === void 0) throw new Error("WebSocket is not available");
408
+ const protocols = options?.protocols;
409
+ const open = () => protocols === void 0 ? new WS(url) : new WS(url, protocols);
410
+ const reconnect = options?.reconnect;
411
+ if (reconnect === void 0 || reconnect === false) return open();
412
+ return new ReconnectingWebSocket(open, reconnect === true ? {} : reconnect);
413
+ }
414
+
415
+ const NON_ROUTE_PROPS = /* @__PURE__ */ new Set(["then", "catch", "finally", "toJSON", "constructor"]);
416
+ const PASSTHROUGH_PROPS = /* @__PURE__ */ new Set(["toString", "valueOf", "call", "apply", "bind"]);
417
+ function createRpcProxy(client, prefix = "", method = "POST") {
418
+ const make = (path, m) => {
419
+ const fn = (args) => client.request(m, path, args);
420
+ return new Proxy(fn, {
421
+ get(target, prop) {
422
+ if (prop === "withMethod") return (m2) => make(path, m2);
423
+ if (typeof prop !== "string") return Reflect.get(target, prop);
424
+ if (NON_ROUTE_PROPS.has(prop)) return void 0;
425
+ if (PASSTHROUGH_PROPS.has(prop)) return Reflect.get(target, prop);
426
+ return make(path + "/" + encodeSegment(prop), m);
427
+ }
428
+ // No `apply` trap: calling the proxy invokes `fn` directly.
429
+ });
430
+ };
431
+ return make(prefix, method);
432
+ }
433
+
434
+ function createTypedClient(options) {
435
+ return new TupikClient(options);
436
+ }
437
+
438
+ export { ClientRequestError, ReconnectingWebSocket, SSE_MAX_EVENT_SIZE, SSE_MAX_LINE_LENGTH, SseOverflowError, TupikClient, connectSse, createClient, createRpcProxy, createTypedClient, createWebSocket, streamSse };
package/package.json CHANGED
@@ -1,6 +1,54 @@
1
1
  {
2
2
  "name": "@tupik/client",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "version": "1.0.0",
4
+ "description": "Type-safe RPC client for Tupik apps with SSE and WebSocket helpers, inferred from typeof app.",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "tupik",
8
+ "typescript",
9
+ "web-framework",
10
+ "rpc",
11
+ "client",
12
+ "type-safe",
13
+ "sse",
14
+ "websocket"
15
+ ],
16
+ "homepage": "https://github.com/CodeHamper/tupikjs/tree/main/packages/client#readme",
17
+ "repository": {
18
+ "type": "git",
19
+ "url": "https://github.com/CodeHamper/tupikjs.git",
20
+ "directory": "packages/client"
21
+ },
22
+ "bugs": {
23
+ "url": "https://github.com/CodeHamper/tupikjs/issues"
24
+ },
25
+ "type": "module",
26
+ "publishConfig": {
27
+ "access": "public"
28
+ },
29
+ "files": [
30
+ "dist"
31
+ ],
32
+ "exports": {
33
+ ".": {
34
+ "types": "./dist/index.d.ts",
35
+ "import": "./dist/index.mjs"
36
+ }
37
+ },
38
+ "engines": {
39
+ "node": ">=22.12"
40
+ },
41
+ "dependencies": {
42
+ "@tupik/core": "^1.0.0"
43
+ },
44
+ "devDependencies": {
45
+ "typescript": "^5.6.0",
46
+ "unbuild": "^3.0.0",
47
+ "vitest": "^2.1.0"
48
+ },
49
+ "scripts": {
50
+ "build": "unbuild",
51
+ "typecheck": "tsc --noEmit",
52
+ "test": "vitest run"
53
+ }
6
54
  }