$ cat docs/api.md
API referenceReferência de API
Public exports of the 16 packages, taken from each package src/index.ts. Signatures are shortened; the source code is the reference.Exports públicos dos 16 pacotes, tirados do src/index.ts de cada pacote. Assinaturas resumidas; o código-fonte é a referência.
PackagesPacotes
@tupik/core@tupik/schema@tupik/node@tupik/edge@tupik/bun@tupik/client@tupik/hono@tupik/middleware@tupik/infra@tupik/env@tupik/openapi@tupik/testing@tupik/lint@tupik/mcp@tupik/passwordcreate-tupik
Version 1.0.0, published on npm; every package shares it. create-tupik is a CLI
(pnpm create tupik), listed with its command. Other command lines: tupik and
tupik-contract (@tupik/openapi, helpers in @tupik/openapi/cli),
tupik-fuzz (@tupik/testing, @tupik/testing/cli) and tupik-lint
(@tupik/lint). On Cloudflare Workers, import @tupik/password/workers.
Versão 1.0.0, publicada no npm; todos os pacotes a compartilham. create-tupik é uma CLI
(pnpm create tupik), listada com o seu comando. Outras linhas de comando: tupik e
tupik-contract (@tupik/openapi, helpers em @tupik/openapi/cli),
tupik-fuzz (@tupik/testing, @tupik/testing/cli) e tupik-lint
(@tupik/lint). No Cloudflare Workers, importe @tupik/password/workers.
import { createApp, createModule } from '@tupik/core';
import { helmet } from '@tupik/middleware';
import { createTestApp } from '@tupik/testing';
const app = createApp().register(
createModule().use(helmet()).get('/', { access: 'public', handler: () => ({ ok: true }) }),
);
const t = createTestApp(app);
const res = await t.get<{ ok: boolean }>('/');
// in-process, no socket: 200, { ok: true }, x-frame-options: DENY
await t.close();import { createApp, createModule } from '@tupik/core';
import { helmet } from '@tupik/middleware';
import { createTestApp } from '@tupik/testing';
const app = createApp().register(
createModule().use(helmet()).get('/', { access: 'public', handler: () => ({ ok: true }) }),
);
const t = createTestApp(app);
const res = await t.get<{ ok: boolean }>('/');
// in-process, sem socket: 200, { ok: true }, x-frame-options: DENY
await t.close(); @tupik/core
Router, context, middleware pipeline, lifecycle hooks, modules, the app engine, mandatory access rules, data classes and the error catalog. Zero dependencies, no node:* imports.Roteador, contexto, pipeline de middleware, hooks de ciclo de vida, módulos, o app engine, regras de acesso obrigatórias, classes de dado e o catálogo de erros. Zero dependências, sem imports node:*.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
createApp | functionfunção | <TDeps, TPrincipal>(options?: AppOptions<TDeps, TPrincipal>) => TupikApp<TDeps, never, TPrincipal> TPrincipal is inferred from authenticate (or comes from TupikRegister).TPrincipal é inferido de authenticate (ou vem de TupikRegister). |
TupikApp | classclasse | register(module) · use(mw) · onStartup/onShutdown/onRequest/preHandler/onSend/onError(hook) · notFound(handler) · fetch(request, env?, executionCtx?) · start() · stop() · routes · services |
AppOptions | typetipo | { services?; exposeErrors?; bodyLimit?; authenticate?: (ctx) => TPrincipal | null; principalId?; response?: 'strip' | 'validate' | 'off'; schemaConverter?; dev? } bodyLimit defaults to 1 MiB (413 above it); response defaults to strip; dev makes a secret field in a response fail the request.bodyLimit padrão de 1 MiB (413 acima disso); response padrão strip; dev faz um campo secret na resposta falhar a requisição. |
TupikRegister / RegisteredPrincipal | typetipo | declare module '@tupik/core' { interface TupikRegister { principal: User } } Declares the principal once for every module.Declara o principal uma vez para todos os módulos. |
ACCEPTS_REQUEST_LIKE | constconstante | unique symbol = Symbol.for('tupik.acceptsRequestLike') |
createModule | functionfunção | <TDeps, TPrefix, TPrincipal>(prefix?: TPrefix, options?: { access? }) => ModuleBuilder<TDeps, never, NormalizePrefix<TPrefix>, TPrincipal> |
ModuleBuilder | classclasse | use(mw) · access(rule) · get/post/put/patch/delete/head/options(path, RouteOptions) · route(method, path, RouteOptions) · lifecycle hooks · prefix · routes |
RouteOptions | typetipo | { access: Access; schema?: TSchema; errors?: ErrorDefinition[]; tags?: string[]; handler } access is required unless the module has a default (type error, and register throws).access é obrigatório se o módulo não tiver padrão (erro de tipo, e o register lança). |
Access | typetipo | 'public' | 'authenticated' | (ctx) => boolean | Response | { auth?: 'required' | 'optional'; check?; owner?: (ctx) => ownerId; ownerMismatch?: 403 | 404 } Runs after the middleware: 401 without a principal, 403 on a denied policy, 404 for a record owned by someone else.Roda depois do middleware: 401 sem principal, 403 com política negada, 404 para registro de outro dono. |
defineErrors | functionfunção | (specs: Record<code, { status; title; type? }>) => ErrorCatalog Routes list the codes in errors; ctx.fail(code, detail?) answers application/problem+json with code.As rotas listam os códigos em errors; ctx.fail(code, detail?) responde application/problem+json com code. |
ErrorDefinition / ErrorCatalog / problemResponse | typetipo | { code; status; title; type? } · (problem) => Response |
classify | functionfunção | (schema, { 'path.to.field': 'pii' | 'health' | 'secret' }, { fields? }) => schema · (fieldSchema, 'pii' | 'health' | 'secret') => fieldSchema Classes live on the field schemas, so z.array, extend, pick, omit, partial, nesting and unions keep them (Zod 4, Valibot; JSON Schema via x-data-class). Responses drop undeclared fields (JSON Schema or fields) and never carry a secret field.As classes ficam no schema do campo, então z.array, extend, pick, omit, partial, aninhamento e uniões as mantêm (Zod 4, Valibot; JSON Schema via x-data-class). Respostas cortam campo não declarado (JSON Schema ou fields) e nunca levam campo secret. |
routeDataClasses / schemaDataClasses | functionfunção | (route) => RouteDataClasses · (schema) => ClassPaths Paths per class, for loggers and error reporters.Caminhos por classe, para loggers e coletores de erro. |
inspectRoutes | functionfunção | (app) => RouteInfo[] Each route with meta: access, auth, dataClasses, errors and tags.Cada rota com meta: access, auth, dataClasses, errors e tags. |
withTags | functionfunção | (middleware, ...tags) => middleware Marks the routes a middleware guards, e.g. 'rate-limited'.Marca as rotas que um middleware protege, ex.: 'rate-limited'. |
RouteMeta / RouteInfo | typetipo | { access: 'public' | 'authenticated' | 'policy' | 'owner'; auth; dataClasses; errors; tags: ReadonlySet<string> } |
parseCookies / serializeCookie | functionfunção | (header) => Record<string, string> · (name, value, CookieOptions?) => string Secure by default; also behind ctx.cookie and ctx.setCookie.Seguro por padrão; também por trás de ctx.cookie e ctx.setCookie. |
WithRoute | typetipo | ModuleBuilder with one more RouteTypeInfo (type level only).ModuleBuilder com mais um RouteTypeInfo (só em nível de tipo). |
RadixRouter | classclasse | new RadixRouter<T>(options?: RadixRouterOptions) · insert(method, path, value) · match(method, path) · createState() · matchInto(method, path, state) · allowedMethods(path) · size · cacheStats |
MatchState | classclasse | value · param(name) · rawParam(name) · params() |
decodeParam | functionfunção | (raw: string) => string Throws URIError on malformed input (the engine maps it to 400).Lança URIError em entrada malformada (o engine converte em 400). |
RadixRouterOptions | typetipo | { cacheSize?: number } Default 1024; 0 disables the cache. Paths over 256 characters are never cached.Padrão 1024; 0 desliga o cache. Caminhos com mais de 256 caracteres nunca entram no cache. |
RouteMatch | typetipo | { value: T; params: Record<string, string> } |
CacheStats | typetipo | { hits: number; misses: number; evictions: number } |
createContext | functionfunção | <TDeps, TInput>(init: ContextInit<TDeps>) => TupikContext<TDeps, TInput> |
caseInsensitiveHeaders | functionfunção | <T>(headers: T) => T Read view whose missing keys are looked up lowercased; used before validating schema.headers.Visão de leitura que procura em minúsculas a chave que falta; usada antes de validar schema.headers. |
ContextInit | typetipo | { req: Request | RequestLike; deps: TDeps; params?; query?; headers?; body?; runtime?: RuntimeBindings } |
compose | functionfunção | <TDeps>(middlewares: readonly MiddlewareHandler<TDeps>[]) => ComposedHandler<TDeps> |
createPipeline | functionfunção | <TDeps>(middlewares, handler) => (ctx) => Promise<Response> |
toResponse | functionfunção | (result: HandlerResult, ctx?) => Response |
Next | typetipo | () => Promise<Response | void> |
ComposedHandler | typetipo | (ctx: TupikContext<TDeps>) => Promise<Response | void> |
Lifecycle | classclasse | onStartup · onShutdown · onRequest · preHandler · onSend · onError · merge(other) |
StartupHook / ShutdownHook | typetipo | (deps: TDeps) => void | Promise<void> |
RequestHook | typetipo | (ctx) => Response | void | Promise<Response | void> |
SendHook | typetipo | (ctx, response: Response) => Response | void | Promise<Response | void> |
ErrorHook | typetipo | (error: unknown, ctx) => Response | void | Promise<Response | void> |
HttpError | classclasse | new HttpError(message, { status?, code?, headers?, details? }) · toResponse() · HttpError.notFound() · HttpError.badRequest() |
HttpErrorOptions | typetipo | { status?: number; code?: string; headers?: HeadersInit; details?: unknown } |
isHttpError | functionfunção | (value: unknown) => value is HttpError |
ACCEPTS_LIGHT_RESPONSE / LIGHT_RESPONSE | constconstante | unique symbol Protocol between runtime drivers and the engine for light responses.Protocolo entre drivers de runtime e o engine para respostas leves. |
LightResponseData | typetipo | { status: number; body: string; contentType: string } |
HTTPMethod | typetipo | 'GET' | 'POST' | 'PUT' | 'DELETE' | 'PATCH' | 'HEAD' | 'OPTIONS' |
StandardSchemaV1 | typetipo | { '~standard': { version: 1; vendor: string; validate(value) } } |
RouteSchema | typetipo | { body?; query?; params?; headers?; response?: Record<number, StandardSchemaV1> } |
TupikContext | typetipo | req · resHeaders · status() · header() · json() · text() · html() · stream() · redirect() · cookie() · setCookie() · fail() · principal · getPrincipal() · deps · body · query · params · headers · rawStore · runtime getPrincipal(): Promise<Principal | null> runs authenticate once per request for middleware; access reuses it.getPrincipal(): Promise<Principal | null> roda o authenticate uma vez por requisição para os middlewares; o access reaproveita. |
Handler | typetipo | (ctx: TupikContext<TDeps, inferred input>) => HandlerResult | Promise<HandlerResult> |
HandlerResult | typetipo | Response | object | string | void |
MiddlewareHandler | typetipo | (ctx, next: () => Promise<Response | void>) => Promise<Response | void>, with optional meta.tags |
RouteContract / CompiledRoute | typetipo | { method; path; schema?; meta; middlewares + handler | pipeline } |
RequestLike / RequestHeadersLike | typetipo | Minimal request surface accepted by TupikApp.fetch besides Request.Superfície mínima de requisição aceita por TupikApp.fetch além de Request. |
RuntimeBindings / ExecutionContextLike | typetipo | { env: TEnv | undefined; executionCtx } · { waitUntil(promise); passThroughOnException?() } |
InferOutput / InferRouteOutput | typetipo | Output type of a Standard Schema / of a route.Tipo de saída de um Standard Schema / de uma rota. |
RouteTypeInfo / NormalizePrefix / JoinPath | typetipo | Type-level route metadata used by the typed client.Metadados de rota em nível de tipo usados pelo cliente tipado. |
AccessKeyword / AccessKind / AccessPolicy / PolicyResult | typetipo | 'public' | 'authenticated' · 'public' | 'authenticated' | 'policy' | 'owner' · (ctx) => PolicyResult · boolean | Response |
OptionalAuthAccess / RequiredAuthAccess | typetipo | { auth: 'optional'; check? } · { auth?: 'required'; check?; owner?; ownerMismatch?: 403 | 404 } |
AuthLevel / AuthOf / EffectiveAuth / PrincipalFor | typetipo | 'none' | 'optional' | 'required' Type helpers: the access rule decides the type of ctx.principal (null, T | null or T).Helpers de tipo: a regra de acesso decide o tipo de ctx.principal (null, T | null ou T). |
Authenticate | typetipo | (ctx) => TPrincipal | null | undefined | Promise<...> Runs only for routes that need a principal, after the middleware.Roda só nas rotas que precisam de principal, depois do middleware. |
ErrorSpec / ErrorCodes / Problem | typetipo | { status; title; type? } · TErrors[number]['code'] · { status; title; code; type?; detail? } |
DataClass / DataClassMap / DataPath / ClassPaths / ClassifyOptions | typetipo | 'pii' | 'health' | 'secret' · { [dot.path]?: DataClass } · { pii?: string[]; health?: string[]; secret?: string[] } · { fields? } |
RouteDataClasses | typetipo | { body?; query?; params?; headers?; response?: Record<status, ClassPaths> } |
ResponseMode | typetipo | 'strip' | 'validate' | 'off' secret fields are removed in every mode.Campos secret saem em todos os modos. |
SchemaConverter / JsonSchemaObject | typetipo | (schema: StandardSchemaV1) => JsonSchemaObject · Record<string, unknown> Standard Schema to JSON Schema, e.g. z.toJSONSchema; shared with @tupik/openapi.Standard Schema para JSON Schema, ex.: z.toJSONSchema; o mesmo do @tupik/openapi. |
DeclaredRouteMeta / MiddlewareMeta | typetipo | { errors; tags } · { tags?: readonly string[] } |
ModuleOptions | typetipo | { access?: Access } Second argument of createModule: module default access.Segundo argumento do createModule: access padrão do módulo. |
AnyModuleBuilder / ModulesRoutes | typetipo | What register accepts and the route union it collects (type level).O que o register aceita e a união de rotas que ele junta (nível de tipo). |
RedirectStatus | typetipo | 301 | 302 | 303 | 307 | 308 Statuses accepted by ctx.redirect.Status aceitos por ctx.redirect. |
createRunner | functionfunção | <TDeps>(middlewares, handler) => (ctx) => Response | Promise<Response> Like createPipeline, but answers synchronously when nothing awaited.Como o createPipeline, mas responde de forma síncrona quando nada esperou. |
InferSchemaOutput / RouteInput | typetipo | Output type read from '~standard.types.output' / the validated input of a route.Tipo de saída lido de '~standard.types.output' / a entrada validada de uma rota. |
CookieOptions | typetipo | { path?; domain?; maxAge?; expires?; secure?; httpOnly?; sameSite?: 'Strict' | 'Lax' | 'None' | false; partitioned? } Secure, HttpOnly and SameSite=Lax by default; the __Host- and __Secure- prefix rules are checked.Secure, HttpOnly e SameSite=Lax por padrão; as regras dos prefixos __Host- e __Secure- são conferidas. |
@tupik/schema
Standard Schema v1 validation, RFC 9457 problem details, a compiled JSON serializer and adapters for precompiled validators.Validação Standard Schema v1, problem details RFC 9457, serializer JSON compilado e adaptadores para validadores pré-compilados.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
isStandardSchema | functionfunção | (value: unknown) => value is StandardSchemaV1 |
validateSchema | functionfunção | <TOutput>(schema, value, options?: ValidateOptions) => Promise<ValidationResult<TOutput>> |
validateRoute | functionfunção | (schema: RouteSchema | undefined, input: RouteInput) => Promise<ValidationResult<ValidatedRouteInput>> |
parseRoute | functionfunção | (schema, input) => Promise<ValidatedRouteInput> Throws ValidationError on invalid input.Lança ValidationError em entrada inválida. |
ValidationError | classclasse | new ValidationError(issues, options?) · issues · problem |
isValidationError | functionfunção | (value: unknown) => value is ValidationError |
toProblemDetails | functionfunção | (issues, options?: ProblemOptions) => ProblemDetails |
problemResponse | functionfunção | (issues, options?) => Response application/problem+json response.Resposta application/problem+json. |
VALIDATION_PROBLEM_TYPE | constconstante | 'https://tupik.dev/problems/validation-error' |
compileSerializer | functionfunção | (shape: JsonShape) => (value: unknown) => string |
JsonShape | typetipo | Shape description consumed by compileSerializer.Descrição de formato consumida por compileSerializer. |
StandardSchemaV1 | typetipo | Re-exported from @tupik/core.Reexportado de @tupik/core. |
SchemaIssue | typetipo | { pointer: string; message: string } |
ValidationResult / ValidationSuccess / ValidationFailure | typetipo | { success: true; value } | { success: false; issues } |
ValidateOptions | typetipo | { pointer?: string } |
RouteInput / ValidatedRouteInput | typetipo | { body; query; params; headers } |
ProblemDetails / ProblemOptions | typetipo | { type; title; status; detail?; instance?; errors? } |
fromAjv | functionfunção | <T>(validate: AjvValidateLike<T>) => StandardSchemaV1<unknown, T> Ajv compiled or standalone validator, run without a promise.Validador Ajv compilado ou standalone, roda sem promise. |
fromTypeBox | functionfunção | <T>(compiled: TypeBoxCheckLike<T>) => StandardSchemaV1<unknown, T> Pass TypeCompiler.Compile(schema).Passe TypeCompiler.Compile(schema). |
fromTypia | functionfunção | <T>(validate: TypiaValidateLike<T>) => StandardSchemaV1<unknown, T> Pass typia.createValidate<T>().Passe typia.createValidate<T>(). |
AjvValidateLike / TypeBoxCheckLike / TypiaValidateLike | typetipo | Structural shapes: the package does not depend on Ajv, TypeBox or typia.Formatos estruturais: o pacote não depende de Ajv, TypeBox nem typia. |
@tupik/node
Native node:http driver: serves any object with fetch(request), with streaming, body limit and abort.Driver nativo node:http: serve qualquer objeto com fetch(request), com streaming, limite de body e abort.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
serve | functionfunção | (app: NodeApp, options?: ServeOptions) => Server | ServeCluster Returns a ServeCluster when options.workers is set.Devolve um ServeCluster quando options.workers está definido. |
dispatch | functionfunção | (app, req: IncomingMessage, res: ServerResponse, options?: Pick<ServeOptions, 'bodyLimit' | 'onError'>) => Promise<void> |
toWebRequest | functionfunção | (req: IncomingMessage, options?: ToWebRequestOptions) => Promise<Request> |
sendResponse | functionfunção | (res: ServerResponse, response: Response) => Promise<void> |
NodeRequest | classclasse | class NodeRequest implements RequestLike · new NodeRequest(method, url, rawHeaders, body, signal?) |
PayloadTooLargeError | classclasse | class extends Error { status = 413 } |
NodeApp | typetipo | { fetch(request: Request): Promise<Response> } |
ServeOptions | typetipo | { port?: number; hostname?: string; bodyLimit?: number; onError?: (error, req) => void; headersTimeout?: number; requestTimeout?: number; keepAliveTimeout?: number } & ClusterOptions |
ToWebRequestOptions | typetipo | { bodyLimit?: number; signal?: AbortSignal } |
SignalSource | typetipo | AbortSignal | (() => AbortSignal) |
ClusterOptions | typetipo | { workers?: number | 'auto'; reusePort?: boolean; shutdownTimeout?: number } Part of ServeOptions. reusePort defaults to on where supported; shutdownTimeout is 10 s.Parte de ServeOptions. reusePort ligado por padrão onde há suporte; shutdownTimeout de 10 s. |
ServeCluster | typetipo | { ready: Promise<number>; workers: readonly Worker[]; close(): Promise<void> } Returned by serve(app, { workers }) in the primary process.Devolvido por serve(app, { workers }) no processo primário. |
reusePortSupported | functionfunção | (platform?, version?) => boolean Linux with Node 22.12+ (or 23.1+).Linux com Node 22.12+ (ou 23.1+). |
@tupik/edge
Fetch-handler adapter for Cloudflare Workers and other WinterCG runtimes; forwards env and executionCtx.Adaptador fetch-handler para Cloudflare Workers e outros runtimes WinterCG; repassa env e executionCtx.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
toEdgeHandler | functionfunção | <TEnv>(app: EdgeApp) => EdgeHandler<TEnv> |
createEdgeWorker | functionfunção | <TEnv>(app: EdgeApp) => { fetch: EdgeHandler<TEnv> } |
getEnv | functionfunção | <TEnv>(ctx: { runtime: RuntimeBindings }) => TEnv |
EdgeApp | typetipo | { fetch(request, env?, executionCtx?): Promise<Response> } |
EdgeHandler | typetipo | (request: Request, env?: TEnv, executionCtx?) => Promise<Response> |
ExecutionContextLike | typetipo | Re-exported from @tupik/core.Reexportado de @tupik/core. |
@tupik/bun
Bun.serve adapter: hands the native Request straight to app.fetch.Adaptador Bun.serve: entrega o Request nativo direto ao app.fetch.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
createBunHandler | functionfunção | (app: BunApp) => BunHandler |
serveBun | functionfunção | (app: BunApp, options?: BunServeOptions & { bun?: BunRuntime }) => BunServer |
BunApp | typetipo | { fetch(request: Request): Promise<Response> } |
BunHandler | typetipo | (request: Request) => Promise<Response> |
BunServeOptions | typetipo | { port?: number; hostname?: string } |
BunRuntime / BunServer | typetipo | { serve(options): BunServer } · { stop(): void } |
createBunRoutes | functionfunção | (app: BunApp, handler: BunRouteHandler) => Record<string, BunRouteHandler> The app paths for Bun.serve({ routes }); serveBun uses it and keeps fetch as fallback.Os caminhos do app para Bun.serve({ routes }); o serveBun usa e mantém o fetch como reserva. |
toBunPath | functionfunção | (path: string) => string | undefined Tupik path to a Bun route pattern, or undefined when Bun cannot express it.Caminho Tupik para um padrão de rota do Bun, ou undefined quando o Bun não consegue expressar. |
BunRouteHandler | typetipo | (request: Request) => Response | Promise<Response> |
@tupik/client
Typed RPC client over fetch, with SSE parsing, WebSocket helper and a path proxy.Cliente RPC tipado sobre fetch, com parser de SSE, helper de WebSocket e proxy de caminhos.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
createClient | functionfunção | (options: ClientOptions) => TupikClient |
TupikClient | classclasse | request(method, path, options?) · get/post/put/patch/delete/head/options(path, options?) → Promise<ClientResult<TData>> |
createTypedClient | functionfunção | <TApp>(options: ClientOptions) => TypedClient<AppRoutes<TApp>> |
createRpcProxy | functionfunção | (client: TupikClient, prefix?: string, method?: HTTPMethod) => unknown method defaults to 'POST'.method padrão 'POST'. |
streamSse | functionfunção | (body: ReadableStream<Uint8Array>, options?: { onControl?(control: SseControl) }) => AsyncGenerator<SseEvent> onControl gets { id?, retry? } of a frame without data.onControl recebe { id?, retry? } de um quadro sem data. |
connectSse | functionfunção | (url: string, options?: SseConnectOptions) => AsyncGenerator<SseEvent> Optional reconnect with Last-Event-ID; applies retry: and id: also from frames without data.Reconexão opcional com Last-Event-ID; aplica retry: e id: também de quadros sem data. |
createWebSocket | functionfunção | (url: string, options?: WebSocketOptions) => WebSocketLike | ReconnectingWebSocket |
ReconnectingWebSocket | classclasse | send · close · addEventListener/removeEventListener · readyState Returned when reconnect is set.Devolvido quando reconnect está ligado. |
ClientRequestError | classclasse | Error & { kind: 'network' | 'timeout' | 'abort' } |
ClientOptions | typetipo | { baseUrl: string; headers?: Record<string, string> | (() => Record<string, string>); fetch?: typeof fetch } & FetchControls |
FetchControls / RetryOptions | typetipo | { signal?; timeout?; credentials?; retry?: { attempts; baseDelayMs?; maxDelayMs?; statuses? } } |
RequestOptions | typetipo | { params?; query?: Record<string, QueryValue>; headers?; body? } & FetchControls |
ClientResult | typetipo | { ok: true; data; response } | { ok: false; kind: 'problem' | 'http'; error; response } | { ok: false; kind: 'network' | 'timeout' | 'abort'; error: ClientRequestError; response: undefined } |
Problem | typetipo | { type?; title?; status?; detail?; instance?; code?: TCode; [extension: string]: unknown } RFC 9457 problem details.Problem details da RFC 9457. |
TypedClient / TypedRequestOptions | typetipo | Per-method typed surface derived from the app routes.Superfície tipada por método derivada das rotas do app. |
AppRoutes / InferInput / PathParams | typetipo | Type helpers over typeof app.Helpers de tipo sobre typeof app. |
SseEvent | typetipo | { event: string; data: string; id?: string; retry?: number } |
SseConnectOptions / SseReconnectOptions | typetipo | { fetch?; headers?; credentials?; signal?; lastEventId?; reconnect?: boolean | { delayMs?; maxAttempts? } } |
WebSocketLike / WebSocketConstructor / WebSocketOptions | typetipo | { protocols?; WebSocket?; reconnect?: boolean | { maxAttempts?; baseDelayMs?; maxDelayMs? } } |
ClientFailureKind | typetipo | 'network' | 'timeout' | 'abort' |
RouteErrorCode / AccessProblemCode | typetipo | declared errors codes · 'UNAUTHORIZED' | 'FORBIDDEN' | 'NOT_FOUND' On a typed call, a kind: 'problem' result types error.code with the route codes plus the access codes.Numa chamada tipada, o resultado kind: 'problem' tipa error.code com os códigos da rota mais os de acesso. |
RouteMap / MethodRoutes | typetipo | Routes of an app indexed by method and path (type level).Rotas de um app indexadas por método e caminho (nível de tipo). |
QueryValue | typetipo | string | number | boolean | undefined | readonly (string | number | boolean)[] Arrays repeat the key.Arrays repetem a chave. |
SSE_MAX_LINE_LENGTH / SSE_MAX_EVENT_SIZE | constconstante | 1 MiB Larger lines or events reject with SseOverflowError.Linhas ou eventos maiores rejeitam com SseOverflowError. |
SseOverflowError | classclasse | class extends Error |
WebSocketEventType / WebSocketListener / WebSocketReconnectOptions | typetipo | 'open' | 'message' | 'close' | 'error' · (event) => void · { maxAttempts?; baseDelayMs?; maxDelayMs? } |
@tupik/hono
Mounts a Tupik app inside an existing Hono app, so an area can move one route at a time. Bindings and executionCtx reach ctx.runtime.Monta um app Tupik dentro de um app Hono que já existe, para mover uma área rota a rota. Bindings e executionCtx chegam em ctx.runtime.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
toHono | functionfunção | (app: MountableApp, options?: ToHonoOptions) => Hono Sub-app for hono.route(prefix, ...); the prefix leaves the path before Tupik matches.Sub-app para hono.route(prefixo, ...); o prefixo sai do caminho antes de o Tupik procurar a rota. |
tupikHandler | functionfunção | (app: MountableApp, options?: TupikHandlerOptions) => MiddlewareHandler Hono handler for hono.all(pattern, ...).Handler Hono para hono.all(padrão, ...). |
honoAuthenticate | functionfunção | (read: (c: Context) => TPrincipal | null | undefined) => Authenticate createApp({ authenticate }) that reads the principal your Hono middleware already resolved.createApp({ authenticate }) que lê o principal que o middleware do Hono já resolveu. |
MountableApp / TupikHandlerOptions / ToHonoOptions | typetipo | { fetch; notFound } · { basePath?; fallthrough? } · { fallthrough? } fallthrough sends paths without a Tupik route to the next Hono handler.fallthrough manda caminhos sem rota no Tupik para o próximo handler do Hono. |
@tupik/middleware
Official universal middlewares: cors, rateLimit, jwt, logger, compress, helmet, requestId, cookies, timing, csrf and the SaaS set (session, tenant, clientIp, bodyLimit, timeout, webhookSignature, idempotency, captcha, apiKey, audit, errorReporter, etag, cacheControl, locale, maintenance, basicAuth, ipAllow, tracing).Middlewares universais oficiais: cors, rateLimit, jwt, logger, compress, helmet, requestId, cookies, timing, csrf e o conjunto de SaaS (session, tenant, clientIp, bodyLimit, timeout, webhookSignature, idempotency, captcha, apiKey, audit, errorReporter, etag, cacheControl, locale, maintenance, basicAuth, ipAllow, tracing).
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
cors | functionfunção | (options?: CorsOptions) => MiddlewareHandler |
rateLimit | functionfunção | (options: RateLimitOptions) => MiddlewareHandler |
MemoryStore | classclasse | new MemoryStore(options?: MemoryStoreOptions) · get(key) · increment(key, windowMs) · now() · size |
resolveClientIp | functionfunção | (headers, options: ClientIpOptions) => string | undefined trust 'cloudflare': cf-connecting-ip only; 'proxy': x-forwarded-for from the right.trust 'cloudflare': só cf-connecting-ip; 'proxy': x-forwarded-for pela direita. |
DurableObjectRateLimitStore | classclasse | new DurableObjectRateLimitStore({ namespace, shards?, now? }) |
RateLimitDurableObject | classclasse | new RateLimitDurableObject(state, env?) · fetch(request) · alarm() Export it from your Worker and bind it as a Durable Object.Exporte do seu Worker e ligue como Durable Object. |
CloudflareRateLimitStore | classclasse | new CloudflareRateLimitStore({ binding, now? }) |
jwt | functionfunção | (options: JwtOptions) => MiddlewareHandler |
signJwt | functionfunção | (payload: JwtPayload, secret: string, options?: SignJwtOptions) => Promise<string> |
verifyJwt | functionfunção | (token: string, secret: JwtSecret, options?: VerifyJwtOptions) => Promise<JwtVerifyResult> |
base64UrlEncode | functionfunção | (bytes: Uint8Array) => string |
base64UrlDecode | functionfunção | (input: string) => Uint8Array |
logger | functionfunção | (options?: LoggerOptions) => MiddlewareHandler |
compress | functionfunção | (options?: CompressOptions) => MiddlewareHandler |
helmet | functionfunção | (options?: HelmetOptions) => MiddlewareHandler |
requestId | functionfunção | (options?: RequestIdOptions) => MiddlewareHandler |
timing | functionfunção | (options?: TimingOptions) => MiddlewareHandler |
csrf | functionfunção | (options: CsrfOptions) => MiddlewareHandler Signed double-submit tokens for unsafe methods; not authentication.Tokens double-submit assinados para métodos inseguros; não é autenticação. |
cookies | functionfunção | () => MiddlewareHandler |
parseCookies | functionfunção | (header: string | null) => Record<string, string> |
serializeCookie | functionfunção | (name: string, value: string, options?: CookieOptions) => string |
session | functionfunção | <TData>(options: SessionOptions) => SessionMiddleware<TData> get(ctx) handle: create, update, rotate, destroy, revokeAll; revokeUser(userId).Handle get(ctx): create, update, rotate, destroy, revokeAll; revokeUser(userId). |
MemorySessionStore / D1SessionStore / KVSessionStore | classclasse | new D1SessionStore({ database, table?, now? }) · D1SessionStore.schema(table?) · purgeExpired() Keys are sha256(session id); user index for revocation.Chaves são sha256(id da sessão); índice por usuário para revogação. |
MemoryTtlStore / D1TtlStore / KVTtlStore | classclasse | get(key) · add(key, value, ttlMs) · set(key, value, ttlMs) · delete(key) Dedup and idempotency storage; add is atomic in memory and D1.Storage de dedup e idempotência; add é atômico em memória e D1. |
tenant | functionfunção | <TTenant>(options: TenantOptions<TTenant>) => TenantMiddleware<TTenant> |
getTenantId | functionfunção | (ctx) => string | undefined |
clientIp | functionfunção | (options: ClientIpOptions) => MiddlewareHandler |
getClientIp | functionfunção | (ctx) => string | undefined |
bodyLimit | functionfunção | (options: BodyLimitOptions) => MiddlewareHandler |
getRawBody | functionfunção | (ctx) => Uint8Array | undefined |
timeout | functionfunção | (options: TimeoutOptions) => MiddlewareHandler |
getSignal | functionfunção | (ctx) => AbortSignal | undefined |
webhookSignature | functionfunção | (options: WebhookSignatureOptions) => MiddlewareHandler Presets 'github', 'stripe', 'asaas'.Presets 'github', 'stripe', 'asaas'. |
idempotency | functionfunção | (options: IdempotencyOptions) => MiddlewareHandler principal may be async: async (ctx) => (await ctx.getPrincipal())?.id.principal pode ser async: async (ctx) => (await ctx.getPrincipal())?.id. |
captcha | functionfunção | (options: CaptchaOptions) => MiddlewareHandler |
apiKey | functionfunção | <TPrincipal>(options: ApiKeyOptions<TPrincipal>) => ApiKeyMiddleware<TPrincipal> |
generateApiKey | functionfunção | (prefix: string) => Promise<{ key: string; hash: string }> |
hashApiKey | functionfunção | (key: string) => Promise<string> |
audit | functionfunção | (options: AuditOptions) => MiddlewareHandler |
errorReporter | functionfunção | (options: ErrorReporterOptions) => MiddlewareHandler |
etag | functionfunção | (options?: EtagOptions) => MiddlewareHandler |
cacheControl | functionfunção | (options: CacheControlOptions) => MiddlewareHandler |
locale | functionfunção | <TLocale>(options: LocaleOptions<TLocale>) => LocaleMiddleware<TLocale> |
maintenance | functionfunção | (options: MaintenanceOptions) => MiddlewareHandler |
basicAuth | functionfunção | (options: BasicAuthOptions) => MiddlewareHandler |
ipAllow | functionfunção | (options: IpAllowOptions) => MiddlewareHandler |
CorsOptions / CorsOrigin | typetipo | See the Middleware guide.Veja o guia de Middlewares. |
RateLimitOptions / RateLimitStore / RateLimitEntry / RateLimitStoreContext / RateLimitTrust / ClientIpOptions / MissingKeyPolicy / MemoryStoreOptions | typetipo | See the Middleware guide.Veja o guia de Middlewares. |
BindingSource / RateLimitBindingLike / CloudflareRateLimitStoreOptions / DurableObjectNamespaceLike / DurableObjectRateLimitStoreOptions / DurableObjectStateLike / DurableObjectStorageLike / RateLimitDurableObjectOptions | typetipo | See the Middleware guide.Veja o guia de Middlewares. |
JwtAlgorithm / JwtHeader / JwtOptions / JwtPayload / JwtVerifyResult / SignJwtOptions / VerifyJwtOptions | typetipo | JwtOptions: secret (32 bytes or more, or a kid map), algorithms, audience, issuer, clockToleranceSec, required. exp is required.JwtOptions: secret (32 bytes ou mais, ou um mapa de kid), algorithms, audience, issuer, clockToleranceSec, required. exp é obrigatório. |
ErrorDetail / LogEntry / LoggerOptions | typetipo | See the Middleware guide.Veja o guia de Middlewares. |
CompressEncoding / CompressOptions | typetipo | See the Middleware guide.Veja o guia de Middlewares. |
HelmetOptions / HstsOptions | typetipo | See the Middleware guide.Veja o guia de Middlewares. |
RequestIdOptions | typetipo | { header?: string; generator?: () => string; trustIncoming?: boolean; expose?: boolean } |
TimingOptions | typetipo | { metric?: string; header?: string; description?: string } |
CsrfOptions / CsrfSessionSource | typetipo | { secret: string; session?: CsrfSessionSource; cookieName?: string; headerName?: string; origins?: readonly string[]; secure?: boolean; sameSite?: 'Strict' | 'Lax' | 'None' } session accepts a function or the session() middleware itself.session aceita uma função ou o próprio middleware session(). |
SessionOptions / SessionCookieOptions / SessionHandle / SessionMiddleware / SessionRecord / SessionStore / MemorySessionStoreOptions / D1SessionStoreOptions / KVSessionStoreOptions | typetipo | See the Sessions guide.Veja o guia de Sessões. |
TtlStore / MemoryTtlStoreOptions / D1TtlStoreOptions / KVTtlStoreOptions / D1DatabaseLike / D1PreparedStatementLike / KVNamespaceLike / StoreContext | typetipo | Duck-typed Workers bindings; no cloudflare:workers import.Bindings do Workers por duck typing; sem import de cloudflare:workers. |
TenantOptions / TenantMiddleware / BodyLimitOptions / TimeoutOptions / IdempotencyOptions / CaptchaOptions / AuditOptions / AuditEvent / ErrorReporterOptions | typetipo | See each middleware guide.Veja o guia de cada middleware. |
WebhookSignatureOptions / HmacWebhookOptions / TokenWebhookOptions / PresetWebhookOptions / WebhookPreset | typetipo | See the Webhook signatures guide.Veja o guia de Assinatura de webhooks. |
ApiKeyOptions / ApiKeyRecord / ApiKeyIdentity / ApiKeyMiddleware | typetipo | See the API keys guide.Veja o guia de Chaves de API. |
EtagOptions / CacheControlOptions / LocaleOptions / LocaleMiddleware / MaintenanceOptions / BasicAuthOptions / IpAllowOptions | typetipo | See each middleware guide.Veja o guia de cada middleware. |
CookieOptions | typetipo | { path?: string; domain?: string; maxAge?: number; expires?: Date; secure?: boolean; httpOnly?: boolean; sameSite?: 'Strict' | 'Lax' | 'None' | false; partitioned?: boolean } Secure, HttpOnly and SameSite=Lax by default.Secure, HttpOnly e SameSite=Lax por padrão. |
RATE_LIMITED_TAG | constconstante | 'rate-limited' Tag rateLimit adds to route meta; tupik audit looks for it on writes.Marca que o rateLimit põe no meta da rota; o tupik audit procura por ela nas escritas. |
tracing | functionfunção | (options: TracingMiddlewareOptions) => MiddlewareHandler One OpenTelemetry SERVER span per request: method, route template, status, tenant and an optional salted user.hash. Never the URL, query, body or headers.Um span OpenTelemetry SERVER por requisição: método, modelo da rota, status, tenant e um user.hash opcional com salt. Nunca a URL, a query, o corpo nem os headers. |
setTraceAttributes | functionfunção | (ctx, attributes: Record<string, unknown>) => void Attributes pass the shared redaction and the route data classes.Os atributos passam pela redação compartilhada e pelas classes de dado da rota. |
getTraceparent | functionfunção | (ctx) => string | undefined W3C traceparent for outgoing calls.traceparent W3C para chamadas de saída. |
TracingMiddlewareOptions / TraceableRoute | typetipo | { tracer?; app: { routes }; redact?; principal?: { salt; id? }; parentContext? } · { method; path; schema? } |
@tupik/infra
Production building blocks with zero dependencies: pluggable storage, structured JSON logger, duck-typed OpenTelemetry tracing.Blocos de produção sem dependências: storage plugável, logger JSON estruturado, tracing OpenTelemetry por duck typing.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
createMemoryStorage | functionfunção | (options?: MemoryStorageOptions) => Storage Per-entry TTL; expired entries are dropped on access.TTL por entrada; entradas expiradas são removidas no acesso. |
namespaced | functionfunção | (storage: Storage, prefix: string) => Storage Keys become prefix + ':' + key; clear() only clears the namespace.As chaves viram prefix + ':' + key; clear() limpa só o namespace. |
createLogger | functionfunção | (options?: LoggerOptions) => Logger |
DEFAULT_REDACT_KEYS | constconstante | readonly string[] Keys always redacted by createLogger.Chaves sempre ocultadas pelo createLogger. |
maskIp | functionfunção | (value: string) => string IPv4 → /24, IPv6 → /48, per list entry.IPv4 → /24, IPv6 → /48, por item da lista. |
createRedactor | functionfunção | (options?: RedactOptions) => (value: unknown) => unknown The logger redaction as a function; also used by @tupik/middleware (logger, errorReporter).A redação do logger como função; também usada pelo @tupik/middleware (logger, errorReporter). |
IP_LOG_KEYS | constconstante | readonly string[] Keys whose values are masked as IPs.Chaves cujos valores são mascarados como IP. |
createRuntimeTracer | functionfunção | (options?: TracingOptions) => RuntimeTracer |
Storage | typetipo | get<T>(key) · set<T>(key, value, options?) · delete(key) · clear() · keys?(prefix?) |
StorageEntryOptions / MemoryStorageOptions | typetipo | { ttlMs?: number } · { now?: () => number } |
ErrorDetail / LogLevel / LogRecord / LogSink / Logger / LoggerOptions / RedactOptions | typetipo | See the Infra guide.Veja o guia de Infra. |
SpanLike / TracerLike / TracingOptions / RuntimeTracer | typetipo | See the Infra guide.Veja o guia de Infra. |
parseTraceparent / formatTraceparent | functionfunção | (header) => SpanContextLike | undefined · (context) => string | undefined W3C trace context; an invalid header gives undefined.Contexto de trace W3C; header inválido dá undefined. |
createAttributeRedactor | functionfunção | (options?: AttributeRedactorOptions) => (attributes) => Record<string, AttributeValue> Span attributes through the redaction; sensitive paths become [redacted], nested objects flatten to dotted keys.Atributos de span pela redação; caminhos sensíveis viram [redacted], objetos aninhados viram chaves com ponto. |
AttributeRedactorOptions / AttributeValue / SpanContextLike / SpanOptionsLike / SpanStartOptions | typetipo | { sensitive?: string[]; redact?; ... } · string | number | boolean | readonly (string | number | boolean)[] · { traceId; spanId; traceFlags } |
@tupik/env
Validated environment: variables, secrets and Workers bindings declared once; a missing value stops the app at startup.Ambiente validado: variáveis, segredos e bindings do Workers declarados uma vez; valor faltando para o app na subida.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
defineEnv | functionfunção | (shape: EnvShape) => EnvDefinition parse(source?) throws EnvError; safeParse(source?) returns { ok, env | error }. Reads process.env, Bun.env or Deno.env by default.parse(source?) lança EnvError; safeParse(source?) devolve { ok, env | error }. Lê process.env, Bun.env ou Deno.env por padrão. |
EnvError | classclasse | Error & { issues: readonly EnvIssue[] } Every problem at once; messages never contain values.Todos os problemas de uma vez; as mensagens nunca trazem os valores. |
string / secret / url / number / boolean / oneOf | functionfunção | (options?) => EnvField<T> All take optional and default, except secret (no default on purpose). An empty string counts as missing.Todos aceitam optional e default, menos secret (sem default de propósito). Texto vazio conta como ausente. |
binding | constconstante | binding.d1() · kv() · r2() · queue() · durableObject() · rateLimit() · service() Checked by shape; pass the real type for full typing: binding.d1<D1Database>().Conferido pelo formato; passe o tipo real para tipagem completa: binding.d1<D1Database>(). |
withEnv | functionfunção | (definition, handler: (request, env, ctx) => Response | Promise<Response>, options?: WithEnvOptions) => (request, env, ctx) => Promise<Response> Workers: validates once per isolate; an invalid env logs once and answers a generic 500.Workers: valida uma vez por isolate; env inválido vai ao log uma vez e responde um 500 genérico. |
EnvDefinition / EnvShape / EnvValues / EnvResult / EnvIssue / EnvSource / InferEnv / OutputOf | typetipo | InferEnv<typeof env> names the parsed object.InferEnv<typeof env> nomeia o objeto validado. |
EnvField / FieldKind / FieldOptions / NumberOptions / Resolve / SecretOptions / StringOptions / UrlOptions / WithEnvOptions | typetipo | Options of the builders.Opções dos construtores. |
BindingBuilder / BindingKind / BindingOptions / BindingTypes / D1Like / KVLike / R2Like / QueueLike / DurableObjectNamespaceLike / RateLimitLike / ServiceLike | typetipo | Duck-typed binding shapes; no cloudflare:workers import.Formatos de binding por duck typing; sem import de cloudflare:workers. |
StandardSchemaV1 | typetipo | Any Standard Schema validates a variable, if it answers synchronously.Qualquer Standard Schema valida uma variável, se responder de forma síncrona. |
@tupik/openapi
OpenAPI 3.1.0 document from the routes (security, x-access, x-data-class, problem responses), the route contract check, tupik audit and the personal data map.Documento OpenAPI 3.1.0 a partir das rotas (security, x-access, x-data-class, respostas problem), verificação do contrato das rotas, tupik audit e o mapa de dados pessoais.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
generateOpenApiDocument | functionfunção | (app: { routes: readonly OpenApiRouteInfo[] }, options?: GenerateOpenApiOptions) => OpenApiDocument |
toOpenApiPath | functionfunção | (path: string) => string '/users/:id' becomes '/users/{id}'.'/users/:id' vira '/users/{id}'. |
GenerateOpenApiOptions | typetipo | { info?; schemaConverter?; onMissingConverter?: 'error' | 'warn'; securitySchemes?; security?; routeSecurity?; tags? } |
OpenApiSecurityScheme / OpenApiSecurityRequirement / RouteSecurityResolver | typetipo | Security schemes and per-route requirements.Esquemas de segurança e requisitos por rota. |
SchemaConverter | typetipo | (schema: StandardSchemaV1) => JsonSchemaObject |
OpenApiDocument | typetipo | { openapi: '3.1.0'; info: OpenApiInfo; paths: Record<string, OpenApiPathItem>; components?; security? } |
OpenApiInfo / OpenApiParameter / OpenApiOperation / OpenApiPathItem | typetipo | Document building blocks.Blocos de construção do documento. |
OpenApiRouteInfo | typetipo | { method: HTTPMethod; path: string; schema?: RouteSchema } |
JsonSchemaObject | typetipo | Record<string, unknown> |
operationIdOf / routeSchemaConverter / MissingConverterMode | functionfunção | (route) => string · (route, converter, onMissing?: 'error' | 'warn' | 'ignore') => converter Building blocks of the generator: stable operationId and a per-route converter with x-data-class marks.Peças do gerador: operationId estável e um conversor por rota com as marcas x-data-class. |
jsonSchemaOf / ownJsonSchema / annotateDataClasses / SchemaDirection | functionfunção | (schema, converter?, direction) => JsonSchemaObject · (json, classes: ClassPaths) => JsonSchemaObject · 'input' | 'output' annotateDataClasses adds x-data-class to classified fields.annotateDataClasses põe x-data-class nos campos classificados. |
problemSchema / routeProblems | functionfunção | (codes: string[]) => JsonSchemaObject · (meta) => ErrorDefinition[] One application/problem+json response per status, with the code enum: declared errors plus UNAUTHORIZED, FORBIDDEN and NOT_FOUND from the access rule.Uma resposta application/problem+json por status, com o enum de code: erros declarados mais UNAUTHORIZED, FORBIDDEN e NOT_FOUND da regra de acesso. |
snapshotContract / diffContracts / hasBreakingChanges / formatContractChanges / parseContractSnapshot / flattenDataClasses | functionfunção | (app, options?: SnapshotContractOptions) => ContractSnapshot · (previous, current) => ContractChange[] The snapshot records routes, statuses, access, auth, data classes and required body fields.O snapshot grava rotas, status, acesso, auth, classes de dado e campos obrigatórios do corpo. |
ContractSnapshot / ContractRoute / ContractRequestFlags / ContractChange / ContractChangeKind / ContractChangeSeverity / SnapshotContractOptions / ContractAppLike | typetipo | { version: 1; generatedWith; routes } · kind: 'access-changed' | 'security-changed' | 'data-class-added' | 'required-field-added' | ... · 'breaking' | 'warning' | 'compatible' |
auditApp | functionfunção | (app, options?: AuditOptions) => AuditReport Rules: public-sensitive-data, sensitive-data, write-without-rate-limit, id-without-owner, public-route, breaking-change, contract-warning.Regras: public-sensitive-data, sensitive-data, write-without-rate-limit, id-without-owner, public-route, breaking-change, contract-warning. |
acceptAudit | functionfunção | (rule: AuditRuleId, reason: string) => string Route tag that accepts one finding with a mandatory reason; it stays as a note with accepted (SARIF: suppressed in source).Marca de rota que aceita um achado com motivo obrigatório; ele fica como note com accepted (SARIF: suprimido no código). |
formatAuditText / auditToSarif / shouldFail / describeSensitiveData | functionfunção | (report) => string · (report, { uri? }?) => SarifLog · (report, failOn: AuditFailOn) => boolean · (meta) => string |
AUDIT_RULES | constconstante | Record<AuditRuleId, { severity; description }> |
AuditOptions / AuditReport / AuditFinding / AuditRule / AuditRuleId / AuditSeverity / AuditFailOn / SarifLog | typetipo | { baseline?; rateLimitTag?; idParam?; disable?; schemaConverter? } · { routes; findings; counts } · 'error' | 'warning' | 'note' | 'none' |
buildDataMap / formatDataMapMarkdown / parseDataMapConfig | functionfunção | (app, config?: DataMapConfig) => DataMap · (map) => string · (value: unknown) => DataMapConfig Per route: pii, health and secret fields received and returned, plus purpose, legal basis and retention from the config.Por rota: campos pii, health e secret recebidos e devolvidos, mais finalidade, base legal e retenção do config. |
DataMap / DataMapEntry / DataMapConfig / DataMapAnnotation / FieldsByClass | typetipo | { routes; subjectRequests; unannotated } · { purpose?; legalBasis?; retention?; notes? } |
defineSubjectRequests | functionfunção | (options: SubjectRequestOptions) => module GET /privacy/export and DELETE /privacy/data. access defaults to 'authenticated'; 'public' throws.GET /privacy/export e DELETE /privacy/data. access padrão 'authenticated'; 'public' lança erro. |
SubjectRequestOptions / SubjectRequestKind / SUBJECT_REQUEST_TAGS | typetipo | { export; erase; access?; prefix?; subjectId? } · 'export' | 'erase' |
runTupikCli / TUPIK_CLI_USAGE / TupikCliDeps | commandcomando | tupik audit | data-map | contract <module> [options] From @tupik/openapi/cli; the tupik bin.De @tupik/openapi/cli; o bin tupik. |
runContractCli / runContractCommand / CONTRACT_CLI_USAGE / ContractCliDeps | commandcomando | tupik-contract snapshot <module> --out <file> · check <module> --baseline <file> --fail-on-breaking From @tupik/openapi/cli; the tupik-contract bin.De @tupik/openapi/cli; o bin tupik-contract. |
parseArgs / loadApp / readJson / requireModule / writeOutput / optionalValue / choiceValue / resolveCliDeps / runCommand / UsageError / CliDeps / ParsedArgs / ResolvedCliDeps | functionfunção | Helpers in @tupik/openapi/cli that other tupik-<command> bins reuse (tupik-fuzz uses them).Helpers do @tupik/openapi/cli que outros bins tupik-<comando> reaproveitam (o tupik-fuzz usa). |
@tupik/testing
In-process TestKit (no socket, no node:*), contract assertions, generated authorization tests and the fuzzer.TestKit in-process (sem socket, sem node:*), asserções de contrato, testes de autorização gerados e o fuzzer.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
createTestApp | functionfunção | <TApp extends InjectableApp>(app: TApp, options?: CreateTestAppOptions) => TestApp<TApp> |
TestApp | typetipo | app · baseUrl · inject(options) · get/delete/head(path, options?) · post/put/patch(path, body?, options?) · close() |
InjectOptions | typetipo | { method?: string; path: string; headers?; body?; query?; cookies? } |
InjectResponse | typetipo | { status; ok; headers; body: T; text; json<U>(); header(name) } |
InjectableApp | typetipo | { fetch(request: Request): Promise<Response>; stop?(): Promise<void> } |
CreateTestAppOptions | typetipo | { baseUrl?: string } Default 'http://test.local'.Padrão 'http://test.local'. |
InjectBodyOptions / InjectRequestOptions / InjectQueryValue | typetipo | Omit<InjectOptions, ...> · string | number | boolean | undefined |
expectValid / expectProblem / expectContract / expectType | functionfunção | (schema, value) => Promise<void> · (response: Response | InjectResponse, { status?, type? }?) => Promise<ProblemDetails> · (app, contract) => Promise<ContractResult> · <T>(value: T) => void |
Contract / ContractApp / ContractRequest / ContractResult / ContractRoute / ExpectProblemOptions / ProblemDetails | typetipo | { method; path; request?; expect?: { status? } } · { response; body } |
generateAccessTests | functionfunção | (app, options: AccessTestOptions) => AccessTestCase[] 401 for anonymous calls on every route that needs a principal; for owner routes, the owner is served and another principal gets 403/404. A case without its fixture comes back with skip.401 para chamada anônima em toda rota que exige principal; nas rotas com owner, o dono é atendido e outro principal recebe 403/404. Caso sem fixture volta com skip. |
AccessTestOptions / AccessTestCase | typetipo | { principals: { owner; other; anonymous? }; fixtures?; baseUrl? } · { name; method; path; skip?; run() } |
fuzz | functionfunção | (app, options?: FuzzOptions) => Promise<FuzzReport> Hostile inputs from each route contract. Fails on a 5xx, a secret field in any response, health data sent to someone else, success on a foreign record or Object.prototype pollution. Same seed, same inputs.Entradas hostis a partir do contrato de cada rota. Falha com 5xx, campo secret em qualquer resposta, dado health para outra pessoa, sucesso em registro alheio ou poluição de Object.prototype. Mesma seed, mesmas entradas. |
formatFuzzReport | functionfunção | (report: FuzzReport) => string |
FuzzOptions / FuzzReport / FuzzFailure / FuzzFailureReason / FuzzLogEntry | typetipo | { seed?; runs?; principals?; fixtures?; foreignIds?; schemaConverter?; routes?; maxStringLength?; baseUrl? } · 'server-error' | 'threw' | 'leaked-field' | 'cross-access' | 'prototype-pollution' |
InspectableApp / InspectableRoute / PrincipalRequest / RouteFixture / RouteFixtures | typetipo | { headers?; cookies? } · { params?; query?; body?; headers? } · Record<'METHOD /path', RouteFixture> |
TestPrincipals | typetipo | { owner?; other?; anonymous?: PrincipalRequest } anonymous: what a request without a principal still carries (an anonymous CSRF pair), so it reaches the 401 of access.anonymous: o que um pedido sem principal ainda leva (um par CSRF anônimo), para chegar ao 401 do access. |
runFuzzCli / FUZZ_CLI_USAGE | commandcomando | tupik-fuzz <module> --principals p.json --fixtures f.json --seed 1 From @tupik/testing/cli; the tupik-fuzz bin (also tupik fuzz).De @tupik/testing/cli; o bin tupik-fuzz (também tupik fuzz). |
@tupik/lint
Security lint for handlers on the Oxc parser: lookups without owner (BOLA), raw rows in responses, request data in logs, hardcoded secrets. Text, JSON and SARIF output.Lint de segurança dos handlers com o parser Oxc: consulta sem dono (BOLA), linha crua na resposta, dado da requisição no log, segredo no código. Saída texto, JSON e SARIF.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
tupik-lint | commandcomando | tupik-lint src [--format text | json | sarif] [--output file] Exit 0 clean or warnings, 1 with an error, 2 on bad usage or config.Saída 0 limpo ou só avisos, 1 com erro, 2 em uso ou configuração inválidos. |
lintSource | functionfunção | (source: string, options?: LintSourceOptions) => Diagnostic[] Options: filename, config.Opções: filename, config. |
lintFiles | functionfunção | (patterns: readonly string[], options?: LintFilesOptions) => Promise<LintResult> |
loadConfig / parseConfig | functionfunção | (cwd, file?) => Promise<LintConfig> · (value, origin) => LintConfig tupik-lint.config.json or package.json#tupikLint.tupik-lint.config.json ou package.json#tupikLint. |
runLintCli | functionfunção | (argv: readonly string[], io?) => Promise<number> |
formatText / formatJson / formatSarif / FORMATTERS | functionfunção | (result: LintResult) => string |
RULES | constconstante | readonly RuleDefinition[] tupik/no-unscoped-lookup, tupik/no-raw-row-response, tupik/no-log-request-data (warn) and tupik/no-hardcoded-secret (error).tupik/no-unscoped-lookup, tupik/no-raw-row-response, tupik/no-log-request-data (warn) e tupik/no-hardcoded-secret (error). |
SECRET_PATTERNS / SOURCE_EXTENSIONS | constconstante | Known key formats; scanned file extensions (ts, tsx, mts, cts, js, jsx, mjs, cjs).Formatos de chave conhecidos; extensões lidas (ts, tsx, mts, cts, js, jsx, mjs, cjs). |
Diagnostic / LintConfig / LintResult / LintSourceOptions / LintFilesOptions / RuleDefinition / RuleContext / RuleId / Severity / RouteInfo / OutputFormat | typetipo | { ruleId; severity; message; file; line; column } · { rules?; ignore? } · 'off' | 'warn' | 'error' |
@tupik/mcp
Model Context Protocol server from the app routes: tools for AI agents with the same access rules, and no pii or health data unless released. No SDK dependency, runs on Workers.Servidor Model Context Protocol a partir das rotas do app: ferramentas para agentes de IA com as mesmas regras de acesso, e sem dado pii ou health salvo liberação. Sem dependência do SDK, roda no Workers.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
createMcpServer | functionfunção | (app: McpApp, options?: McpServerOptions) => McpServer Streamable HTTP, JSON-RPC 2.0, stateless. Tools are opt-in: tags: ['mcp'] on the route, or tools: ['GET /patients/:id'].Streamable HTTP, JSON-RPC 2.0, sem sessão. Ferramentas são opt-in: tags: ['mcp'] na rota, ou tools: ['GET /patients/:id']. |
McpServerOptions | typetipo | { name?; version?; instructions?; tools?: { tag } | string[]; allowDataClasses?: ('pii' | 'health')[]; forwardHeaders?; allowedOrigins?; schemaConverter? } forwardHeaders defaults to authorization and cookie; secret never leaves.forwardHeaders padrão authorization e cookie; secret nunca sai. |
McpServer / McpApp / McpRoute / McpTool / McpToolAnnotations | typetipo | { fetch(request); tools } · { routes; fetch } · { name; description; inputSchema; annotations } |
MCP_PROTOCOL_VERSIONS | constconstante | ['2025-06-18', '2025-03-26'] |
JSON_RPC_ERRORS / JsonRpcError | constconstante | JSON-RPC 2.0 error codes · class extends Error { code } |
@tupik/password
Argon2id (RFC 9106) compiled from Rust to WebAssembly: 34 kB (12.9 kB gzip), PHC strings, constant-time verify. Same API on Workers, Node.js, Bun and Deno.Argon2id (RFC 9106) compilado de Rust para WebAssembly: 34 kB (12,9 kB com gzip), strings PHC, verificação em tempo constante. A mesma API no Workers, Node.js, Bun e Deno.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
hashPassword | functionfunção | (password: PasswordInput, options?: HashOptions) => Promise<string> PHC string. profile 'owasp' by default (19456 KiB, t=2, p=1); 'light' fits the Workers free plan CPU limit.String PHC. profile 'owasp' por padrão (19456 KiB, t=2, p=1); 'light' cabe no limite de CPU do plano grátis do Workers. |
verifyPassword | functionfunção | (phc: string, password: PasswordInput, options?: VerifyOptions) => Promise<boolean> Constant time. A malformed PHC string throws.Tempo constante. String PHC malformada lança erro. |
needsRehash | functionfunção | (phc: string, options?: RehashOptions) => boolean true when the hash is below the target parameters: upgrade at the next login.true quando o hash está abaixo dos parâmetros alvo: atualize no próximo login. |
initPassword | functionfunção | (source?: WasmSource) => Promise<void> Loads the module. On Workers import '@tupik/password/workers', which passes the bundled .wasm for you.Carrega o módulo. No Workers importe '@tupik/password/workers', que passa o .wasm empacotado por você. |
argon2idRaw | functionfunção | (input: RawArgon2Input) => Promise<Uint8Array> Raw hash bytes, for test vectors.Bytes do hash, para vetores de teste. |
parsePhc | functionfunção | (phc: string) => ParsedPhc | undefined |
PROFILES / MAX_MEMORY_COST | constconstante | { owasp: { memoryCost: 19456, timeCost: 2, parallelism: 1 }; light: { memoryCost: 4096, timeCost: 1, parallelism: 1 } } · 1048576 KiB |
HashOptions / VerifyOptions / RehashOptions / Argon2Params / ParsedPhc / RawArgon2Input / WasmSource / PasswordInput / PasswordInputOptions / ProfileName | typetipo | { profile?; memoryCost?; timeCost?; parallelism?; hashLength?; saltLength?; secret?; maxPasswordBytes?; normalize? } · 'owasp' | 'light' |
create-tupik
Project scaffolder. A CLI, not a library: it writes a node, bun or workers project with AGENTS.md and llms.txt and never runs install.Gerador de projeto. Uma CLI, não uma biblioteca: grava um projeto node, bun ou workers com AGENTS.md e llms.txt e nunca roda install.
| Export | KindTipo | SignatureAssinatura |
|---|---|---|
create-tupik | commandcomando | pnpm create tupik my-api --template node | bun | workers [--force] Missing directory or template are asked interactively.Diretório ou template ausentes são perguntados de forma interativa. |