@ts-pf/server-http 0.2.1 → 0.3.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 +21 -0
- package/README.md +9 -1
- package/dist/handler.d.ts +61 -2
- package/dist/handler.d.ts.map +1 -1
- package/dist/handler.js +161 -75
- package/dist/handler.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +8 -5
- package/skills/ts-pf-server-http/SKILL.md +32 -2
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 ts-pf 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
|
@@ -12,9 +12,17 @@ import { CORSPlugin, FetchHandler } from '@ts-pf/server-http'
|
|
|
12
12
|
|
|
13
13
|
const handler = new FetchHandler(app, {
|
|
14
14
|
plugins: [new CORSPlugin()],
|
|
15
|
-
|
|
15
|
+
// Default key dedupes every unary call, writes included. Pass key to restrict to reads.
|
|
16
|
+
interceptors: applyPlugins([new DedupePlugin({ key: readKey })]),
|
|
16
17
|
})
|
|
17
18
|
const result = await handler.handle(request, { prefix: '/rpc', context: { db } })
|
|
18
19
|
```
|
|
19
20
|
|
|
21
|
+
Options: `codec`, `plugins`, `interceptors`, `validation`, and `onError(error, { request, path, context })` (type `FetchHandlerOnError`). Without `onError`, unknown throws and `INTERNAL` errors are logged with `console.error`; passing it replaces that logging. Mid-stream errors are in-band codec items and reach neither. A JSON envelope object with keys but no `input` key is `400 BAD_REQUEST` from the codec; `{}` and `{"input":null}` still mean no input. A request `x-ts-pf-protocol` header that is present and not `1` is `400 BAD_REQUEST` `Unsupported protocol version` before the body is read; a missing header is accepted.
|
|
22
|
+
|
|
20
23
|
Do not import this package from `@ts-pf/client-http`.
|
|
24
|
+
|
|
25
|
+
## API
|
|
26
|
+
|
|
27
|
+
- `FetchHandler`, `FetchHandlerOnError`, `HandleResult`, `HandlerPlugin`
|
|
28
|
+
- `CORSPlugin`, `RequestLimitPlugin`, `RequestHeadersPlugin`, `ResponseHeadersPlugin`
|
package/dist/handler.d.ts
CHANGED
|
@@ -8,24 +8,83 @@ export type HandleResult = {
|
|
|
8
8
|
matched: true;
|
|
9
9
|
response: Response;
|
|
10
10
|
};
|
|
11
|
+
/** `FetchHandler` `onError` option. `context` is `unknown` like `HandlerPlugin`. */
|
|
12
|
+
export type FetchHandlerOnError = (error: unknown, info: {
|
|
13
|
+
request: Request;
|
|
14
|
+
path: readonly string[];
|
|
15
|
+
context: unknown;
|
|
16
|
+
}) => void | Promise<void>;
|
|
17
|
+
/**
|
|
18
|
+
* `TCtx` is inferred from the router's context brand (the `$context<C>()`
|
|
19
|
+
* type behind `impl.router()`), so `handle(request, { context })` is checked
|
|
20
|
+
* against it. A tree not produced by `impl.router()` infers `unknown`. An
|
|
21
|
+
* explicit `new FetchHandler<AppCtx>(app)` is still accepted when `AppCtx`
|
|
22
|
+
* satisfies the router's context.
|
|
23
|
+
*/
|
|
11
24
|
export declare class FetchHandler<TCtx = unknown> {
|
|
12
25
|
private readonly router;
|
|
13
26
|
private readonly codec;
|
|
14
27
|
private readonly plugins;
|
|
15
28
|
private readonly interceptors;
|
|
16
29
|
private readonly validation;
|
|
17
|
-
|
|
30
|
+
private readonly onError;
|
|
31
|
+
constructor(router: ImplementedRouter<unknown, TCtx>, options?: {
|
|
18
32
|
codec?: RpcCodec;
|
|
19
33
|
plugins?: HandlerPlugin[];
|
|
20
34
|
interceptors?: readonly CallInterceptor[];
|
|
21
35
|
validation?: ProcedureValidation;
|
|
36
|
+
/**
|
|
37
|
+
* Side-effect hook for every error that becomes an error response.
|
|
38
|
+
* Receives the original thrown value (before an unknown throw is
|
|
39
|
+
* mapped to `INTERNAL`), including `METHOD_NOT_ALLOWED`, `NOT_FOUND`,
|
|
40
|
+
* codec `BAD_REQUEST`, and `VALIDATION`. Runs after every
|
|
41
|
+
* `HandlerPlugin.onError` (array order) and before the failure is
|
|
42
|
+
* encoded. It cannot replace the response. A `Response` returned from
|
|
43
|
+
* `HandlerPlugin.onRequest` is not an error to this hook, and a throw
|
|
44
|
+
* from `onError` itself rejects `handle()`. Errors thrown after a
|
|
45
|
+
* streamed response has started are written in-band by the codec
|
|
46
|
+
* (unknown throws as `INTERNAL`) and do not reach this hook or the
|
|
47
|
+
* default log.
|
|
48
|
+
*
|
|
49
|
+
* When omitted, `FetchHandler` logs with `console.error`: unknown
|
|
50
|
+
* (non-`PFError`) throws, and `INTERNAL` `PFError`s (an output schema
|
|
51
|
+
* failure under `validation.output`, invalid declared error `data`, or
|
|
52
|
+
* an explicit `INTERNAL` throw). Declared and other protocol errors are
|
|
53
|
+
* not logged. Passing `onError` replaces that default logging entirely.
|
|
54
|
+
*/
|
|
55
|
+
onError?: FetchHandlerOnError;
|
|
22
56
|
});
|
|
57
|
+
/**
|
|
58
|
+
* The call pipeline (see the ts-pf skill, "Call pipeline"): each numbered
|
|
59
|
+
* step is a method below. Any throw from steps 0–5, including
|
|
60
|
+
* `METHOD_NOT_ALLOWED`, `NOT_FOUND`, codec `BAD_REQUEST`, and an
|
|
61
|
+
* `onResponse` plugin on the success path, takes the step-6 error path.
|
|
62
|
+
*/
|
|
23
63
|
handle(request: Request, opts: {
|
|
24
64
|
prefix: string;
|
|
25
65
|
context: TCtx | ((req: Request) => TCtx | Promise<TCtx>);
|
|
26
66
|
}): Promise<HandleResult>;
|
|
27
|
-
|
|
67
|
+
/** Step 0. Returns a plugin's short-circuit `Response`; `state.request` holds the latest wrap. */
|
|
68
|
+
private applyOnRequest;
|
|
69
|
+
/**
|
|
70
|
+
* Step 1, lookup third. Prefix matched but no procedure at `path`:
|
|
71
|
+
* `NOT_FOUND` (no call interceptors). Runs before decode, so an unknown
|
|
72
|
+
* path never buffers or parses the body.
|
|
73
|
+
*/
|
|
74
|
+
private lookup;
|
|
75
|
+
/** Step 3. Each `onContext` may replace the context (header bags). */
|
|
76
|
+
private applyOnContext;
|
|
77
|
+
/** Step 4. `runProcedure` with the request signal, interceptors, and validation. */
|
|
78
|
+
private run;
|
|
79
|
+
/** Step 5. */
|
|
28
80
|
private successResponse;
|
|
81
|
+
/** Step 6, side effects: `HandlerPlugin.onError` in array order, then `onError` or the default log. */
|
|
82
|
+
private reportError;
|
|
83
|
+
private logError;
|
|
84
|
+
/** Step 6, response: `toWireError` maps an unknown throw to `INTERNAL`; its status follows. */
|
|
29
85
|
private errorResponse;
|
|
86
|
+
/** Step 7. Every matched `Response` (success, 405, errors, short-circuit) passes `onResponse`. */
|
|
87
|
+
private respond;
|
|
88
|
+
private applyOnResponse;
|
|
30
89
|
}
|
|
31
90
|
//# sourceMappingURL=handler.d.ts.map
|
package/dist/handler.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA,OAAO,
|
|
1
|
+
{"version":3,"file":"handler.d.ts","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA,OAAO,EAOL,KAAK,QAAQ,EAEd,MAAM,aAAa,CAAA;AAOpB,OAAO,EACL,KAAK,eAAe,EACpB,KAAK,iBAAiB,EAEtB,KAAK,mBAAmB,EAGzB,MAAM,eAAe,CAAA;AACtB,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AAEjD,MAAM,MAAM,YAAY,GACpB;IAAE,OAAO,EAAE,KAAK,CAAC;IAAC,QAAQ,CAAC,EAAE,SAAS,CAAA;CAAE,GACxC;IAAE,OAAO,EAAE,IAAI,CAAC;IAAC,QAAQ,EAAE,QAAQ,CAAA;CAAE,CAAA;AAEzC,oFAAoF;AACpF,MAAM,MAAM,mBAAmB,GAAG,CAChC,KAAK,EAAE,OAAO,EACd,IAAI,EAAE;IAAE,OAAO,EAAE,OAAO,CAAC;IAAC,IAAI,EAAE,SAAS,MAAM,EAAE,CAAC;IAAC,OAAO,EAAE,OAAO,CAAA;CAAE,KAClE,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAA;AAazB;;;;;;GAMG;AACH,qBAAa,YAAY,CAAC,IAAI,GAAG,OAAO;IAQpC,OAAO,CAAC,QAAQ,CAAC,MAAM;IAPzB,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAU;IAChC,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAiB;IACzC,OAAO,CAAC,QAAQ,CAAC,YAAY,CAA4B;IACzD,OAAO,CAAC,QAAQ,CAAC,UAAU,CAAiC;IAC5D,OAAO,CAAC,QAAQ,CAAC,OAAO,CAAiC;gBAGtC,MAAM,EAAE,iBAAiB,CAAC,OAAO,EAAE,IAAI,CAAC,EACzD,OAAO,CAAC,EAAE;QACR,KAAK,CAAC,EAAE,QAAQ,CAAA;QAChB,OAAO,CAAC,EAAE,aAAa,EAAE,CAAA;QACzB,YAAY,CAAC,EAAE,SAAS,eAAe,EAAE,CAAA;QACzC,UAAU,CAAC,EAAE,mBAAmB,CAAA;QAChC;;;;;;;;;;;;;;;;;;WAkBG;QACH,OAAO,CAAC,EAAE,mBAAmB,CAAA;KAC9B;IASH;;;;;OAKG;IACG,MAAM,CACV,OAAO,EAAE,OAAO,EAChB,IAAI,EAAE;QACJ,MAAM,EAAE,MAAM,CAAA;QACd,OAAO,EAAE,IAAI,GAAG,CAAC,CAAC,GAAG,EAAE,OAAO,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,CAAC,CAAA;KACzD,GACA,OAAO,CAAC,YAAY,CAAC;IAkCxB,kGAAkG;YACpF,cAAc;IAe5B;;;;OAIG;IACH,OAAO,CAAC,MAAM;IAWd,sEAAsE;YACxD,cAAc;IAY5B,oFAAoF;IACpF,OAAO,CAAC,GAAG;IAeX,cAAc;YACA,eAAe;IAI7B,uGAAuG;YACzF,WAAW;IAuBzB,OAAO,CAAC,QAAQ;IAmBhB,+FAA+F;YACjF,aAAa;IAO3B,kGAAkG;YACpF,OAAO;YAcP,eAAe;CAkB9B"}
|
package/dist/handler.js
CHANGED
|
@@ -1,102 +1,164 @@
|
|
|
1
|
-
import { httpStatus, JSONCodec, PROTOCOL_HEADER, parseProcedurePath, } from '@ts-pf/http';
|
|
2
|
-
import { isPFError, PFError, PROTOCOL_VERSION } from '@ts-pf/protocol';
|
|
1
|
+
import { httpStatus, JSONCodec, PROTOCOL_HEADER, PROTOCOL_HTTP_STATUS, parseProcedurePath, } from '@ts-pf/http';
|
|
2
|
+
import { isPFError, PFError, PROTOCOL_VERSION, toWireError, } from '@ts-pf/protocol';
|
|
3
3
|
import { lookupProcedure, runProcedure, } from '@ts-pf/server';
|
|
4
|
+
/**
|
|
5
|
+
* `TCtx` is inferred from the router's context brand (the `$context<C>()`
|
|
6
|
+
* type behind `impl.router()`), so `handle(request, { context })` is checked
|
|
7
|
+
* against it. A tree not produced by `impl.router()` infers `unknown`. An
|
|
8
|
+
* explicit `new FetchHandler<AppCtx>(app)` is still accepted when `AppCtx`
|
|
9
|
+
* satisfies the router's context.
|
|
10
|
+
*/
|
|
4
11
|
export class FetchHandler {
|
|
5
12
|
router;
|
|
6
13
|
codec;
|
|
7
14
|
plugins;
|
|
8
15
|
interceptors;
|
|
9
16
|
validation;
|
|
17
|
+
onError;
|
|
10
18
|
constructor(router, options) {
|
|
11
19
|
this.router = router;
|
|
12
20
|
this.codec = options?.codec ?? new JSONCodec();
|
|
13
21
|
this.plugins = options?.plugins ?? [];
|
|
14
22
|
this.interceptors = options?.interceptors ?? [];
|
|
15
23
|
this.validation = options?.validation;
|
|
24
|
+
this.onError = options?.onError;
|
|
16
25
|
}
|
|
26
|
+
/**
|
|
27
|
+
* The call pipeline (see the ts-pf skill, "Call pipeline"): each numbered
|
|
28
|
+
* step is a method below. Any throw from steps 0–5, including
|
|
29
|
+
* `METHOD_NOT_ALLOWED`, `NOT_FOUND`, codec `BAD_REQUEST`, and an
|
|
30
|
+
* `onResponse` plugin on the success path, takes the step-6 error path.
|
|
31
|
+
*/
|
|
17
32
|
async handle(request, opts) {
|
|
18
33
|
const url = new URL(request.url);
|
|
19
34
|
const path = parseProcedurePath(url.pathname, opts.prefix);
|
|
20
35
|
if (path === null) {
|
|
21
36
|
return { matched: false };
|
|
22
37
|
}
|
|
23
|
-
|
|
24
|
-
let context;
|
|
38
|
+
const state = { request, context: undefined };
|
|
25
39
|
try {
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
29
|
-
|
|
30
|
-
matched: true,
|
|
31
|
-
response: await this.applyOnResponse(inbound, result, context),
|
|
32
|
-
};
|
|
33
|
-
}
|
|
34
|
-
if (result instanceof Request) {
|
|
35
|
-
inbound = result;
|
|
36
|
-
}
|
|
40
|
+
// 0. HandlerPlugin.onRequest: wrap the request or short-circuit (CORS preflight)
|
|
41
|
+
const shortCircuit = await this.applyOnRequest(state);
|
|
42
|
+
if (shortCircuit !== undefined) {
|
|
43
|
+
return await this.respond(state, shortCircuit);
|
|
37
44
|
}
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
56
|
-
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
if (next !== undefined) {
|
|
65
|
-
context = next;
|
|
66
|
-
}
|
|
67
|
-
}
|
|
68
|
-
const runOpts = { signal: inbound.signal };
|
|
69
|
-
if (this.interceptors.length > 0) {
|
|
70
|
-
runOpts.interceptors = this.interceptors;
|
|
45
|
+
// 1. method, then protocol version, then procedure: a 405, 400, or 404
|
|
46
|
+
// answers before the body is read
|
|
47
|
+
assertPost(state.request);
|
|
48
|
+
assertProtocolVersion(state.request);
|
|
49
|
+
const procedure = this.lookup(path);
|
|
50
|
+
// 2. decode the body
|
|
51
|
+
const decoded = await this.codec.decodeRequest(bodySource(state.request));
|
|
52
|
+
// 3. context factory, then HandlerPlugin.onContext
|
|
53
|
+
state.context = await resolveContext(state.request, opts.context);
|
|
54
|
+
await this.applyOnContext(state);
|
|
55
|
+
// 4–5. call-interceptor onion around runProcedure, then encode
|
|
56
|
+
const output = await this.run(procedure, decoded.input, state);
|
|
57
|
+
return await this.respond(state, await this.successResponse(output));
|
|
58
|
+
}
|
|
59
|
+
catch (error) {
|
|
60
|
+
// 6. HandlerPlugin.onError, then onError or the default log, then encode the failure
|
|
61
|
+
await this.reportError(error, state, path);
|
|
62
|
+
return this.respond(state, await this.errorResponse(error));
|
|
63
|
+
}
|
|
64
|
+
}
|
|
65
|
+
/** Step 0. Returns a plugin's short-circuit `Response`; `state.request` holds the latest wrap. */
|
|
66
|
+
async applyOnRequest(state) {
|
|
67
|
+
for (const plugin of this.plugins) {
|
|
68
|
+
const result = await plugin.onRequest?.({ request: state.request });
|
|
69
|
+
if (result instanceof Response) {
|
|
70
|
+
return result;
|
|
71
71
|
}
|
|
72
|
-
if (
|
|
73
|
-
|
|
72
|
+
if (result instanceof Request) {
|
|
73
|
+
state.request = result;
|
|
74
74
|
}
|
|
75
|
-
const output = await runProcedure(procedure, decoded.input, context, runOpts);
|
|
76
|
-
const response = await this.successResponse(output);
|
|
77
|
-
return {
|
|
78
|
-
matched: true,
|
|
79
|
-
response: await this.applyOnResponse(inbound, response, context),
|
|
80
|
-
};
|
|
81
75
|
}
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
76
|
+
return undefined;
|
|
77
|
+
}
|
|
78
|
+
/**
|
|
79
|
+
* Step 1, lookup third. Prefix matched but no procedure at `path`:
|
|
80
|
+
* `NOT_FOUND` (no call interceptors). Runs before decode, so an unknown
|
|
81
|
+
* path never buffers or parses the body.
|
|
82
|
+
*/
|
|
83
|
+
lookup(path) {
|
|
84
|
+
const procedure = lookupProcedure(this.router, path);
|
|
85
|
+
if (!procedure) {
|
|
86
|
+
throw new PFError({
|
|
87
|
+
code: 'NOT_FOUND',
|
|
88
|
+
message: 'Procedure not found',
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
return procedure;
|
|
92
|
+
}
|
|
93
|
+
/** Step 3. Each `onContext` may replace the context (header bags). */
|
|
94
|
+
async applyOnContext(state) {
|
|
95
|
+
for (const plugin of this.plugins) {
|
|
96
|
+
const next = await plugin.onContext?.({
|
|
97
|
+
request: state.request,
|
|
98
|
+
context: state.context,
|
|
99
|
+
});
|
|
100
|
+
if (next !== undefined) {
|
|
101
|
+
state.context = next;
|
|
87
102
|
}
|
|
88
|
-
const failure = isPFError(error)
|
|
89
|
-
? error
|
|
90
|
-
: new PFError({
|
|
91
|
-
code: 'INTERNAL',
|
|
92
|
-
message: 'Internal server error',
|
|
93
|
-
});
|
|
94
|
-
return {
|
|
95
|
-
matched: true,
|
|
96
|
-
response: await this.applyOnResponse(inbound, await this.errorResponse(failure), context),
|
|
97
|
-
};
|
|
98
103
|
}
|
|
99
104
|
}
|
|
105
|
+
/** Step 4. `runProcedure` with the request signal, interceptors, and validation. */
|
|
106
|
+
run(procedure, input, state) {
|
|
107
|
+
const runOpts = { signal: state.request.signal };
|
|
108
|
+
if (this.interceptors.length > 0) {
|
|
109
|
+
runOpts.interceptors = this.interceptors;
|
|
110
|
+
}
|
|
111
|
+
if (this.validation) {
|
|
112
|
+
runOpts.validation = this.validation;
|
|
113
|
+
}
|
|
114
|
+
return runProcedure(procedure, input, state.context, runOpts);
|
|
115
|
+
}
|
|
116
|
+
/** Step 5. */
|
|
117
|
+
async successResponse(output) {
|
|
118
|
+
return encodedResponse(await this.codec.encodeSuccess(output), 200);
|
|
119
|
+
}
|
|
120
|
+
/** Step 6, side effects: `HandlerPlugin.onError` in array order, then `onError` or the default log. */
|
|
121
|
+
async reportError(error, state, path) {
|
|
122
|
+
for (const plugin of this.plugins) {
|
|
123
|
+
await plugin.onError?.(state.context === undefined
|
|
124
|
+
? { request: state.request, error }
|
|
125
|
+
: { request: state.request, error, context: state.context });
|
|
126
|
+
}
|
|
127
|
+
if (this.onError) {
|
|
128
|
+
await this.onError(error, {
|
|
129
|
+
request: state.request,
|
|
130
|
+
path,
|
|
131
|
+
context: state.context,
|
|
132
|
+
});
|
|
133
|
+
return;
|
|
134
|
+
}
|
|
135
|
+
this.logError(error, path);
|
|
136
|
+
}
|
|
137
|
+
logError(error, path) {
|
|
138
|
+
const where = `"${path.join('/')}"`;
|
|
139
|
+
if (!isPFError(error)) {
|
|
140
|
+
console.error(`[ts-pf/server-http] Unhandled error in ${where}:`, error);
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
if (error.code !== 'INTERNAL') {
|
|
144
|
+
return;
|
|
145
|
+
}
|
|
146
|
+
const causes = this.validation?.output === true
|
|
147
|
+
? 'output schema failure, invalid declared error data, or an INTERNAL throw'
|
|
148
|
+
: 'invalid declared error data or an INTERNAL throw';
|
|
149
|
+
console.error(`[ts-pf/server-http] INTERNAL error in ${where} (${causes}):`, error);
|
|
150
|
+
}
|
|
151
|
+
/** Step 6, response: `toWireError` maps an unknown throw to `INTERNAL`; its status follows. */
|
|
152
|
+
async errorResponse(error) {
|
|
153
|
+
return encodedResponse(await this.codec.encodeFailure(toWireError(error)), isPFError(error) ? httpStatus(error) : PROTOCOL_HTTP_STATUS.INTERNAL);
|
|
154
|
+
}
|
|
155
|
+
/** Step 7. Every matched `Response` (success, 405, errors, short-circuit) passes `onResponse`. */
|
|
156
|
+
async respond(state, response) {
|
|
157
|
+
return {
|
|
158
|
+
matched: true,
|
|
159
|
+
response: await this.applyOnResponse(state.request, response, state.context),
|
|
160
|
+
};
|
|
161
|
+
}
|
|
100
162
|
async applyOnResponse(request, response, context) {
|
|
101
163
|
let current = response;
|
|
102
164
|
for (const plugin of this.plugins) {
|
|
@@ -109,13 +171,37 @@ export class FetchHandler {
|
|
|
109
171
|
}
|
|
110
172
|
return current;
|
|
111
173
|
}
|
|
112
|
-
|
|
113
|
-
|
|
174
|
+
}
|
|
175
|
+
/** Step 1, method third. Thrown inside the pipeline so plugins and `onError` see 405s too. */
|
|
176
|
+
function assertPost(request) {
|
|
177
|
+
if (request.method !== 'POST') {
|
|
178
|
+
throw new PFError({
|
|
179
|
+
code: 'METHOD_NOT_ALLOWED',
|
|
180
|
+
message: 'Method not allowed',
|
|
181
|
+
});
|
|
114
182
|
}
|
|
115
|
-
|
|
116
|
-
|
|
183
|
+
}
|
|
184
|
+
/**
|
|
185
|
+
* Step 1, version third. An absent `x-ts-pf-protocol` is accepted (curl,
|
|
186
|
+
* non-ts-pf clients). A present value other than the supported major (after
|
|
187
|
+
* trimming ASCII whitespace) is the same `BAD_REQUEST` the message handshake
|
|
188
|
+
* answers, so a future-major client gets a diagnostic instead of a v1 decode.
|
|
189
|
+
*/
|
|
190
|
+
function assertProtocolVersion(request) {
|
|
191
|
+
const version = request.headers.get(PROTOCOL_HEADER);
|
|
192
|
+
if (version !== null && version.trim() !== PROTOCOL_VERSION) {
|
|
193
|
+
throw new PFError({
|
|
194
|
+
code: 'BAD_REQUEST',
|
|
195
|
+
message: 'Unsupported protocol version',
|
|
196
|
+
});
|
|
117
197
|
}
|
|
118
198
|
}
|
|
199
|
+
/** Step 3, factory half: a value or a `(req) => ctx` function. */
|
|
200
|
+
async function resolveContext(request, context) {
|
|
201
|
+
return typeof context === 'function'
|
|
202
|
+
? await context(request)
|
|
203
|
+
: context;
|
|
204
|
+
}
|
|
119
205
|
function bodySource(request) {
|
|
120
206
|
return {
|
|
121
207
|
contentType: request.headers.get('content-type'),
|
package/dist/handler.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"handler.js","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,SAAS,EACT,eAAe,EACf,kBAAkB,GAInB,MAAM,aAAa,CAAA;AACpB,OAAO,
|
|
1
|
+
{"version":3,"file":"handler.js","sourceRoot":"","sources":["../src/handler.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,UAAU,EACV,SAAS,EACT,eAAe,EACf,oBAAoB,EACpB,kBAAkB,GAInB,MAAM,aAAa,CAAA;AACpB,OAAO,EACL,SAAS,EACT,OAAO,EACP,gBAAgB,EAChB,WAAW,GACZ,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAGL,eAAe,EAGf,YAAY,GACb,MAAM,eAAe,CAAA;AAwBtB;;;;;;GAMG;AACH,MAAM,OAAO,YAAY;IAQJ;IAPF,KAAK,CAAU;IACf,OAAO,CAAiB;IACxB,YAAY,CAA4B;IACx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OAAO,CAAC,IAAI,YAAY,QAAQ,CAAC,EAAE,CAAC;QACxC,OAAO,CAAC,GAAG,CAAC,cAAc,EAAE,OAAO,CAAC,WAAW,CAAC,CAAA;IAClD,CAAC;IACD,IAAI,OAAO,CAAC,IAAI,YAAY,cAAc,EAAE,CAAC;QAC3C,OAAO,CAAC,GAAG,CAAC,eAAe,EAAE,wBAAwB,CAAC,CAAA;QACtD,OAAO,CAAC,GAAG,CAAC,mBAAmB,EAAE,IAAI,CAAC,CAAA;IACxC,CAAC;IACD,OAAO,IAAI,QAAQ,CAAC,OAAO,CAAC,IAAI,EAAE,EAAE,MAAM,EAAE,OAAO,EAAE,CAAC,CAAA;AACxD,CAAC"}
|
package/dist/index.d.ts
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { type CORSOrigin, CORSPlugin, type CORSPluginOptions, } from './cors-plugin.js';
|
|
2
|
-
export { FetchHandler, type HandleResult } from './handler.js';
|
|
2
|
+
export { FetchHandler, type FetchHandlerOnError, type HandleResult, } from './handler.js';
|
|
3
3
|
export type { HandlerPlugin } from './plugins.js';
|
|
4
4
|
export { RequestHeadersPlugin, type RequestHeadersPluginContext, } from './request-headers-plugin.js';
|
|
5
5
|
export { RequestLimitPlugin, type RequestLimitPluginOptions, } from './request-limit-plugin.js';
|
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,UAAU,EACf,UAAU,EACV,KAAK,iBAAiB,GACvB,MAAM,kBAAkB,CAAA;AACzB,OAAO,
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,UAAU,EACf,UAAU,EACV,KAAK,iBAAiB,GACvB,MAAM,kBAAkB,CAAA;AACzB,OAAO,EACL,YAAY,EACZ,KAAK,mBAAmB,EACxB,KAAK,YAAY,GAClB,MAAM,cAAc,CAAA;AACrB,YAAY,EAAE,aAAa,EAAE,MAAM,cAAc,CAAA;AACjD,OAAO,EACL,oBAAoB,EACpB,KAAK,2BAA2B,GACjC,MAAM,6BAA6B,CAAA;AACpC,OAAO,EACL,kBAAkB,EAClB,KAAK,yBAAyB,GAC/B,MAAM,2BAA2B,CAAA;AAClC,OAAO,EACL,qBAAqB,EACrB,KAAK,4BAA4B,GAClC,MAAM,8BAA8B,CAAA"}
|
package/dist/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
export { CORSPlugin, } from './cors-plugin.js';
|
|
2
|
-
export { FetchHandler } from './handler.js';
|
|
2
|
+
export { FetchHandler, } from './handler.js';
|
|
3
3
|
export { RequestHeadersPlugin, } from './request-headers-plugin.js';
|
|
4
4
|
export { RequestLimitPlugin, } from './request-limit-plugin.js';
|
|
5
5
|
export { ResponseHeadersPlugin, } from './response-headers-plugin.js';
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,UAAU,GAEX,MAAM,kBAAkB,CAAA;AACzB,OAAO,
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,UAAU,GAEX,MAAM,kBAAkB,CAAA;AACzB,OAAO,EACL,YAAY,GAGb,MAAM,cAAc,CAAA;AAErB,OAAO,EACL,oBAAoB,GAErB,MAAM,6BAA6B,CAAA;AACpC,OAAO,EACL,kBAAkB,GAEnB,MAAM,2BAA2B,CAAA;AAClC,OAAO,EACL,qBAAqB,GAEtB,MAAM,8BAA8B,CAAA"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@ts-pf/server-http",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.3.1",
|
|
4
4
|
"description": "Fetch Request/Response handler and HTTP HandlerPlugins",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ts-pf",
|
|
@@ -16,6 +16,9 @@
|
|
|
16
16
|
"json-rpc"
|
|
17
17
|
],
|
|
18
18
|
"license": "MIT",
|
|
19
|
+
"engines": {
|
|
20
|
+
"node": ">=22"
|
|
21
|
+
},
|
|
19
22
|
"repository": {
|
|
20
23
|
"type": "git",
|
|
21
24
|
"url": "git+https://github.com/crobinson42/ts-pf.git",
|
|
@@ -47,12 +50,12 @@
|
|
|
47
50
|
"lint": "biome check src tests"
|
|
48
51
|
},
|
|
49
52
|
"dependencies": {
|
|
50
|
-
"@ts-pf/http": "0.
|
|
51
|
-
"@ts-pf/protocol": "0.
|
|
52
|
-
"@ts-pf/server": "0.
|
|
53
|
+
"@ts-pf/http": "0.2.0",
|
|
54
|
+
"@ts-pf/protocol": "0.2.0",
|
|
55
|
+
"@ts-pf/server": "0.4.1"
|
|
53
56
|
},
|
|
54
57
|
"devDependencies": {
|
|
55
|
-
"@ts-pf/contract": "0.1
|
|
58
|
+
"@ts-pf/contract": "0.2.1",
|
|
56
59
|
"zod": "^4.0.0"
|
|
57
60
|
}
|
|
58
61
|
}
|
|
@@ -22,19 +22,49 @@ const handler = new FetchHandler(app, {
|
|
|
22
22
|
new CORSPlugin({ origin: ['https://app.example.com'] }),
|
|
23
23
|
new RequestLimitPlugin({ maxBodySize: 1024 * 1024 }),
|
|
24
24
|
],
|
|
25
|
-
|
|
25
|
+
// Default key dedupes every unary call, writes included. Pass key to restrict to reads.
|
|
26
|
+
interceptors: applyPlugins([new DedupePlugin({ key: readKey })]),
|
|
26
27
|
})
|
|
27
28
|
|
|
28
29
|
const result = await handler.handle(request, { prefix: '/rpc', context: { db } })
|
|
30
|
+
```
|
|
31
|
+
|
|
32
|
+
Inside your request handler, fall through on a prefix miss:
|
|
33
|
+
|
|
34
|
+
```ts no-check
|
|
29
35
|
if (!result.matched) return new Response('Not Found', { status: 404 })
|
|
30
36
|
return result.response
|
|
31
37
|
```
|
|
32
38
|
|
|
39
|
+
`new FetchHandler(app)` infers its context type from `app` (the `$context<C>()` behind `impl.router()`), so `handle(request, { context })` is checked against it and a factory gets `req: Request` for free: `context: (req) => ({ db, req })`. An explicit `new FetchHandler<AppCtx>(app)` still works when `AppCtx` satisfies the app's context. A tree not produced by `impl.router()` infers `unknown`; use `impl.router()`, or pick procedures into a second `impl.router()` call, to keep the check.
|
|
40
|
+
|
|
33
41
|
`plugins` is HTTP-only (`HandlerPlugin`). RPC call interceptors go on `{ interceptors }` from `@ts-pf/server`. `validation` is the same `ProcedureValidation` as `runProcedure`: input checks default on, output and stream output items run only with `{ validation: { output: true } }`. Set it on the constructor, not on `handle()`. `CORSPlugin` answers `OPTIONS` preflight.
|
|
34
42
|
|
|
43
|
+
## Errors
|
|
44
|
+
|
|
45
|
+
Unknown throws become `500 INTERNAL` with no stack on the wire. By default `FetchHandler` logs them with `console.error` (the original thrown value, tagged `[ts-pf/server-http]` with the procedure path). It also logs `INTERNAL` `PFError`s — an output schema failure under `validation.output`, invalid declared error `data`, or an explicit `INTERNAL` throw — naming those causes. Declared errors and every other protocol code (`VALIDATION`, `NOT_FOUND`, `BAD_REQUEST`, `METHOD_NOT_ALLOWED`, `PAYLOAD_TOO_LARGE`) are expected and are not logged.
|
|
46
|
+
|
|
47
|
+
Pass `onError` to route errors to your own logger. It receives the original error (before `INTERNAL` mapping) for every error response, runs after each `HandlerPlugin.onError`, cannot replace the response (a throw from it rejects `handle()`), and turns the default logging off:
|
|
48
|
+
|
|
49
|
+
```ts
|
|
50
|
+
import { FetchHandler } from '@ts-pf/server-http'
|
|
51
|
+
|
|
52
|
+
new FetchHandler(app, {
|
|
53
|
+
onError(error, { request, path, context }) {
|
|
54
|
+
logger.error({ err: error, path: path.join('/'), url: request.url })
|
|
55
|
+
},
|
|
56
|
+
})
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
Errors thrown after a streamed response has started (`StreamCodec` / `SseCodec` output) are written in-band by the codec as `INTERNAL` items; they do not reach `onError` or the default log.
|
|
60
|
+
|
|
61
|
+
`FetchHandler` checks the method, then the protocol version, then looks the procedure up, all before it reads the body. A non-POST is `405 METHOD_NOT_ALLOWED`. A request whose `x-ts-pf-protocol` header is present and not `1` (surrounding whitespace ignored) is `400 BAD_REQUEST` `Unsupported protocol version`; a missing header is accepted, so curl and non-ts-pf clients work as before. An unknown path under the prefix is `404 NOT_FOUND`. In all three cases the body is never buffered or decoded, whatever it holds (invalid JSON, a multipart upload, an oversized stream). `RequestLimitPlugin`'s `Content-Length` check runs earlier, in `onRequest`, so a declared oversize body is still `413 PAYLOAD_TOO_LARGE` on any path and for any method; only its streamed-body cap is skipped on a 404 because nothing reads the stream.
|
|
62
|
+
|
|
63
|
+
A JSON envelope object with keys but no `input` key (`{"id":1}` instead of `{"input":{"id":1}}`) is `400 BAD_REQUEST` `Request body must be {"input": ...}`, whichever codec carries it (plain JSON, the multipart `rpc` part, or a JSONL input line). `{}` and `{"input":null}` still mean no input.
|
|
64
|
+
|
|
35
65
|
## API
|
|
36
66
|
|
|
37
|
-
- `FetchHandler`, `HandleResult`, `HandlerPlugin`
|
|
67
|
+
- `FetchHandler`, `FetchHandlerOnError`, `HandleResult`, `HandlerPlugin`
|
|
38
68
|
- `CORSPlugin`, `RequestLimitPlugin`, `RequestHeadersPlugin`, `ResponseHeadersPlugin`
|
|
39
69
|
|
|
40
70
|
## Pair with
|