$ cat docs/quickstart.md
QuickstartQuickstart
A module declares routes, the app registers them and the driver delivers the response. No decorators, no reflection.Um módulo declara rotas, o app as registra e o driver entrega a resposta. Sem decorators e sem reflexão.
1. Install1. Instalar
Node.js 22 or 24 (22.12 or newer) and TypeScript 5.4+ with native ESM ("type": "module").
Node.js 22 ou 24 (22.12 ou mais novo) e TypeScript 5.4+ com ESM nativo ("type": "module").
pnpm add @tupik/core @tupik/node Version 1.0.0 on npm. With npm: npm install @tupik/core @tupik/node. New project: npm create tupik@latest.Versão 1.0.0 no npm. Com npm: npm install @tupik/core @tupik/node. Projeto novo: npm create tupik@latest.
2. Create the app2. Criar o app
createModule() returns a fluent builder; each HTTP method takes { access, handler }.
Every route declares access: there is no implicit public route, so a forgotten rule is a type error
and register refuses it at startup. createApp().register(module) compiles the routes into
the Radix router.
createModule() devolve um builder fluente; cada método HTTP recebe { access, handler }.
Toda rota declara access: não existe rota pública implícita, então uma regra esquecida é erro de tipo
e o register a recusa na subida. createApp().register(modulo) compila as rotas no roteador
Radix.
import { createApp, createModule } from '@tupik/core';
import { serve } from '@tupik/node';
const health = createModule().get('/health', {
access: 'public',
handler: (ctx) => ctx.json({ ok: true }),
});
const app = createApp().register(health);
serve(app, { port: 3000 }); 3. First endpoint3. Primeiro endpoint
Handlers may return a Response, an object (serialized as JSON), a string, or use the context helpers:
ctx.json, ctx.text, ctx.html, ctx.status. Without a
params schema, ctx.params is a Record<string, string>; declare one in
schema for a validated, typed id.
Handlers podem devolver uma Response, um objeto (serializado como JSON), uma string ou usar os
helpers do contexto: ctx.json, ctx.text, ctx.html, ctx.status.
Sem schema de params, ctx.params é um Record<string, string>; declare um
em schema para ter um id validado e tipado.
import { createModule } from '@tupik/core';
export const users = createModule('/users')
.get('/:id', {
access: 'public',
handler: (ctx) => ({ id: ctx.params.id }),
})
.post('/', {
access: 'authenticated',
handler: (ctx) => ctx.status(201).json({ createdBy: ctx.principal.id }),
});
// app.ts
// createApp({ authenticate: (ctx) => sessions.get(ctx.cookie('sid')) ?? null })
// .register(health).register(users); 4. Access, owners and errors4. Acesso, dono e erros
access takes 'public', 'authenticated', a policy (ctx) => boolean or
{ auth, check, owner }. It runs after the middleware and before the handler: no principal answers
401, a denied policy 403, and an owner that is not the principal 404 (the record's existence is not
revealed). ctx.principal is typed by the rule. defineErrors declares error codes once;
a route lists the ones it may raise and ctx.fail(code) answers application/problem+json.
The security model explains each piece.
access aceita 'public', 'authenticated', uma política (ctx) => boolean ou
{ auth, check, owner }. Roda depois do middleware e antes do handler: sem principal responde 401,
política negada 403, e um owner que não é o principal 404 (não revela que o registro existe).
ctx.principal é tipado pela regra. defineErrors declara os códigos de erro uma vez; a rota
lista os que pode lançar e ctx.fail(code) responde application/problem+json.
O modelo de segurança explica cada peça.
import { createModule, defineErrors } from '@tupik/core';
const errors = defineErrors({
POST_LOCKED: { status: 423, title: 'Post is locked' },
});
export const posts = createModule('/posts')
.access('authenticated') // module default; a route's own access wins
.get('/:id', {
// BOLA guard: someone else's post answers 404
access: { owner: async (ctx) => (await db.post(ctx.params.id))?.authorId },
handler: (ctx) => db.post(ctx.params.id),
})
.delete('/:id', {
access: (ctx) => ctx.principal.role === 'admin',
errors: [errors.POST_LOCKED],
handler: (ctx) => ctx.fail('POST_LOCKED'),
}); 5. Test without a server5. Testar sem servidor
app.fetch(request) is the universal port: tests call the app directly, no port opened.
app.fetch(request) é a porta universal: testes chamam o app direto, sem abrir porta.
const response = await app.fetch(new Request('http://localhost/health'));
console.log(response.status); // 200
console.log(await response.json()); // { ok: true }