$ cat docs/hono.md
Inside HonoDentro do Hono
Mount a Tupik app in an existing Hono app and move the API one route at a time.Monte um app Tupik num app Hono que já existe e mova a API uma rota de cada vez.
What it doesO que faz
@tupik/hono serves part of a Hono app with Tupik. The Hono request, the bindings (c.env) and the execution context (c.executionCtx, for waitUntil) reach Tupik as ctx.req and ctx.runtime. The Tupik Response, headers and streams included, goes back to Hono as is. It works wherever Hono runs: Cloudflare Workers, Bun, Deno and Node.js.
O @tupik/hono serve parte de um app Hono com o Tupik. A requisição do Hono, os bindings (c.env) e o contexto de execução (c.executionCtx, para o waitUntil) chegam ao Tupik como ctx.req e ctx.runtime. A Response do Tupik, com headers e streams, volta intacta ao Hono. Funciona onde o Hono roda: Cloudflare Workers, Bun, Deno e Node.js.
npm install @tupik/hono @tupik/core hono hono (^4.10.0) is a peer dependency: the adapter uses the one your app already has.
O hono (^4.10.0) é dependência par: o adaptador usa o que o seu app já tem.
import { Hono } from 'hono';
import { createApp, createModule } from '@tupik/core';
import { toHono, tupikHandler } from '@tupik/hono';
import { z } from 'zod';
const users = createModule('/users')
.access('public')
.get('/:id', { schema: { params: z.object({ id: z.string() }) }, handler: (ctx) => ({ id: ctx.params.id }) });
const v2 = createApp().register(users);
const hono = new Hono();
hono.route('/v2', toHono(v2)); // GET /v2/users/7: Tupik sees /users/7
hono.all('/v3/*', tupikHandler(v2, { basePath: '/v3' })); // same, with a pattern
export default hono;import { Hono } from 'hono';
import { createApp, createModule } from '@tupik/core';
import { toHono, tupikHandler } from '@tupik/hono';
import { z } from 'zod';
const users = createModule('/users')
.access('public')
.get('/:id', { schema: { params: z.object({ id: z.string() }) }, handler: (ctx) => ({ id: ctx.params.id }) });
const v2 = createApp().register(users);
const hono = new Hono();
hono.route('/v2', toHono(v2)); // GET /v2/users/7: o Tupik vê /users/7
hono.all('/v3/*', tupikHandler(v2, { basePath: '/v3' })); // o mesmo, com padrão
export default hono; OptionsOpções
| OptionOpção | DefaultPadrão | EffectEfeito |
|---|---|---|
basePath (tupikHandler) | prefix of hono.routeprefixo do hono.route | Removed from the path before Tupik matches it.Sai do caminho antes de o Tupik procurar a rota. |
fallthrough | false | Paths with no Tupik route go to the next Hono handler instead of a Tupik 404.Caminho sem rota no Tupik vai para o próximo handler do Hono em vez do 404 do Tupik. |
Only unmatched paths fall through: a 404 from a handler or from access.owner stays a 404. fallthrough registers the app's notFound, so do not set your own.
Só o caminho sem rota passa adiante: o 404 de um handler ou do access.owner continua 404. O fallthrough registra o notFound do app, então não defina o seu.
Reusing the Hono userAproveitar o usuário do Hono
import type { Context } from 'hono';
import { createApp } from '@tupik/core';
import { honoAuthenticate } from '@tupik/hono';
type AppEnv = { Variables: { user: User | undefined } };
const v2 = createApp({ authenticate: honoAuthenticate((c: Context<AppEnv>) => c.get('user')) }); The principal your Hono auth middleware already resolved feeds Tupik's access (401, 403 and the owner 404). A request that did not come through the adapter is anonymous.
O principal que o middleware de login do Hono já resolveu alimenta o access do Tupik (401, 403 e o 404 do dono). Requisição que não passou pelo adaptador é anônima.
Migrating from HonoMigrar do Hono
- Mount first, move nothing. Create an empty Tupik app and mount it with
fallthrough: truebefore the Hono routes of that area:hono.route('/api', toHono(tupikApp, { fallthrough: true })). Every request still reaches Hono. - Bridge auth. Pass
honoAuthenticate(...)tocreateApp, reading what your Hono middleware sets. - Move one route. Rewrite it as a Tupik route with its
accessand schemas, then delete the Hono one. Path and response stay the same; the client does not notice. - Mind the methods. A path that exists in Tupik with another method answers 405. Move all methods of a path together, or declare the remaining Hono route before the mount.
- Check the contract. Run
tupik-contract snapshoton the Tupik app after each move and--fail-on-breakingin CI. - Finish. When the area is empty in Hono, drop
fallthrough, or serve the Tupik app directly with@tupik/edge.
- Monte antes, sem mover nada. Crie um app Tupik vazio e monte com
fallthrough: trueantes das rotas Hono daquela área:hono.route('/api', toHono(tupikApp, { fallthrough: true })). Toda requisição ainda chega ao Hono. - Ligue o login. Passe
honoAuthenticate(...)aocreateApp, lendo o que o seu middleware do Hono guarda. - Mova uma rota. Reescreva como rota Tupik com
accesse schemas e apague a do Hono. Caminho e resposta ficam iguais; o cliente não percebe. - Cuidado com os métodos. Um caminho que existe no Tupik com outro método responde 405. Mova todos os métodos de um caminho juntos ou declare a rota Hono que sobrou antes da montagem.
- Confira o contrato. Rode
tupik-contract snapshotno app Tupik depois de cada rota e--fail-on-breakingno CI. - Termine. Quando a área estiver vazia no Hono, tire o
fallthroughou sirva o app Tupik direto com o@tupik/edge.
| HonoHono | TupikTupik |
|---|---|
app.post('/x', zValidator('json', s), h) | .post('/x', { schema: { body: s }, access, handler }) |
requireAuth middleware per routemiddleware requireAuth rota a rota | access: 'authenticated' (required on every route)access: 'authenticated' (obrigatório em toda rota) |
c.req.valid('json') | ctx.body |
c.json(data, 201) | ctx.status(201).json(data) or return the objectctx.status(201).json(data) ou devolver o objeto |
c.env.DB | getEnv<Env>(ctx).DB (@tupik/edge) |
c.executionCtx.waitUntil(p) | ctx.runtime.executionCtx?.waitUntil(p) |