stitchkit 0.0.1 → 0.1.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 +21 -0
- package/README.md +373 -4
- package/dist/browser/client.d.ts +30 -0
- package/dist/browser/client.d.ts.map +1 -0
- package/dist/browser/http.d.ts +77 -0
- package/dist/browser/http.d.ts.map +1 -0
- package/dist/browser/socket-io.d.ts +69 -0
- package/dist/browser/socket-io.d.ts.map +1 -0
- package/dist/browser/stream.d.ts +2 -0
- package/dist/browser/stream.d.ts.map +1 -0
- package/dist/contract/define.d.ts +94 -0
- package/dist/contract/define.d.ts.map +1 -0
- package/dist/contract/errors.d.ts +46 -0
- package/dist/contract/errors.d.ts.map +1 -0
- package/dist/contract/index.d.ts +4 -0
- package/dist/contract/index.d.ts.map +1 -0
- package/dist/contract/index.js +26 -0
- package/dist/contract/pagination.d.ts +19 -0
- package/dist/contract/pagination.d.ts.map +1 -0
- package/dist/index-5sxnvwb1.js +368 -0
- package/dist/index-7wfkbvss.js +92 -0
- package/dist/index-809wc1tt.js +18 -0
- package/dist/index-gfzn1n4n.js +29 -0
- package/dist/index-ke4mx4ea.js +38 -0
- package/dist/index-n7bmdwmz.js +68 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +111 -0
- package/dist/internal/errors.d.ts +5 -0
- package/dist/internal/errors.d.ts.map +1 -0
- package/dist/internal/typed.d.ts +9 -0
- package/dist/internal/typed.d.ts.map +1 -0
- package/dist/observability/audit.d.ts +32 -0
- package/dist/observability/audit.d.ts.map +1 -0
- package/dist/observability/context.d.ts +60 -0
- package/dist/observability/context.d.ts.map +1 -0
- package/dist/observability/event.d.ts +49 -0
- package/dist/observability/event.d.ts.map +1 -0
- package/dist/observability/index.d.ts +14 -0
- package/dist/observability/index.d.ts.map +1 -0
- package/dist/observability/index.js +266 -0
- package/dist/observability/sanitize.d.ts +42 -0
- package/dist/observability/sanitize.d.ts.map +1 -0
- package/dist/observability/trace.d.ts +42 -0
- package/dist/observability/trace.d.ts.map +1 -0
- package/dist/react/cache-bridge.d.ts +53 -0
- package/dist/react/cache-bridge.d.ts.map +1 -0
- package/dist/react/cursor-query.d.ts +37 -0
- package/dist/react/cursor-query.d.ts.map +1 -0
- package/dist/react.d.ts +3 -0
- package/dist/react.d.ts.map +1 -0
- package/dist/react.js +52 -0
- package/dist/server/cache.d.ts +15 -0
- package/dist/server/cache.d.ts.map +1 -0
- package/dist/server/context.d.ts +9 -0
- package/dist/server/context.d.ts.map +1 -0
- package/dist/server/create.d.ts +4 -0
- package/dist/server/create.d.ts.map +1 -0
- package/dist/server/event-bus.d.ts +24 -0
- package/dist/server/event-bus.d.ts.map +1 -0
- package/dist/server/implement.d.ts +16 -0
- package/dist/server/implement.d.ts.map +1 -0
- package/dist/server/index.d.ts +17 -0
- package/dist/server/index.d.ts.map +1 -0
- package/dist/server/index.js +965 -0
- package/dist/server/logger.d.ts +21 -0
- package/dist/server/logger.d.ts.map +1 -0
- package/dist/server/middleware/auth.d.ts +50 -0
- package/dist/server/middleware/auth.d.ts.map +1 -0
- package/dist/server/middleware/cookies.d.ts +34 -0
- package/dist/server/middleware/cookies.d.ts.map +1 -0
- package/dist/server/middleware/cors.d.ts +9 -0
- package/dist/server/middleware/cors.d.ts.map +1 -0
- package/dist/server/multipart.d.ts +14 -0
- package/dist/server/multipart.d.ts.map +1 -0
- package/dist/server/rate-limit.d.ts +17 -0
- package/dist/server/rate-limit.d.ts.map +1 -0
- package/dist/server/request.d.ts +22 -0
- package/dist/server/request.d.ts.map +1 -0
- package/dist/server/router.d.ts +42 -0
- package/dist/server/router.d.ts.map +1 -0
- package/dist/server/socket-io.d.ts +42 -0
- package/dist/server/socket-io.d.ts.map +1 -0
- package/dist/server/stream.d.ts +18 -0
- package/dist/server/stream.d.ts.map +1 -0
- package/dist/server/swept-map.d.ts +22 -0
- package/dist/server/swept-map.d.ts.map +1 -0
- package/dist/server/types.d.ts +124 -0
- package/dist/server/types.d.ts.map +1 -0
- package/dist/tools/agent.d.ts +14 -0
- package/dist/tools/agent.d.ts.map +1 -0
- package/dist/tools/execute.d.ts +21 -0
- package/dist/tools/execute.d.ts.map +1 -0
- package/dist/tools/mcp-handler.d.ts +21 -0
- package/dist/tools/mcp-handler.d.ts.map +1 -0
- package/dist/tools/mcp-stdio.d.ts +25 -0
- package/dist/tools/mcp-stdio.d.ts.map +1 -0
- package/dist/tools/mcp.d.ts +42 -0
- package/dist/tools/mcp.d.ts.map +1 -0
- package/dist/tools/mount.d.ts +61 -0
- package/dist/tools/mount.d.ts.map +1 -0
- package/dist/tools/names.d.ts +2 -0
- package/dist/tools/names.d.ts.map +1 -0
- package/dist/tools/remote.d.ts +22 -0
- package/dist/tools/remote.d.ts.map +1 -0
- package/dist/tools/schema.d.ts +4 -0
- package/dist/tools/schema.d.ts.map +1 -0
- package/dist/tools/view-file.d.ts +57 -0
- package/dist/tools/view-file.d.ts.map +1 -0
- package/dist/tools.d.ts +8 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/tools.js +654 -0
- package/package.json +136 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Max Listov
|
|
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,7 +1,376 @@
|
|
|
1
|
-
|
|
1
|
+
<p align="center">
|
|
2
|
+
<strong>Contract-first backend framework for Bun.</strong><br/>
|
|
3
|
+
Define your API once — get an HTTP API, MCP tools, AI-agent tools and a typed client.
|
|
4
|
+
</p>
|
|
2
5
|
|
|
3
|
-
|
|
6
|
+
<p align="center">
|
|
7
|
+
<a href="https://www.npmjs.com/package/stitchkit"><img src="https://img.shields.io/npm/v/stitchkit?color=2563eb" alt="npm version" /></a>
|
|
8
|
+
<a href="https://github.com/max-listov/stitchkit/actions/workflows/ci.yml"><img src="https://github.com/max-listov/stitchkit/actions/workflows/ci.yml/badge.svg" alt="CI" /></a>
|
|
9
|
+
<a href="./LICENSE"><img src="https://img.shields.io/npm/l/stitchkit?color=2563eb" alt="MIT license" /></a>
|
|
10
|
+
<img src="https://img.shields.io/badge/runtime-Bun-fbf0df?logo=bun&logoColor=000" alt="Bun" />
|
|
11
|
+
</p>
|
|
4
12
|
|
|
5
|
-
|
|
13
|
+
<p align="center">
|
|
14
|
+
<img src="https://raw.githubusercontent.com/max-listov/stitchkit/master/assets/infographic-hero.jpg" alt="One contract becomes an HTTP API, MCP tools, AI-agent tools and a typed client" width="100%" />
|
|
15
|
+
</p>
|
|
6
16
|
|
|
7
|
-
|
|
17
|
+
<p align="center">
|
|
18
|
+
<em>One <code>defineContract()</code> → an HTTP API, MCP tools and AI-agent tools on the server — plus a fully-typed client to call them.</em>
|
|
19
|
+
</p>
|
|
20
|
+
|
|
21
|
+
---
|
|
22
|
+
|
|
23
|
+
## Why
|
|
24
|
+
|
|
25
|
+
- **One contract, four surfaces.** Define your API once — get HTTP routes, MCP tools (for Claude/Cursor), AI SDK tools (for agents), and a typed client.
|
|
26
|
+
- **Zero HTTP framework deps.** Built on `Bun.serve()` directly. No Hono, no Elysia, no Express.
|
|
27
|
+
- **Fullstack type safety.** Server handlers, client calls, MCP tools — all typed from the same contract.
|
|
28
|
+
- **Small.** ~4000 lines of source. No magic, no codegen, no build step.
|
|
29
|
+
- **Thin over what you already use.** WebSocket = Socket.IO (`createSocketIOClient` / `createSocketIOServer`). React data layer = `react-query-kit` (`createCursorQuery`). stitchkit owns the contract and the transport — not its own competing WebSocket or hook engine.
|
|
30
|
+
|
|
31
|
+
### The problem it solves
|
|
32
|
+
|
|
33
|
+
A modern backend exposes the *same* operations three ways — an HTTP API for the
|
|
34
|
+
app, MCP tools for assistants like Claude and Cursor, and tool definitions for AI
|
|
35
|
+
agents. Written by hand, that is one surface described three times: three places
|
|
36
|
+
to drift, three places to keep in sync. stitchkit collapses them into a single
|
|
37
|
+
contract — change it once, every surface and the typed client move together.
|
|
38
|
+
|
|
39
|
+
<p align="center">
|
|
40
|
+
<img src="https://raw.githubusercontent.com/max-listov/stitchkit/master/assets/infographic-compare.jpg" alt="Without stitchkit: the same API hand-written three times. With stitchkit: one contract drives them all." width="100%" />
|
|
41
|
+
</p>
|
|
42
|
+
|
|
43
|
+
## Status
|
|
44
|
+
|
|
45
|
+
Pre-1.0. The core is stable and covered by tests, but the public API may still
|
|
46
|
+
change between minor versions until 1.0. Bun-only — there is no Node/Deno
|
|
47
|
+
compatibility layer.
|
|
48
|
+
|
|
49
|
+
## Install
|
|
50
|
+
|
|
51
|
+
```bash
|
|
52
|
+
bun add stitchkit
|
|
53
|
+
```
|
|
54
|
+
|
|
55
|
+
## Import policy
|
|
56
|
+
|
|
57
|
+
Browser code imports browser-safe entrypoints:
|
|
58
|
+
|
|
59
|
+
```ts
|
|
60
|
+
import { defineContract, createClient, createHttpClient } from 'stitchkit'
|
|
61
|
+
import { createSocketIOClient } from 'stitchkit'
|
|
62
|
+
import { createCursorQuery, createCacheBridge } from 'stitchkit/react'
|
|
63
|
+
import { parseSSE } from 'stitchkit'
|
|
64
|
+
```
|
|
65
|
+
|
|
66
|
+
Server code imports server entrypoints:
|
|
67
|
+
|
|
68
|
+
```ts
|
|
69
|
+
import { createServer, createHandler, implement } from 'stitchkit/server'
|
|
70
|
+
import { createSocketIOServer, createAuthHook } from 'stitchkit/server'
|
|
71
|
+
import { createMcpHandler, mountAgent } from 'stitchkit/tools'
|
|
72
|
+
```
|
|
73
|
+
|
|
74
|
+
The root `stitchkit` entrypoint is browser-safe. Server and tool code live behind `stitchkit/server` and `stitchkit/tools`.
|
|
75
|
+
|
|
76
|
+
## Quick Start
|
|
77
|
+
|
|
78
|
+
### 1. Define a contract
|
|
79
|
+
|
|
80
|
+
```ts
|
|
81
|
+
// shared/contracts.ts
|
|
82
|
+
import { defineContract } from 'stitchkit'
|
|
83
|
+
import { z } from 'zod'
|
|
84
|
+
|
|
85
|
+
const UserSchema = z.object({ id: z.string(), name: z.string() })
|
|
86
|
+
const CreateUserSchema = z.object({ name: z.string() })
|
|
87
|
+
const IdSchema = z.object({ id: z.string() })
|
|
88
|
+
|
|
89
|
+
export const users = defineContract({ prefix: 'users' }, {
|
|
90
|
+
list: { method: 'GET', path: '/', desc: 'List all users', output: z.array(UserSchema) },
|
|
91
|
+
create: { method: 'POST', path: '/', desc: 'Create a user', input: CreateUserSchema, output: UserSchema },
|
|
92
|
+
get: { method: 'GET', path: '/:id', desc: 'Get user by ID', params: IdSchema, output: UserSchema },
|
|
93
|
+
delete: { method: 'DELETE', path: '/:id', desc: 'Delete a user', params: IdSchema },
|
|
94
|
+
})
|
|
95
|
+
```
|
|
96
|
+
|
|
97
|
+
### 2. Implement handlers
|
|
98
|
+
|
|
99
|
+
```ts
|
|
100
|
+
// server/index.ts
|
|
101
|
+
import { implement, createServer } from 'stitchkit/server'
|
|
102
|
+
import { users } from '../shared/contracts'
|
|
103
|
+
|
|
104
|
+
const service = implement(users, {
|
|
105
|
+
list: (ctx) => db.users.findMany(),
|
|
106
|
+
create: (ctx) => db.users.create({ name: ctx.input.name }),
|
|
107
|
+
get: (ctx) => db.users.findById(ctx.params.id),
|
|
108
|
+
delete: (ctx) => db.users.delete(ctx.params.id),
|
|
109
|
+
})
|
|
110
|
+
|
|
111
|
+
createServer({ services: [service], port: 3000 })
|
|
112
|
+
```
|
|
113
|
+
|
|
114
|
+
### 3. Use from the client
|
|
115
|
+
|
|
116
|
+
```ts
|
|
117
|
+
// client/api.ts
|
|
118
|
+
import { createClient, createHttpClient } from 'stitchkit'
|
|
119
|
+
import { users } from '../shared/contracts'
|
|
120
|
+
|
|
121
|
+
const http = createHttpClient({ baseUrl: '/api' })
|
|
122
|
+
export const api = createClient(users, http)
|
|
123
|
+
|
|
124
|
+
await api.list() // GET /users → User[]
|
|
125
|
+
await api.create({ name: 'Max' }) // POST /users → User
|
|
126
|
+
await api.get({ id: '123' }) // GET /users/123 → User
|
|
127
|
+
```
|
|
128
|
+
|
|
129
|
+
For many contracts at once, use `createClients(contractRegistry, http)`.
|
|
130
|
+
|
|
131
|
+
### 4. React data layer (react-query-kit)
|
|
132
|
+
|
|
133
|
+
stitchkit does not ship its own hook engine — pair the typed client with
|
|
134
|
+
[`react-query-kit`](https://github.com/liaoliao666/react-query-kit), wrapping
|
|
135
|
+
the client methods directly:
|
|
136
|
+
|
|
137
|
+
```ts
|
|
138
|
+
import { createMutation, createQuery } from 'react-query-kit'
|
|
139
|
+
import { api } from './api'
|
|
140
|
+
|
|
141
|
+
export const useUsers = createQuery({ queryKey: ['users'], fetcher: () => api.list() })
|
|
142
|
+
export const useCreateUser = createMutation({ mutationFn: api.create })
|
|
143
|
+
```
|
|
144
|
+
|
|
145
|
+
For cursor-paginated lists, `createCursorQuery` is the canonical helper:
|
|
146
|
+
|
|
147
|
+
```ts
|
|
148
|
+
import { createCursorQuery } from 'stitchkit/react'
|
|
149
|
+
import { api } from './api'
|
|
150
|
+
|
|
151
|
+
export const useFeed = createCursorQuery({ queryKey: ['feed'], endpoint: api.feed.list })
|
|
152
|
+
```
|
|
153
|
+
|
|
154
|
+
It injects `cursor` from the page param and bakes in `getNextPageParam`. Page
|
|
155
|
+
size is the server's call — the contract's `limit` default — never the client's.
|
|
156
|
+
|
|
157
|
+
### 5. MCP tools (for Claude, Cursor, etc.)
|
|
158
|
+
|
|
159
|
+
```ts
|
|
160
|
+
import { createMcpHandler } from 'stitchkit/tools'
|
|
161
|
+
|
|
162
|
+
const handleMcp = createMcpHandler({
|
|
163
|
+
serverInfo: { name: 'my-app', version: '1.0.0' },
|
|
164
|
+
auth: (req) => resolveApiKey(req), // → identity, or null for 401
|
|
165
|
+
services: [service], // contract endpoints with expose: ['MCP']
|
|
166
|
+
})
|
|
167
|
+
// mount `handleMcp` under /mcp — no @modelcontextprotocol/sdk import in your app
|
|
168
|
+
```
|
|
169
|
+
|
|
170
|
+
### 6. AI Agent tools
|
|
171
|
+
|
|
172
|
+
```ts
|
|
173
|
+
import { mountAgent } from 'stitchkit/tools'
|
|
174
|
+
import { generateText } from 'ai'
|
|
175
|
+
|
|
176
|
+
const tools = mountAgent(service, { context: { userId: 'agent-1' } })
|
|
177
|
+
const result = await generateText({ model, tools, prompt: 'Create a user named Max' })
|
|
178
|
+
```
|
|
179
|
+
|
|
180
|
+
### 7. WebSocket (Socket.IO)
|
|
181
|
+
|
|
182
|
+
stitchkit's WebSocket layer is Socket.IO — `polling` fallback, heartbeat, acks,
|
|
183
|
+
a mature client. The wrappers cover the boilerplate.
|
|
184
|
+
|
|
185
|
+
```ts
|
|
186
|
+
// Server
|
|
187
|
+
import { createServer, createSocketIOServer } from 'stitchkit/server'
|
|
188
|
+
|
|
189
|
+
const socket = createSocketIOServer<ServerToClientEvents, ClientToServerEvents>({
|
|
190
|
+
cors: { origin: 'https://app.example.com' },
|
|
191
|
+
})
|
|
192
|
+
|
|
193
|
+
socket.io.on('connection', (s) => { /* rooms, handshake auth — your domain logic */ })
|
|
194
|
+
|
|
195
|
+
createServer({
|
|
196
|
+
services: [service],
|
|
197
|
+
websocket: socket.websocket, // → Bun.serve
|
|
198
|
+
rawRoutes: [socket.route], // ready /socket.io/* route
|
|
199
|
+
})
|
|
200
|
+
```
|
|
201
|
+
|
|
202
|
+
```ts
|
|
203
|
+
// Client
|
|
204
|
+
import { createSocketIOClient } from 'stitchkit'
|
|
205
|
+
|
|
206
|
+
const socket = createSocketIOClient<ServerToClientEvents, ClientToServerEvents>({
|
|
207
|
+
url: 'https://api.example.com',
|
|
208
|
+
})
|
|
209
|
+
socket.connect()
|
|
210
|
+
socket.on('notification', (data) => console.log(data)) // typed
|
|
211
|
+
socket.emit('join', { room: 'r1' }) // typed
|
|
212
|
+
```
|
|
213
|
+
|
|
214
|
+
### 8. Cache Bridge
|
|
215
|
+
|
|
216
|
+
Sync Socket.IO events into the TanStack Query cache. Transport-agnostic — it
|
|
217
|
+
takes any emitter with `on(event, handler) => unsubscribe` (the
|
|
218
|
+
`createSocketIOClient` result qualifies).
|
|
219
|
+
|
|
220
|
+
```ts
|
|
221
|
+
import { createCacheBridge } from 'stitchkit/react'
|
|
222
|
+
|
|
223
|
+
const bridge = createCacheBridge({
|
|
224
|
+
socket,
|
|
225
|
+
queryClient,
|
|
226
|
+
handlers: {
|
|
227
|
+
notification: (data, ctx) => {
|
|
228
|
+
if (ctx.isFresh(['notes'])) return // skip echo of own mutation
|
|
229
|
+
ctx.queryClient.setQueryData(['notes'], data)
|
|
230
|
+
},
|
|
231
|
+
},
|
|
232
|
+
})
|
|
233
|
+
bridge.connect()
|
|
234
|
+
// in a mutation: onSuccess: () => bridge.markFresh(['notes'])
|
|
235
|
+
```
|
|
236
|
+
|
|
237
|
+
### 9. SSE Streaming
|
|
238
|
+
|
|
239
|
+
```ts
|
|
240
|
+
import { streamSSE } from 'stitchkit/server' // server: AsyncGenerator → SSE Response
|
|
241
|
+
import { parseSSE } from 'stitchkit' // client: Response → AsyncGenerator
|
|
242
|
+
```
|
|
243
|
+
|
|
244
|
+
## Features
|
|
245
|
+
|
|
246
|
+
| Feature | API |
|
|
247
|
+
|---------|-----|
|
|
248
|
+
| **Contract** | `defineContract()` — single source of truth for your API |
|
|
249
|
+
| **HTTP Server** | `createServer()` / `createHandler()` — Bun.serve, validation, hooks, raw routes |
|
|
250
|
+
| **MCP Tools** | `createMcpHandler()` / `mountMcp()` — MCP tools from contracts |
|
|
251
|
+
| **Agent Tools** | `mountAgent()` — Vercel AI SDK tools from contracts |
|
|
252
|
+
| **Typed Client** | `createClient()` / `createClients()` — typed fetch from contracts |
|
|
253
|
+
| **Cursor Pagination** | `createCursorQuery()` — `react-query-kit` infinite query from a contract method |
|
|
254
|
+
| **WebSocket** | `createSocketIOClient()` / `createSocketIOServer()` — typed Socket.IO wrappers |
|
|
255
|
+
| **Cache Bridge** | `createCacheBridge()` — socket events → TanStack Query cache |
|
|
256
|
+
| **Auth** | `createAuthHook()` / `createBearerResolver()` — scope-aware auth from `contract.scope` |
|
|
257
|
+
| **SSE Streaming** | `streamSSE()` / `parseSSE()` — async generator ↔ SSE |
|
|
258
|
+
| **Events** | `createEventBus<EventMap>()` — typed in-process pub/sub |
|
|
259
|
+
| **Multipart** | `parseMultipart()` — file upload with field validation |
|
|
260
|
+
| **Rate Limiting** | `createRateLimiter()` — token bucket, per-key |
|
|
261
|
+
| **Cache** | `createCache()` — in-memory with TTL + `cacheHeaders()` |
|
|
262
|
+
| **Errors** | `AppError`, `notFound()`, `badRequest()`, `unauthorized()` |
|
|
263
|
+
|
|
264
|
+
## How it compares
|
|
265
|
+
|
|
266
|
+
A modern backend exposes the same operations as an HTTP API, as MCP tools and as
|
|
267
|
+
AI-agent tools. Most stacks make you describe each surface separately.
|
|
268
|
+
|
|
269
|
+
| | **Without stitchkit** | **With stitchkit** |
|
|
270
|
+
|--|----------------------|--------------------|
|
|
271
|
+
| Define an operation | once per surface — HTTP, MCP, agent (3×) | once — `defineContract()` |
|
|
272
|
+
| Keep the surfaces in sync | manual; they drift apart | cannot drift — one source |
|
|
273
|
+
| Typed client | hand-written, or a codegen step | inferred from the contract |
|
|
274
|
+
| Expose a new surface | re-describe every endpoint | flip `expose` — already typed |
|
|
275
|
+
|
|
276
|
+
Versus other typed-API tools:
|
|
277
|
+
|
|
278
|
+
| Capability | stitchkit | tRPC | ts-rest | Hono / Elysia |
|
|
279
|
+
|------------|:---:|:---:|:---:|:---:|
|
|
280
|
+
| Contract is plain data — no decorators, no codegen | ✅ | ⚠️ router type | ✅ | ❌ |
|
|
281
|
+
| Inferred typed client | ✅ | ✅ | ✅ | ⚠️ Eden / hc |
|
|
282
|
+
| Plain HTTP REST routes | ✅ | ⚠️ RPC-style | ✅ | ✅ |
|
|
283
|
+
| **MCP tools from the same contract** | ✅ | ❌ | ❌ | ❌ |
|
|
284
|
+
| **AI-agent tools from the same contract** | ✅ | ❌ | ❌ | ❌ |
|
|
285
|
+
| No HTTP-framework dependency | ✅ | ✅ | ✅ | — it is one |
|
|
286
|
+
|
|
287
|
+
The line no other tool draws: **the same contract becomes MCP tools and AI-agent
|
|
288
|
+
tools** — not just an HTTP API and a client. That is what stitchkit is for.
|
|
289
|
+
|
|
290
|
+
## Lifecycle Hooks
|
|
291
|
+
|
|
292
|
+
```ts
|
|
293
|
+
createServer({
|
|
294
|
+
services: [service],
|
|
295
|
+
hooks: {
|
|
296
|
+
onRequest(req) { }, // logging, rate limiting
|
|
297
|
+
beforeHandle(ctx, endpoint) { }, // auth, scope checks
|
|
298
|
+
afterHandle(ctx, result) { }, // transform, cache headers
|
|
299
|
+
onError(ctx, error) { }, // error formatting
|
|
300
|
+
},
|
|
301
|
+
})
|
|
302
|
+
```
|
|
303
|
+
|
|
304
|
+
## Auth & Scopes
|
|
305
|
+
|
|
306
|
+
Contracts carry a `scope`; `createAuthHook` enforces it on every transport from
|
|
307
|
+
one declarative `rules` map:
|
|
308
|
+
|
|
309
|
+
```ts
|
|
310
|
+
import { createAuthHook, createBearerResolver } from 'stitchkit/server'
|
|
311
|
+
|
|
312
|
+
const authHook = createAuthHook<User>({
|
|
313
|
+
resolve: (ctx) => resolveSession(ctx),
|
|
314
|
+
rules: {
|
|
315
|
+
public: 'public',
|
|
316
|
+
user: 'authenticated',
|
|
317
|
+
admin: (user) => user.isAdmin,
|
|
318
|
+
},
|
|
319
|
+
})
|
|
320
|
+
|
|
321
|
+
createServer({ services, hooks: { beforeHandle: authHook } })
|
|
322
|
+
```
|
|
323
|
+
|
|
324
|
+
## Dependencies
|
|
325
|
+
|
|
326
|
+
stitchkit ships with **one runtime dependency**. Everything else is an optional
|
|
327
|
+
peer — an install pulls in only what the project actually uses.
|
|
328
|
+
|
|
329
|
+
| Dependency | Kind | Why this one |
|
|
330
|
+
|------------|------|--------------|
|
|
331
|
+
| `ky` | bundled, runtime | The HTTP client behind the typed client — ~13 KB, `fetch`-based, with retry, hooks and timeouts built in. The only thing stitchkit installs for you. |
|
|
332
|
+
| `zod` | peer, **required** | Schemas are the single source of truth. A peer so your app and stitchkit share **one** `zod` instance — `z.infer` types and `instanceof` checks break across two copies. |
|
|
333
|
+
| `@modelcontextprotocol/sdk` | peer, optional | Only `stitchkit/tools` — the MCP server. |
|
|
334
|
+
| `ai` | peer, optional | Only `stitchkit/tools` — agent tools (Vercel AI SDK). |
|
|
335
|
+
| `@tanstack/react-query` + `react-query-kit` | peer, optional | Only `stitchkit/react` — `createCursorQuery`, `createCacheBridge`. |
|
|
336
|
+
| `socket.io` / `@socket.io/bun-engine` / `socket.io-client` | peer, optional | Only the Socket.IO wrappers. |
|
|
337
|
+
|
|
338
|
+
**Why peers, not bundled.** A peer is resolved once, by your app — framework and
|
|
339
|
+
app code share a single instance. Bundled copies would double `zod`, split the
|
|
340
|
+
`react` hook runtime and break `instanceof`. Optional peers mean an app that
|
|
341
|
+
never touches MCP never installs the MCP SDK. → [DECISIONS.md](./docs/DECISIONS.md#adr-0011)
|
|
342
|
+
|
|
343
|
+
The framework itself is small — ~4000 lines, no codegen, no build step in your app.
|
|
344
|
+
|
|
345
|
+
## Example
|
|
346
|
+
|
|
347
|
+
A complete runnable app lives in [`packages/starter`](./packages/starter) — a
|
|
348
|
+
notes CRUD with a contract, a typed client, `react-query-kit` hooks and a
|
|
349
|
+
Socket.IO live-reload.
|
|
350
|
+
|
|
351
|
+
## Documentation
|
|
352
|
+
|
|
353
|
+
This README is the quick start. The full guide and API reference are in
|
|
354
|
+
[`docs/`](./docs/README.md):
|
|
355
|
+
|
|
356
|
+
- **Guide** — [getting started](./docs/guide/getting-started.md) ·
|
|
357
|
+
[contracts](./docs/guide/contracts.md) ·
|
|
358
|
+
[HTTP server](./docs/guide/server.md) ·
|
|
359
|
+
[typed client](./docs/guide/client.md) ·
|
|
360
|
+
[MCP & agents](./docs/guide/mcp-and-agents.md) ·
|
|
361
|
+
[realtime](./docs/guide/realtime.md) ·
|
|
362
|
+
[auth & errors](./docs/guide/auth-and-errors.md) ·
|
|
363
|
+
[testing & deployment](./docs/guide/testing-and-deployment.md)
|
|
364
|
+
- **[API reference](./docs/api/reference.md)** — every export, by entrypoint.
|
|
365
|
+
- **[Roadmap](./ROADMAP.md)** — where stitchkit is going.
|
|
366
|
+
- **[Architecture decisions](./docs/DECISIONS.md)** — the *why* behind the design.
|
|
367
|
+
|
|
368
|
+
## Contributing
|
|
369
|
+
|
|
370
|
+
Issues and PRs are welcome — see [CONTRIBUTING.md](./CONTRIBUTING.md). Released
|
|
371
|
+
changes are in [CHANGELOG.md](./CHANGELOG.md); security issues go through
|
|
372
|
+
[SECURITY.md](./SECURITY.md).
|
|
373
|
+
|
|
374
|
+
## License
|
|
375
|
+
|
|
376
|
+
[MIT](./LICENSE) © Max Listov
|
|
@@ -0,0 +1,30 @@
|
|
|
1
|
+
import type { ContractDef, EndpointDef, TypedHttpClient } from '../contract';
|
|
2
|
+
import { type HttpClient as HttpAdapter } from './http';
|
|
3
|
+
/** Config for the built-in fetch client — used when no `HttpClient` is passed. */
|
|
4
|
+
export interface ClientConfig {
|
|
5
|
+
baseUrl: string;
|
|
6
|
+
headers?: Record<string, string> | (() => Record<string, string>);
|
|
7
|
+
credentials?: RequestCredentials;
|
|
8
|
+
onError?: (status: number, body: unknown) => void;
|
|
9
|
+
}
|
|
10
|
+
/** Per-contract client tweaks — a dynamic URL `pathPrefix` and the keys it consumes. */
|
|
11
|
+
export interface ContractClientConfig {
|
|
12
|
+
pathPrefix?: string | ((args: Record<string, unknown>) => string);
|
|
13
|
+
stripPrefixKeys?: string[];
|
|
14
|
+
}
|
|
15
|
+
/**
|
|
16
|
+
* Build a fully-typed client from a contract. Every endpoint becomes a typed
|
|
17
|
+
* method — arguments and result inferred from its schemas. Pass an `HttpClient`
|
|
18
|
+
* (from `createHttpClient`) for cookie auth, SSR and retry, or a plain
|
|
19
|
+
* `ClientConfig` for a bare fetch client.
|
|
20
|
+
*/
|
|
21
|
+
export declare function createClient<T extends Record<string, EndpointDef>>(contract: ContractDef<T, string>, configOrClient: ClientConfig | HttpAdapter, contractConfig?: ContractClientConfig): TypedHttpClient<T>;
|
|
22
|
+
/**
|
|
23
|
+
* Batch form of `createClient` — one fully-typed client per contract, built
|
|
24
|
+
* from a `name → contract` registry. Each key keeps its own client type, so
|
|
25
|
+
* the project lists its contracts once and gets the whole typed API.
|
|
26
|
+
*/
|
|
27
|
+
export declare function createClients<T extends Record<string, ContractDef<Record<string, EndpointDef>, string>>>(contracts: T, http: HttpAdapter): {
|
|
28
|
+
[K in keyof T]: TypedHttpClient<T[K]['endpoints']>;
|
|
29
|
+
};
|
|
30
|
+
//# sourceMappingURL=client.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"client.d.ts","sourceRoot":"","sources":["../../src/browser/client.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,WAAW,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@@ -0,0 +1,77 @@
|
|
|
1
|
+
import type { ErrorEnvelope } from '../contract';
|
|
2
|
+
export type ApiEvent = {
|
|
3
|
+
type: 'unauthorized';
|
|
4
|
+
} | {
|
|
5
|
+
type: 'network_error';
|
|
6
|
+
} | {
|
|
7
|
+
type: 'logout';
|
|
8
|
+
};
|
|
9
|
+
export type ApiEventListener = (event: ApiEvent) => void;
|
|
10
|
+
export declare class ApiError extends Error {
|
|
11
|
+
readonly code: string;
|
|
12
|
+
readonly status: number;
|
|
13
|
+
readonly details?: unknown | undefined;
|
|
14
|
+
readonly hint?: string | undefined;
|
|
15
|
+
constructor(code: string, status?: number, details?: unknown | undefined, message?: string, hint?: string | undefined);
|
|
16
|
+
static is(error: unknown): error is ApiError;
|
|
17
|
+
}
|
|
18
|
+
/**
|
|
19
|
+
* Parse a response body into an `ErrorEnvelope['error']` — the default
|
|
20
|
+
* `HttpClientConfig.parseError`. Returns `null` when the body is not a
|
|
21
|
+
* stitchkit error envelope. Shared by `createHttpClient` and `createClient`.
|
|
22
|
+
*/
|
|
23
|
+
export declare function parseApiErrorBody(body: unknown): ErrorEnvelope['error'] | null;
|
|
24
|
+
export type HeaderProvider = Record<string, string> | (() => Record<string, string> | null | undefined);
|
|
25
|
+
/** Configuration for `createHttpClient`. */
|
|
26
|
+
export interface HttpClientConfig {
|
|
27
|
+
baseUrl: string;
|
|
28
|
+
timeout?: number;
|
|
29
|
+
credentials?: RequestCredentials;
|
|
30
|
+
/**
|
|
31
|
+
* Transport retry. Defaults: 2 attempts, GET only, network errors only
|
|
32
|
+
* (empty `statusCodes`). Retrying a server that *responded* (5xx) belongs
|
|
33
|
+
* in the data layer (e.g. TanStack Query), not the transport — keeping it
|
|
34
|
+
* here too would multiply attempts. Override per project if really needed.
|
|
35
|
+
*/
|
|
36
|
+
retry?: {
|
|
37
|
+
limit?: number;
|
|
38
|
+
methods?: string[];
|
|
39
|
+
statusCodes?: number[];
|
|
40
|
+
};
|
|
41
|
+
parseError?: (body: unknown) => ErrorEnvelope['error'] | null;
|
|
42
|
+
authEndpoints?: string[];
|
|
43
|
+
/**
|
|
44
|
+
* Extra headers added to every request. A function is re-evaluated per
|
|
45
|
+
* request — use it for runtime tokens (e.g. a short-lived auth token).
|
|
46
|
+
*/
|
|
47
|
+
headers?: HeaderProvider;
|
|
48
|
+
}
|
|
49
|
+
type ParamValue = string | number | boolean | undefined;
|
|
50
|
+
type ParamArrayValue = Array<string | number>;
|
|
51
|
+
export interface RequestOptions {
|
|
52
|
+
params?: Record<string, ParamValue | ParamArrayValue>;
|
|
53
|
+
timeout?: number;
|
|
54
|
+
responseType?: 'json' | 'blob';
|
|
55
|
+
}
|
|
56
|
+
/** The HTTP transport adapter `createClient` builds typed methods on. */
|
|
57
|
+
export interface HttpClient {
|
|
58
|
+
get<T>(url: string, options?: RequestOptions): Promise<T>;
|
|
59
|
+
post<T>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
|
|
60
|
+
put<T>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
|
|
61
|
+
patch<T>(url: string, data?: unknown, options?: RequestOptions): Promise<T>;
|
|
62
|
+
delete<T>(url: string, options?: RequestOptions): Promise<T>;
|
|
63
|
+
setServerContext(cookies: string): void;
|
|
64
|
+
subscribe(listener: ApiEventListener): () => void;
|
|
65
|
+
/** Mark the client as logged out — suppresses further `unauthorized` events. */
|
|
66
|
+
logout(): void;
|
|
67
|
+
/** Clear the logged-out flag — call after a successful re-login. */
|
|
68
|
+
resetLogoutState(): void;
|
|
69
|
+
}
|
|
70
|
+
/**
|
|
71
|
+
* Create a Ky-based `HttpClient` — the transport `createClient` builds on.
|
|
72
|
+
* Handles cookie auth, SSR cookie forwarding, error parsing into `ApiError`, a
|
|
73
|
+
* `401 → unauthorized` event stream, and safe transport retry.
|
|
74
|
+
*/
|
|
75
|
+
export declare function createHttpClient(config: HttpClientConfig): HttpClient;
|
|
76
|
+
export {};
|
|
77
|
+
//# sourceMappingURL=http.d.ts.map
|
|
@@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E,MAAM,CAAC,CAAC,EAAE,GAAG,EAAE,MAAM,EAAE,OAAO,CAAC,EAAE,cAAc,GAAG,OAAO,CAAC,CAAC,CAAC,CAAC;IAC7D,gBAAgB,CAAC,OAAO,EAAE,MAAM,GAAG,IAAI,CAAC;IACxC,SAAS,CAAC,QAAQ,EAAE,gBAAgB,GAAG,MAAM,IAAI,CAAC;IAClD,gFAAgF;IAChF,MAAM,IAAI,IAAI,CAAC;IACf,oEAAoE;IACpE,gBAAgB,IAAI,IAAI,CAAC;CAC1B;AAED;;;;GAIG;AACH,wBAAgB,gBAAgB,CAAC,MAAM,EAAE,gBAAgB,GAAG,UAAU,CA4JrE"}
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Typed Socket.IO client — the family WebSocket client.
|
|
3
|
+
*
|
|
4
|
+
* The whole family runs on Socket.IO (`polling` fallback, heartbeat, acks,
|
|
5
|
+
* mature reconnection) — not a hand-rolled WebSocket. Every project copied the
|
|
6
|
+
* same ~150-line client: `io()` config, connection-state machine, a typed
|
|
7
|
+
* `on/emit`, a connection-change subscription. `createSocketIOClient` is that
|
|
8
|
+
* shared kernel.
|
|
9
|
+
*
|
|
10
|
+
* Subscriptions are durable: `on()` registers a handler once and the client
|
|
11
|
+
* re-attaches it onto every socket it builds — so a handler survives an
|
|
12
|
+
* explicit `disconnect()` / `connect()` cycle, and (because re-attach happens
|
|
13
|
+
* before `socket.connect()`) no handshake-time event is ever missed. A thin
|
|
14
|
+
* per-project layer can therefore subscribe once at construction.
|
|
15
|
+
*
|
|
16
|
+
* Auth identity (`userId`, `clientId`) is project-specific — it arrives in an
|
|
17
|
+
* app `authenticated` event — so it stays in that per-project layer on top.
|
|
18
|
+
* This client owns only the transport: connection lifecycle + typed events.
|
|
19
|
+
*
|
|
20
|
+
* The returned client satisfies `CacheBridgeSocket` (`on()` returns an
|
|
21
|
+
* unsubscribe), so it plugs straight into `createCacheBridge`.
|
|
22
|
+
*/
|
|
23
|
+
import type { EventsMap } from '@socket.io/component-emitter';
|
|
24
|
+
/**
|
|
25
|
+
* Socket.IO event map — `{ event: (...args) => void }`. Aliases Socket.IO's
|
|
26
|
+
* own `EventsMap` constraint, which intentionally maps to `any`: that is what
|
|
27
|
+
* lets a plain `interface ServerToClientEvents { … }` (no index signature) be
|
|
28
|
+
* passed as a type argument. Per-event typing is fully preserved on the
|
|
29
|
+
* public `on` / `emit` signatures.
|
|
30
|
+
*/
|
|
31
|
+
export type SocketEventMap = EventsMap;
|
|
32
|
+
export interface SocketIOClientConfig {
|
|
33
|
+
/** Server origin, e.g. `https://api.example.com`. */
|
|
34
|
+
url: string;
|
|
35
|
+
/** Socket.IO endpoint path. Default `/socket.io/`. */
|
|
36
|
+
path?: string;
|
|
37
|
+
/** Send cookies on the handshake (cookie-based auth). Default `true`. */
|
|
38
|
+
withCredentials?: boolean;
|
|
39
|
+
/** Transports, in preference order. Default `['websocket', 'polling']`. */
|
|
40
|
+
transports?: Array<'websocket' | 'polling'>;
|
|
41
|
+
/** Reconnection attempts. Default `Infinity`. */
|
|
42
|
+
reconnectionAttempts?: number;
|
|
43
|
+
/** Initial reconnection delay (ms). Default `1000`. */
|
|
44
|
+
reconnectionDelay?: number;
|
|
45
|
+
/** Max reconnection delay (ms). Default `5000`. */
|
|
46
|
+
reconnectionDelayMax?: number;
|
|
47
|
+
/** Connection timeout (ms). Default `20000`. */
|
|
48
|
+
timeout?: number;
|
|
49
|
+
}
|
|
50
|
+
export interface SocketIOClient<TServerEvents extends SocketEventMap, TClientEvents extends SocketEventMap> {
|
|
51
|
+
/** Create the socket (if absent) and connect. Idempotent. */
|
|
52
|
+
connect(): void;
|
|
53
|
+
/** Disconnect and drop the socket instance. */
|
|
54
|
+
disconnect(): void;
|
|
55
|
+
/** True while the underlying socket is connected. */
|
|
56
|
+
readonly connected: boolean;
|
|
57
|
+
/**
|
|
58
|
+
* Subscribe to a server → client event. Returns an unsubscribe. The handler
|
|
59
|
+
* is durable — it is re-attached onto every socket the client builds, so it
|
|
60
|
+
* survives a `disconnect()` / `connect()` cycle.
|
|
61
|
+
*/
|
|
62
|
+
on<E extends keyof TServerEvents & string>(event: E, handler: TServerEvents[E]): () => void;
|
|
63
|
+
/** Emit a client → server event. No-op while disconnected. */
|
|
64
|
+
emit<E extends keyof TClientEvents & string>(event: E, ...args: Parameters<TClientEvents[E]>): void;
|
|
65
|
+
/** Subscribe to connection up/down changes. Returns an unsubscribe. */
|
|
66
|
+
onConnectionChange(listener: (connected: boolean) => void): () => void;
|
|
67
|
+
}
|
|
68
|
+
export declare function createSocketIOClient<TServerEvents extends SocketEventMap, TClientEvents extends SocketEventMap>(config: SocketIOClientConfig): SocketIOClient<TServerEvents, TClientEvents>;
|
|
69
|
+
//# sourceMappingURL=socket-io.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"socket-io.d.ts","sourceRoot":"","sources":["../../src/browser/socket-io.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,OAAO,KAAK,EAAE,SAAS,EAAE,MAAM,8BAA8B,CAAC;AAM9D;;;;;;GAMG;AACH,MAAM,MAAM,cAAc,GAAG,SAAS,CAAC;AAEvC,MAAM,WAAW,oBAAoB;IACnC,qDAAqD;IACrD,GAAG,EAAE,MAAM,CAAC;IACZ,sDAAsD;IACtD,IAAI,CAAC,EAAE,MAAM,CAAC;IACd,yEAAyE;IACzE,eAAe,CAAC,EAAE,OAAO,CAAC;IAC1B,2EAA2E;IAC3E,UAAU,CAAC,EAAE,KAAK,CAAC,WAAW,GAAG,SAAS,CAAC,CAAC;IAC5C,iDAAiD;IACjD,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,uDAAuD;IACvD,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,mDAAmD;IACnD,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,gDAAgD;IAChD,OAAO,CAAC,EAAE,MAAM,CAAC;CAClB;AAED,M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