Documentation menuMenu da documentação

$ cat docs/client.md

RPC clientCliente RPC

The client turns HTTP calls into discriminated results, without generating a separate client codebase.O cliente transforma chamadas HTTP em resultados discriminados, sem gerar código de cliente separado.

HTTP

createClient({ baseUrl }) exposes get/post/put/patch/delete/head/options. Each call resolves (never rejects) to { ok: true, data } or { ok: false, kind, error }: kind is 'problem' (an application/problem+json body typed as Problem), 'http' (any other error body) or, with no response, 'network', 'timeout' and 'abort'. signal, timeout, credentials, headers and retry (off by default) are accepted per client and per call.

createClient({ baseUrl }) expõe get/post/put/patch/delete/head/options. Cada chamada resolve (nunca rejeita) para { ok: true, data } ou { ok: false, kind, error }: kind é 'problem' (corpo application/problem+json tipado como Problem), 'http' (outro corpo de erro) ou, sem response, 'network', 'timeout' e 'abort'. signal, timeout, credentials, headers e retry (desligado por padrão) valem por cliente e por chamada.

client.ts
import { createClient } from '@tupik/client';

const client = createClient({
  baseUrl: 'https://api.example.dev',
  headers: () => ({ authorization: 'Bearer ' + token }),
  credentials: 'include',
  timeout: 10_000,
});

const result = await client.get<{ id: string }>('/users/:id', {
  params: { id: '42' },
  query: { expand: true, tag: ['a', 'b'] }, // ?expand=true&tag=a&tag=b
  signal: controller.signal,
  retry: { attempts: 2 }, // idempotent methods only; honours Retry-After
});

if (result.ok) console.log(result.data.id);
else if (result.kind === 'problem') console.error(result.error.title, result.error.detail); // RFC 9457
else if (result.kind === 'http') console.error(result.response.status, result.error);
else console.error(result.kind, result.error); // 'network' 
import { createClient } from '@tupik/client';

const client = createClient({
  baseUrl: 'https://api.example.dev',
  headers: () => ({ authorization: 'Bearer ' + token }),
  credentials: 'include',
  timeout: 10_000,
});

const result = await client.get<{ id: string }>('/users/:id', {
  params: { id: '42' },
  query: { expand: true, tag: ['a', 'b'] }, // ?expand=true&tag=a&tag=b
  signal: controller.signal,
  retry: { attempts: 2 }, // só métodos idempotentes; respeita Retry-After
});

if (result.ok) console.log(result.data.id);
else if (result.kind === 'problem') console.error(result.error.title, result.error.detail); // RFC 9457
else if (result.kind === 'http') console.error(result.response.status, result.error);
else console.error(result.kind, result.error); //  'timeout' | 'abort'|'network' | 'timeout' | 'abort'

SSE

streamSse(body) is an async generator that follows the text/event-stream format (an event without its closing blank line is discarded). connectSse(url, options) opens the stream and, with reconnect, reopens it after a drop.

As the WHATWG spec says, a frame with retry: or id: and no data dispatches no event but still applies. streamSse(body, { onControl }) hands it to onControl as { id?, retry? }, and connectSse uses it for the reconnect delay and the next Last-Event-ID. A server that sends retry: 3000 on connect no longer needs reconnect.delayMs to match it.

streamSse(body) é um async generator que segue o formato text/event-stream (evento sem a linha em branco final é descartado). connectSse(url, options) abre o stream e, com reconnect, reabre após uma queda.

Como manda a especificação WHATWG, um quadro com retry: ou id: e sem data não gera evento, mas vale. streamSse(body, { onControl }) o entrega ao onControl como { id?, retry? }, e o connectSse o usa no intervalo de reconexão e no próximo Last-Event-ID. Um servidor que envia retry: 3000 ao conectar não precisa mais de reconnect.delayMs igual.

sse.ts
import { connectSse, streamSse } from '@tupik/client';

const response = await fetch('https://api.example.dev/events');
if (response.body) {
  // retry: or id: with no data dispatches no event, but still arrives here
  const onControl = (control: { id?: string; retry?: number }) => console.log(control.retry, control.id);
  for await (const event of streamSse(response.body, { onControl })) {
    console.log(event.event, event.data, event.id);
  }
}

// reconnects with Last-Event-ID and the server retry: delay, with or without data
for await (const event of connectSse('https://api.example.dev/events', { reconnect: true, signal })) {
  console.log(event.data);
}
import { connectSse, streamSse } from '@tupik/client';

const response = await fetch('https://api.example.dev/events');
if (response.body) {
  // retry: ou id: sem data não gera evento, mas chega aqui
  const onControl = (control: { id?: string; retry?: number }) => console.log(control.retry, control.id);
  for await (const event of streamSse(response.body, { onControl })) {
    console.log(event.event, event.data, event.id);
  }
}

// reconecta com Last-Event-ID e o retry: do servidor, com ou sem data
for await (const event of connectSse('https://api.example.dev/events', { reconnect: true, signal })) {
  console.log(event.data);
}

WebSocket

Uses the global WebSocket; inject another constructor through the WebSocket option.

Usa o WebSocket global; injete outro construtor pela opção WebSocket.

ws.ts
import { createWebSocket } from '@tupik/client';

const socket = createWebSocket('wss://api.example.dev/live', { protocols: 'tupik' });

// reopens after an unexpected close (backoff); listeners survive
const live = createWebSocket('wss://api.example.dev/live', { reconnect: { maxAttempts: 10 } });
live.addEventListener('message', (event) => console.log(event));
import { createWebSocket } from '@tupik/client';

const socket = createWebSocket('wss://api.example.dev/live', { protocols: 'tupik' });

// reabre após um close inesperado (backoff); os listeners continuam
const live = createWebSocket('wss://api.example.dev/live', { reconnect: { maxAttempts: 10 } });
live.addEventListener('message', (event) => console.log(event));

createRpcProxy

rpc.module.method(args) becomes client.request(verb, '/module/method', args); the default verb is POST and withMethod changes the verb of a branch. Segments are URL-encoded; . and .. throw.

rpc.modulo.metodo(args) vira client.request(verbo, '/modulo/metodo', args); o verbo padrão é POST e withMethod troca o verbo de um ramo. Os segmentos são codificados; . e .. lançam erro.

rpc.ts
import { createClient, createRpcProxy, type ClientResult, type RequestOptions } from '@tupik/client';

type Call = ((args?: RequestOptions) => Promise<ClientResult<unknown>>) & {
  withMethod(method: 'GET'): Call;
};
interface Rpc {
  users: { create: Call; list: Call };
}

// createRpcProxy returns unknown: describe the expected shape with an interface.
const rpc = createRpcProxy(createClient({ baseUrl: 'https://api.example.dev' })) as Rpc;

await rpc.users.create({ body: { name: 'Tupi' } }); // POST /users/create
await rpc.users.list.withMethod('GET')(); // GET /users/list
import { createClient, createRpcProxy, type ClientResult, type RequestOptions } from '@tupik/client';

type Call = ((args?: RequestOptions) => Promise<ClientResult<unknown>>) & {
  withMethod(method: 'GET'): Call;
};
interface Rpc {
  users: { create: Call; list: Call };
}

// createRpcProxy devolve unknown: descreva a forma esperada com uma interface.
const rpc = createRpcProxy(createClient({ baseUrl: 'https://api.example.dev' })) as Rpc;

await rpc.users.create({ body: { name: 'Tupi' } }); // POST /users/create
await rpc.users.list.withMethod('GET')(); // GET /users/list

Typed clientCliente tipado

The type of result.data comes from the route type info: when the route declares schema.response for 200 or 201, it is that schema's output (~standard.types.output); otherwise it is the handler's return type, or unknown for a raw Response. On a kind: 'problem' result, error.code is typed with the codes from the route's errors list plus UNAUTHORIZED, FORBIDDEN and NOT_FOUND from the access rule.

O tipo de result.data vem da informação de tipo da rota: quando a rota declara schema.response para 200 ou 201, é a saída desse schema (~standard.types.output); senão, é o tipo de retorno do handler, ou unknown para uma Response crua. Num resultado kind: 'problem', o error.code é tipado com os códigos da lista errors da rota mais UNAUTHORIZED, FORBIDDEN e NOT_FOUND da regra de acesso.

typed.ts
import { createTypedClient } from '@tupik/client';
import type { app } from './server';

const api = createTypedClient<typeof app>({ baseUrl: 'https://api.example.dev' });
// paths, params and body inferred from the routes registered in the app

const result = await api.get('/posts/:id', { params: { id: '7' } });
if (result.ok) console.log(result.data.title);
else if (result.kind === 'problem') {
  // the route's declared errors plus the access codes
  console.log(result.error.code); // 'POST_LOCKED' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | undefined
}
import { createTypedClient } from '@tupik/client';
import type { app } from './server';

const api = createTypedClient<typeof app>({ baseUrl: 'https://api.example.dev' });
// caminhos, params e body inferidos das rotas registradas no app

const result = await api.get('/posts/:id', { params: { id: '7' } });
if (result.ok) console.log(result.data.title);
else if (result.kind === 'problem') {
  // os erros declarados da rota mais os códigos de acesso
  console.log(result.error.code); // 'POST_LOCKED' | 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' | undefined
}