@sendproof/hono 0.0.0-stage → 0.1.0-alpha.1

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 ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Sendproof contributors
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,3 +1,31 @@
1
- # Temporary Holding Version
1
+ # @sendproof/hono
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Mount Sendproof in a Node-hosted Hono application and explicitly register the operations that may run in a rollback preview. Each registered operation uses the same Hono handlers for normal requests and internal preview dispatch.
4
+
5
+ ```js
6
+ import { Hono } from 'hono';
7
+ import { sendproof } from '@sendproof/hono';
8
+
9
+ const app = new Hono();
10
+ const bench = sendproof({
11
+ environment: 'development',
12
+ openApiUrl: '/openapi.json',
13
+ previewProvider, // transaction provider for the database used by the handlers
14
+ resolveIdentity: ({ raw: c }) => currentUser(c),
15
+ authorize: (_request, identity) => Boolean(identity),
16
+ });
17
+ bench.operation('POST', '/items', authenticate, createItem);
18
+ app.route('/', bench);
19
+ ```
20
+
21
+ For a mount at `/tenant`, pass `basePath: '/tenant'` and mount with `app.route('/tenant', bench)`. Configure a preview provider that starts a transaction on the connection used by the handlers and resolves only after rollback; `@sendproof/sqlite` supplies one for SQLite. Authentication and authorization handlers must be included in each registered operation. Workbench access can be restricted with `authorize`; a stable identity `subject` and `scheme` enable owner-scoped observed-send traces. Sendproof is enabled only in development by default. See the shared protocol and core options for capture limits and other configuration.
22
+
23
+ Preview dispatch stays inside the process and reads response streams only up to `maxResponseBytes`. Avoid handlers that rely on state set by parent middleware: register required middleware with the operation so it runs during both Send and Preview.
24
+
25
+ ## Types and handlers
26
+
27
+ The package is written in strict TypeScript and ships its declarations. `operation()` accepts any Hono handler or middleware (`OperationHandler<E>`), so `bench.operation('GET', '/items/{id}', c => c.json(…))` and typed `Hono<{ Variables: … }>` environments both compile. A basePath is validated at creation: it must be an absolute literal path without a trailing slash, `.` or `..` segments.
28
+
29
+ ## Development
30
+
31
+ Sources live in `src/` (`index.ts` public API, `paths.ts` template and prefix validation, `response.ts` fetch/transport conversion). Tests are in `../tests/hono.test.mts` and run in-process through `app.request()`, with no network. They cover 11 cases: route matching, registration validation, guards, JSON bodies and observed Send, operation middleware versus parent middleware, options and validation, Preview preconditions, base path, stream cancellation at the limit, exact-limit boundary, and handler failures.
@@ -0,0 +1,25 @@
1
+ import { Hono } from 'hono';
2
+ import type { Context, Env, Handler, MiddlewareHandler } from 'hono';
3
+ import type { BenchOptions, UnavailableOptions } from '@sendproof/core';
4
+ export type SendproofOptions<E extends Env = Env> = BenchOptions<Context<E>> & {
5
+ /** Path on the parent app where this router is mounted, without a trailing slash. */
6
+ basePath?: string;
7
+ };
8
+ /** A Hono route handler or middleware, as accepted by `app.get(path, …)`. */
9
+ export type OperationHandler<E extends Env = Env> = Handler<E> | MiddlewareHandler<E>;
10
+ export type SendproofRouter<E extends Env = Env> = Hono<E> & {
11
+ /** Register the same Hono handlers for Send and rollback Preview. */
12
+ operation(method: string, template: string, ...handlers: OperationHandler<E>[]): SendproofRouter<E>;
13
+ /**
14
+ * Register handlers for an operation marked `preview: false`, for one that writes to a guarded
15
+ * store such as Redis. Send runs them; capabilities list it in `previewUnavailable` with the
16
+ * reason, and a Preview of it answers 409 without running them.
17
+ */
18
+ unavailable(method: string, template: string, options: UnavailableOptions, ...handlers: OperationHandler<E>[]): SendproofRouter<E>;
19
+ };
20
+ /**
21
+ * Create a Hono router that serves the workbench and carries explicitly
22
+ * registered previewable operations. Mount it on the application with
23
+ * `app.route(basePath || '/', router)`.
24
+ */
25
+ export declare function sendproof<E extends Env = Env>(options?: SendproofOptions<E>): SendproofRouter<E>;
package/dist/index.js ADDED
@@ -0,0 +1,95 @@
1
+ import { Hono } from 'hono';
2
+ import { attributeRequest, createBench, unavailableOperation } from '@sendproof/core';
3
+ import { assertBasePath, routePath } from './paths.js';
4
+ import { captureResponse, toResponse, unmatchedHeader } from './response.js';
5
+ const operationMethods = new Set(['get', 'post', 'put', 'patch', 'delete', 'options']);
6
+ /** Describe a Hono request in the framework-neutral shape the core protocol expects. */
7
+ function describe(c, basePath) {
8
+ const url = new URL(c.req.url);
9
+ return {
10
+ method: c.req.method,
11
+ pathname: url.pathname.slice(basePath.length),
12
+ query: url.search,
13
+ basePath,
14
+ origin: url.origin,
15
+ headers: Object.fromEntries(c.req.raw.headers),
16
+ raw: c,
17
+ };
18
+ }
19
+ /**
20
+ * Create a Hono router that serves the workbench and carries explicitly
21
+ * registered previewable operations. Mount it on the application with
22
+ * `app.route(basePath || '/', router)`.
23
+ */
24
+ export function sendproof(options = {}) {
25
+ const { basePath = '', ...benchOptions } = options;
26
+ assertBasePath(basePath);
27
+ const app = new Hono({ strict: true });
28
+ // Preview dispatches into this second router so a handler runs without the workbench gate in front of it.
29
+ const internal = new Hono({ strict: true });
30
+ const operations = [];
31
+ const bench = createBench(benchOptions, () => operations, { language: 'node', framework: 'Hono' });
32
+ app.use('*', async (c, next) => {
33
+ const request = describe(c, basePath);
34
+ const answer = await bench.lookup(request);
35
+ // Attribute the request's store writes to it on runtimes without Node's HTTP server, whose
36
+ // requests the core attributes itself.
37
+ if (!answer)
38
+ return attributeRequest(next);
39
+ if (!('target' in answer))
40
+ return toResponse(answer, c.req.method);
41
+ const rendered = await bench.preview(request, async () => {
42
+ const target = new URL(answer.target, request.origin);
43
+ const response = await internal.fetch(new Request(target, c.req.raw), c.env);
44
+ if (response.status === 404 && response.headers.get(unmatchedHeader) === '1')
45
+ return { unmatched: true };
46
+ return captureResponse(response, bench.maxResponseBytes);
47
+ });
48
+ return toResponse(rendered, c.req.method);
49
+ });
50
+ internal.notFound(() => new Response(null, { status: 404, headers: { [unmatchedHeader]: '1' } }));
51
+ /** Validate a registration and return its upper-case method. */
52
+ const register = (method, template, handlers) => {
53
+ const verb = method.toLowerCase();
54
+ if (!operationMethods.has(verb) || !handlers.length) {
55
+ throw new TypeError('Choose a supported HTTP method and supply the route handler.');
56
+ }
57
+ const upper = verb.toUpperCase();
58
+ if (operations.some(entry => entry.method === upper && entry.path === template)) {
59
+ throw new TypeError('This operation is already registered.');
60
+ }
61
+ return upper;
62
+ };
63
+ app.unavailable = (method, template, options, ...handlers) => {
64
+ const upper = register(method, template, handlers);
65
+ const entry = unavailableOperation(upper, template, options);
66
+ // Only the public router gets the handlers, so a Preview dispatch finds no operation.
67
+ const [first, ...rest] = handlers;
68
+ app.on(upper, routePath(template), first, ...rest);
69
+ operations.push({ ...entry, preview: false });
70
+ return app;
71
+ };
72
+ app.operation = (method, template, ...handlers) => {
73
+ const upper = register(method, template, handlers);
74
+ const path = routePath(template);
75
+ // The observation wrapper times and captures a real Send when the client asked for a trace.
76
+ const observe = async (c, next) => {
77
+ if (c.req.method !== upper)
78
+ return next();
79
+ const observed = await bench.observation(describe(c, basePath));
80
+ if (!observed)
81
+ return next();
82
+ await observed.run(next);
83
+ const trace = observed.complete(c.res.status);
84
+ if (trace)
85
+ c.header('X-Sendproof-Trace', trace);
86
+ };
87
+ // The guard above guarantees at least one handler, as Hono's typings require.
88
+ const [first, ...rest] = handlers;
89
+ app.on(upper, path, observe, first, ...rest);
90
+ internal.on(upper, path, first, ...rest);
91
+ operations.push({ method: upper, path: template });
92
+ return app;
93
+ };
94
+ return app;
95
+ }
@@ -0,0 +1,11 @@
1
+ /**
2
+ * Path validation shared by the Hono router: OpenAPI route templates are
3
+ * converted to Hono patterns, and the mount prefix is checked before use.
4
+ */
5
+ /**
6
+ * Convert an OpenAPI template such as `/items/{id}` to a Hono pattern such as
7
+ * `/items/:id`. The reserved `/sendproof` namespace cannot be registered.
8
+ */
9
+ export declare function routePath(template: string): string;
10
+ /** Validate the optional mount prefix; the empty string means the router is mounted at the root. */
11
+ export declare function assertBasePath(basePath: string): void;
package/dist/paths.js ADDED
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Path validation shared by the Hono router: OpenAPI route templates are
3
+ * converted to Hono patterns, and the mount prefix is checked before use.
4
+ */
5
+ const segment = String.raw `(?:[a-zA-Z0-9._~%-]+|\{[a-zA-Z_][a-zA-Z0-9_]*\})`;
6
+ const templatePattern = new RegExp(String.raw `^/${segment}(?:/${segment})*$`);
7
+ const basePathPattern = /^\/[a-zA-Z0-9._~-]+(?:\/[a-zA-Z0-9._~-]+)*$/;
8
+ /** Reject `.` and `..` segments, which would let a template escape its mount. */
9
+ const hasDotSegment = (path) => path.split('/').some(part => part === '.' || part === '..');
10
+ /**
11
+ * Convert an OpenAPI template such as `/items/{id}` to a Hono pattern such as
12
+ * `/items/:id`. The reserved `/sendproof` namespace cannot be registered.
13
+ */
14
+ export function routePath(template) {
15
+ if (!templatePattern.test(template) || hasDotSegment(template) || /^\/sendproof(?:\/|$)/i.test(template)) {
16
+ throw new TypeError('Use an OpenAPI route template such as /items/{id}.');
17
+ }
18
+ return template.replace(/\{([^{}]+)\}/g, ':$1');
19
+ }
20
+ /** Validate the optional mount prefix; the empty string means the router is mounted at the root. */
21
+ export function assertBasePath(basePath) {
22
+ if (basePath && (!basePathPattern.test(basePath) || hasDotSegment(basePath))) {
23
+ throw new TypeError('basePath must be an absolute path without a trailing slash.');
24
+ }
25
+ }
@@ -0,0 +1,10 @@
1
+ import type { TransportResponse } from '@sendproof/core';
2
+ /** Marker header set by the internal router's not-found handler to tell "no such operation" from a handler's own 404. */
3
+ export declare const unmatchedHeader = "x-sendproof-unmatched";
4
+ /** Convert a protocol response from the core into a fetch `Response`. */
5
+ export declare function toResponse(answer: TransportResponse, method: string): Response;
6
+ /**
7
+ * Read a Preview response, abandoning the stream as soon as it exceeds `limit`
8
+ * bytes so the remaining body is never buffered.
9
+ */
10
+ export declare function captureResponse(response: Response, limit: number): Promise<TransportResponse>;
@@ -0,0 +1,40 @@
1
+ /** Response statuses that must not carry a body. */
2
+ const bodyless = new Set([204, 205, 304]);
3
+ /** Marker header set by the internal router's not-found handler to tell "no such operation" from a handler's own 404. */
4
+ export const unmatchedHeader = 'x-sendproof-unmatched';
5
+ /** Convert a protocol response from the core into a fetch `Response`. */
6
+ export function toResponse(answer, method) {
7
+ const headers = new Headers();
8
+ for (const [name, value] of Object.entries(answer.headers)) {
9
+ if (value === undefined)
10
+ continue;
11
+ for (const item of Array.isArray(value) ? value : [value])
12
+ headers.append(name, String(item));
13
+ }
14
+ const body = method === 'HEAD' || bodyless.has(answer.status) ? null : new Uint8Array(answer.body);
15
+ return new Response(body, { status: answer.status, headers });
16
+ }
17
+ /**
18
+ * Read a Preview response, abandoning the stream as soon as it exceeds `limit`
19
+ * bytes so the remaining body is never buffered.
20
+ */
21
+ export async function captureResponse(response, limit) {
22
+ const headers = Object.fromEntries(response.headers);
23
+ if (!response.body)
24
+ return { status: response.status, headers, body: Buffer.alloc(0) };
25
+ const reader = response.body.getReader();
26
+ const chunks = [];
27
+ let size = 0;
28
+ for (;;) {
29
+ const { value, done } = await reader.read();
30
+ if (done)
31
+ break;
32
+ size += value.byteLength;
33
+ if (size > limit) {
34
+ void reader.cancel().catch(() => { });
35
+ return { status: response.status, headers, body: Buffer.alloc(0), exceeded: true };
36
+ }
37
+ chunks.push(Buffer.from(value));
38
+ }
39
+ return { status: response.status, headers, body: Buffer.concat(chunks, size) };
40
+ }
package/package.json CHANGED
@@ -1,6 +1,47 @@
1
1
  {
2
2
  "name": "@sendproof/hono",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-alpha.1",
4
+ "description": "Sendproof integration for Hono",
5
+ "license": "MIT",
6
+ "keywords": [
7
+ "hono",
8
+ "openapi",
9
+ "swagger-ui",
10
+ "api-testing",
11
+ "sendproof"
12
+ ],
13
+ "type": "module",
14
+ "exports": {
15
+ ".": {
16
+ "types": "./dist/index.d.ts",
17
+ "default": "./dist/index.js"
18
+ }
19
+ },
20
+ "types": "./dist/index.d.ts",
21
+ "files": [
22
+ "dist"
23
+ ],
24
+ "engines": {
25
+ "node": ">=22.14"
26
+ },
27
+ "dependencies": {
28
+ "@sendproof/core": "0.1.0-alpha.1"
29
+ },
30
+ "peerDependencies": {
31
+ "hono": "^4.0.0"
32
+ },
33
+ "author": "Sendproof contributors",
34
+ "homepage": "https://github.com/mprync/sendproof/tree/main/adapters/node/hono#readme",
35
+ "repository": {
36
+ "type": "git",
37
+ "url": "git+https://github.com/mprync/sendproof.git",
38
+ "directory": "adapters/node/hono"
39
+ },
40
+ "bugs": {
41
+ "url": "https://github.com/mprync/sendproof/issues"
42
+ },
43
+ "publishConfig": {
44
+ "access": "public",
45
+ "provenance": true
46
+ }
47
+ }