@webda/grpc 4.0.0-beta.3

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/.webda/cache ADDED
@@ -0,0 +1,4 @@
1
+ {
2
+ "sourceDigest": "ef8993a88f12bb10819b2de56248a24f",
3
+ "moduleDigest": "7e3441f5c16d35b42aeebaa1b3832f2b"
4
+ }
package/CHANGELOG.md ADDED
@@ -0,0 +1,54 @@
1
+ # Changelog
2
+
3
+ ## [4.0.0-beta.3](https://github.com/loopingz/webda.io/compare/grpc-v4.0.0-beta.1...grpc-v4.0.0-beta.3) (2026-10-05)
4
+
5
+
6
+ ### ⚠ BREAKING CHANGES
7
+
8
+ * **compiler:** the accessors, loadParameters and unserializer modules are removed. They wrote into the sources what webdac build now generates through @webda/content-mapper, or methods nothing calls. The unused webdac build --code flag is removed too.
9
+ * @webda/ts-plugin and the `tsc-esm` binary are removed, and applications now build with TypeScript 7.1. Generated code changes where TypeScript 6 was wrong, each verified against the shipped output:
10
+ - AuditEntry.timestamp, declared `number`, is no longer coerced to Date;
11
+ - AbstractOwnerModel no longer emits `new ModelLink(T)`, a ReferenceError
12
+ on first raw-uuid assignment;
13
+ - sample-app's `User extends WebdaUser` is now treated as a model (TS6's
14
+ base-chain guard was keyed on class name), so its relations are
15
+ initialised and coerced;
16
+ - imports use the specifier the author wrote, not monorepo-relative paths
17
+ that only resolve inside this repository;
18
+ - the emitted .d.ts is valid (TS6 referenced PrimaryKeyType unimported and
19
+ wrote BelongTo without its type argument).
20
+ A build that cannot write its module now fails; under TS6 a strict
21
+ file-naming violation was logged and the build still reported success.
22
+ * **compiler:** model relations are now `type: "string"` in Input, Output and Stored schemas instead of an object with no properties, and six services gain the `type` property they inherit from ServiceParameters. Anything generated from these schemas — API validation, client types — changes with them.
23
+
24
+ ### Features
25
+
26
+ * add build hooks ([97016bc](https://github.com/loopingz/webda.io/commit/97016bcb9a7becfa87793fa6cc408784487e7e07))
27
+ * add grpc module and sample-app webui ([#756](https://github.com/loopingz/webda.io/issues/756)) ([4a7df9a](https://github.com/loopingz/webda.io/commit/4a7df9aacff8ca5e16c57e5fa9f2e2f0dc786e2f))
28
+ * blog-system Binary/Binaries demo + e2e suite, with framework fixes ([#771](https://github.com/loopingz/webda.io/issues/771)) ([fe7e187](https://github.com/loopingz/webda.io/commit/fe7e18786744134fb29447a9f139689abbbd4950))
29
+ * build on TypeScript 7.1; delete @webda/ts-plugin and ts-patch ([0008e97](https://github.com/loopingz/webda.io/commit/0008e97919524d44528a8e3e89ee27cfaa2ee93b))
30
+ * **compiler:** generate schemas with @webda/content-mapper ([af3b7c5](https://github.com/loopingz/webda.io/commit/af3b7c5daa3ba239210be2af490850cde3460d84))
31
+ * **content-mapper:** TypeScript 7.1 content mapper package ([9b57565](https://github.com/loopingz/webda.io/commit/9b57565a467d83671559fa4e2411124a5ae51109))
32
+ * enhance debug panels ([#759](https://github.com/loopingz/webda.io/issues/759)) ([63e6e0c](https://github.com/loopingz/webda.io/commit/63e6e0c3bd7d72fb06b148c7344eb3021d186ae9))
33
+ * WebdaQLString<T> branded type + ts-plugin compile-time validator ([#772](https://github.com/loopingz/webda.io/issues/772)) ([f0c14c1](https://github.com/loopingz/webda.io/commit/f0c14c1d5511b6f5e4f52633a23b3d2fe07b86c1))
34
+
35
+
36
+ ### Bug Fixes
37
+
38
+ * compiler metadata, CLI commands, cron/async hooks and long-running command lifecycle ([#785](https://github.com/loopingz/webda.io/issues/785)) ([0515715](https://github.com/loopingz/webda.io/commit/05157157c9f52af3c8df720f6630053cd2dc8b98))
39
+ * **compiler:** make webdac code a working migration tool ([578ca7b](https://github.com/loopingz/webda.io/commit/578ca7b5243701a4ba1d9a9685c38b2f89ac27ed))
40
+ * unit test models relations ([2d160f1](https://github.com/loopingz/webda.io/commit/2d160f18d2139b362e8a12f935e15eaad27a808a))
41
+
42
+
43
+ ### Dependencies
44
+
45
+ * The following workspace dependencies were updated
46
+ * dependencies
47
+ * @webda/workout bumped to 4.0.0-beta.3
48
+ * devDependencies
49
+ * @webda/compiler bumped to 4.0.0-beta.3
50
+ * @webda/core bumped to 4.0.0-beta.3
51
+ * @webda/test bumped to 4.0.0-beta.3
52
+ * @webda/utils bumped to 4.0.0-beta.3
53
+ * peerDependencies
54
+ * @webda/core bumped from ^4.0.0-beta.1 to ^4.0.0-beta.3
package/LICENSE ADDED
@@ -0,0 +1,166 @@
1
+ GNU LESSER GENERAL PUBLIC LICENSE
2
+ Version 3, 29 June 2007
3
+
4
+ Copyright (C) 2007 Free Software Foundation, Inc. <http://fsf.org/>
5
+ Everyone is permitted to copy and distribute verbatim copies
6
+ of this license document, but changing it is not allowed.
7
+
8
+
9
+ This version of the GNU Lesser General Public License incorporates
10
+ the terms and conditions of version 3 of the GNU General Public
11
+ License, supplemented by the additional permissions listed below.
12
+
13
+ 0. Additional Definitions.
14
+
15
+ As used herein, "this License" refers to version 3 of the GNU Lesser
16
+ General Public License, and the "GNU GPL" refers to version 3 of the GNU
17
+ General Public License.
18
+
19
+ "The Library" refers to a covered work governed by this License,
20
+ other than an Application or a Combined Work as defined below.
21
+
22
+ An "Application" is any work that makes use of an interface provided
23
+ by the Library, but which is not otherwise based on the Library.
24
+ Defining a subclass of a class defined by the Library is deemed a mode
25
+ of using an interface provided by the Library.
26
+
27
+ A "Combined Work" is a work produced by combining or linking an
28
+ Application with the Library. The particular version of the Library
29
+ with which the Combined Work was made is also called the "Linked
30
+ Version".
31
+
32
+ The "Minimal Corresponding Source" for a Combined Work means the
33
+ Corresponding Source for the Combined Work, excluding any source code
34
+ for portions of the Combined Work that, considered in isolation, are
35
+ based on the Application, and not on the Linked Version.
36
+
37
+ The "Corresponding Application Code" for a Combined Work means the
38
+ object code and/or source code for the Application, including any data
39
+ and utility programs needed for reproducing the Combined Work from the
40
+ Application, but excluding the System Libraries of the Combined Work.
41
+
42
+ 1. Exception to Section 3 of the GNU GPL.
43
+
44
+ You may convey a covered work under sections 3 and 4 of this License
45
+ without being bound by section 3 of the GNU GPL.
46
+
47
+ 2. Conveying Modified Versions.
48
+
49
+ If you modify a copy of the Library, and, in your modifications, a
50
+ facility refers to a function or data to be supplied by an Application
51
+ that uses the facility (other than as an argument passed when the
52
+ facility is invoked), then you may convey a copy of the modified
53
+ version:
54
+
55
+ a) under this License, provided that you make a good faith effort to
56
+ ensure that, in the event an Application does not supply the
57
+ function or data, the facility still operates, and performs
58
+ whatever part of its purpose remains meaningful, or
59
+
60
+ b) under the GNU GPL, with none of the additional permissions of
61
+ this License applicable to that copy.
62
+
63
+ 3. Object Code Incorporating Material from Library Header Files.
64
+
65
+ The object code form of an Application may incorporate material from
66
+ a header file that is part of the Library. You may convey such object
67
+ code under terms of your choice, provided that, if the incorporated
68
+ material is not limited to numerical parameters, data structure
69
+ layouts and accessors, or small macros, inline functions and templates
70
+ (ten or fewer lines in length), you do both of the following:
71
+
72
+ a) Give prominent notice with each copy of the object code that the
73
+ Library is used in it and that the Library and its use are
74
+ covered by this License.
75
+
76
+ b) Accompany the object code with a copy of the GNU GPL and this license
77
+ document.
78
+
79
+ 4. Combined Works.
80
+
81
+ You may convey a Combined Work under terms of your choice that,
82
+ taken together, effectively do not restrict modification of the
83
+ portions of the Library contained in the Combined Work and reverse
84
+ engineering for debugging such modifications, if you also do each of
85
+ the following:
86
+
87
+ a) Give prominent notice with each copy of the Combined Work that
88
+ the Library is used in it and that the Library and its use are
89
+ covered by this License.
90
+
91
+ b) Accompany the Combined Work with a copy of the GNU GPL and this license
92
+ document.
93
+
94
+ c) For a Combined Work that displays copyright notices during
95
+ execution, include the copyright notice for the Library among
96
+ these notices, as well as a reference directing the user to the
97
+ copies of the GNU GPL and this license document.
98
+
99
+ d) Do one of the following:
100
+
101
+ 0) Convey the Minimal Corresponding Source under the terms of this
102
+ License, and the Corresponding Application Code in a form
103
+ suitable for, and under terms that permit, the user to
104
+ recombine or relink the Application with a modified version of
105
+ the Linked Version to produce a modified Combined Work, in the
106
+ manner specified by section 6 of the GNU GPL for conveying
107
+ Corresponding Source.
108
+
109
+ 1) Use a suitable shared library mechanism for linking with the
110
+ Library. A suitable mechanism is one that (a) uses at run time
111
+ a copy of the Library already present on the user's computer
112
+ system, and (b) will operate properly with a modified version
113
+ of the Library that is interface-compatible with the Linked
114
+ Version.
115
+
116
+ e) Provide Installation Information, but only if you would otherwise
117
+ be required to provide such information under section 6 of the
118
+ GNU GPL, and only to the extent that such information is
119
+ necessary to install and execute a modified version of the
120
+ Combined Work produced by recombining or relinking the
121
+ Application with a modified version of the Linked Version. (If
122
+ you use option 4d0, the Installation Information must accompany
123
+ the Minimal Corresponding Source and Corresponding Application
124
+ Code. If you use option 4d1, you must provide the Installation
125
+ Information in the manner specified by section 6 of the GNU GPL
126
+ for conveying Corresponding Source.)
127
+
128
+ 5. Combined Libraries.
129
+
130
+ You may place library facilities that are a work based on the
131
+ Library side by side in a single library together with other library
132
+ facilities that are not Applications and are not covered by this
133
+ License, and convey such a combined library under terms of your
134
+ choice, if you do both of the following:
135
+
136
+ a) Accompany the combined library with a copy of the same work based
137
+ on the Library, uncombined with any other library facilities,
138
+ conveyed under the terms of this License.
139
+
140
+ b) Give prominent notice with the combined library that part of it
141
+ is a work based on the Library, and explaining where to find the
142
+ accompanying uncombined form of the same work.
143
+
144
+ 6. Revised Versions of the GNU Lesser General Public License.
145
+
146
+ The Free Software Foundation may publish revised and/or new versions
147
+ of the GNU Lesser General Public License from time to time. Such new
148
+ versions will be similar in spirit to the present version, but may
149
+ differ in detail to address new problems or concerns.
150
+
151
+ Each version is given a distinguishing version number. If the
152
+ Library as you received it specifies that a certain numbered version
153
+ of the GNU Lesser General Public License "or any later version"
154
+ applies to it, you have the option of following the terms and
155
+ conditions either of that published version or of any later version
156
+ published by the Free Software Foundation. If the Library as you
157
+ received it does not specify a version number of the GNU Lesser
158
+ General Public License, you may choose any version of the GNU Lesser
159
+ General Public License ever published by the Free Software Foundation.
160
+
161
+ If the Library as you received it specifies that a proxy can decide
162
+ whether future versions of the GNU Lesser General Public License shall
163
+ apply, that proxy's public statement of acceptance of any version is
164
+ permanent authorization for you to choose that version for the
165
+ Library.
166
+
package/README.md ADDED
@@ -0,0 +1,100 @@
1
+ # @webda/grpc module
2
+
3
+ This module is part of Webda Application Framework that allows you to quickly develop applications with all modern prerequisites: Security, Extensibility, GraphQL, REST, CloudNative [https://webda.io](https://webda.io)
4
+
5
+ <img src="https://webda.io/images/webda.svg" width="128" />
6
+
7
+ ![CI](https://github.com/loopingz/webda.io/workflows/CI/badge.svg)
8
+
9
+ [![Join the chat at https://gitter.im/loopingz/webda](https://badges.gitter.im/loopingz/webda.svg)](https://gitter.im/loopingz/webda?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge&utm_content=badge)
10
+ [![codecov](https://codecov.io/gh/loopingz/webda.io/branch/main/graph/badge.svg?token=8N9DNM3K3O)](https://codecov.io/gh/loopingz/webda.io)
11
+ [![SonarCloud.io](https://sonarcloud.io/api/project_badges/measure?project=loopingz_webda.io&metric=alert_status)](https://sonarcloud.io/summary/new_code?id=loopingz_webda.io)
12
+ ![CodeQL](https://github.com/loopingz/webda.io/workflows/CodeQL/badge.svg)
13
+
14
+ <!-- README_HEADER -->
15
+
16
+ # @webda/grpc
17
+
18
+ > gRPC transport for Webda — exposes registered operations as gRPC services over HTTP/2, with auto-generated `.proto` files from the operation registry.
19
+
20
+ ## When to use it
21
+
22
+ - You want to expose Webda operations to gRPC clients (mobile apps, microservices, inter-service calls) alongside the existing REST API.
23
+ - You are running the multi-protocol dev server (`webda debug`) and need gRPC on the same TLS port as REST and GraphQL.
24
+ - You need a generated `.proto` file that stays in sync with your operation registry automatically on every `webdac build`.
25
+
26
+ ## Install
27
+
28
+ ```bash
29
+ pnpm add @webda/grpc
30
+ ```
31
+
32
+ ## Configuration
33
+
34
+ ```json
35
+ {
36
+ "services": {
37
+ "grpc": {
38
+ "type": "GrpcService",
39
+ "protoFile": ".webda/app.proto",
40
+ "packageName": "webda"
41
+ }
42
+ }
43
+ }
44
+ ```
45
+
46
+ | Parameter | Type | Default | Required | Description |
47
+ |---|---|---|---|---|
48
+ | `protoFile` | string | `".webda/app.proto"` | No | Path where the generated `.proto` file is written and loaded from |
49
+ | `packageName` | string | `"webda"` | No | Protobuf package name used in the generated `.proto` |
50
+
51
+ ## Usage
52
+
53
+ ```typescript
54
+ // 1. Annotate operations in your model/service:
55
+ import { Operation } from "@webda/core";
56
+
57
+ export class PostService extends Service {
58
+ @Operation({ input: "CreatePostInput", output: "Post" })
59
+ async createPost(ctx: OperationContext<CreatePostInput>): Promise<Post> {
60
+ const body = await ctx.getInput();
61
+ return new Post(body).save();
62
+ }
63
+ }
64
+
65
+ // 2. Build to generate the .proto file:
66
+ // webdac build
67
+ // → writes .webda/app.proto
68
+
69
+ // 3. Start the server (gRPC is multiplexed on the same port as REST):
70
+ // webda serve
71
+ // → gRPC requests with content-type: application/grpc are routed to GrpcService
72
+
73
+ // 4. Call from a gRPC client (example using grpcurl):
74
+ // grpcurl -plaintext -d '{"title":"Hello"}' localhost:18080 webda.PostService/CreatePost
75
+ ```
76
+
77
+ ## Reference
78
+
79
+ - API reference: see the auto-generated typedoc at `docs/pages/Modules/grpc/`.
80
+ - Source: [`packages/grpc`](https://github.com/loopingz/webda.io/tree/main/packages/grpc)
81
+ - Related: [`@webda/graphql`](../graphql) for the GraphQL transport; [`@webda/core`](../core) for the `OperationsTransport` base class and operation registration.
82
+
83
+ <!-- README_FOOTER -->
84
+ ## Sponsors
85
+
86
+ <!--
87
+ Support this project by becoming a sponsor. Your logo will show up here with a link to your website. [Become a sponsor](mailto:sponsor@webda.io)
88
+ -->
89
+
90
+ Arize AI is a machine learning observability and model monitoring platform. It helps you visualize, monitor, and explain your machine learning models. [Learn more](https://arize.com)
91
+
92
+ [<img src="https://arize.com/hubfs/arize/brand/arize-logomark-1.png" width="200">](https://arize.com)
93
+
94
+ Loopingz is a software development company that provides consulting and development services. [Learn more](https://loopingz.com)
95
+
96
+ [<img src="https://loopingz.com/images/logo.png" width="200">](https://loopingz.com)
97
+
98
+ Tellae is an innovative consulting firm specialized in cities transportation issues. We provide our clients, both public and private, with solutions to support your strategic and operational decisions. [Learn more](https://tellae.fr)
99
+
100
+ [<img src="https://tellae.fr/" width="200">](https://tellae.fr)
@@ -0,0 +1,109 @@
1
+ import type { Http2ServerRequest, Http2ServerResponse } from "node:http2";
2
+ import type { IncomingMessage, ServerResponse } from "node:http";
3
+ /**
4
+ * Parsed gRPC method definition with serializer/deserializer functions.
5
+ */
6
+ export interface GrpcMethodDef<Req = any, Res = any> {
7
+ requestSerialize: (msg: Req) => Buffer;
8
+ requestDeserialize: (buf: Buffer) => Req;
9
+ responseSerialize: (msg: Res) => Buffer;
10
+ responseDeserialize: (buf: Buffer) => Res;
11
+ requestStream: boolean;
12
+ responseStream: boolean;
13
+ }
14
+ /**
15
+ * gRPC bidirectional stream handler.
16
+ *
17
+ * Manages frame parsing (5-byte header: compressed flag + 4-byte big-endian length),
18
+ * message deserialization, and response framing for HTTP/2 gRPC streams.
19
+ *
20
+ * Supports all four gRPC patterns:
21
+ * - Unary (single request, single response)
22
+ * - Server streaming (single request, stream of responses)
23
+ * - Client streaming (stream of requests, single response)
24
+ * - Bidirectional streaming (stream of requests, stream of responses)
25
+ */
26
+ export declare class GrpcStream<RequestType = any, ResponseType = any> {
27
+ /** Sentinel value indicating successful stream setup */
28
+ static OK: symbol;
29
+ private onMessageHandler;
30
+ private onEndHandler?;
31
+ private onCancelHandler?;
32
+ private chunk;
33
+ private messageLength;
34
+ private request;
35
+ private response;
36
+ private definition;
37
+ /**
38
+ * Create a new GrpcStream to handle a single gRPC request/response lifecycle.
39
+ * @param req - the incoming HTTP/2 request carrying the gRPC frames
40
+ * @param res - the HTTP/2 response used to write gRPC frames and trailers
41
+ * @param definition - protobuf method definition providing serialize/deserialize functions
42
+ */
43
+ constructor(req: IncomingMessage | Http2ServerRequest, res: ServerResponse | Http2ServerResponse, definition: GrpcMethodDef<RequestType, ResponseType>);
44
+ /**
45
+ * Register handler for incoming messages
46
+ * @param handler - callback invoked with each deserialized request message
47
+ * @returns this instance for chaining
48
+ */
49
+ onMessage(handler: (message: RequestType) => void | Promise<void>): this;
50
+ /**
51
+ * Register handler for stream end (client finished sending)
52
+ * @param handler - callback invoked when the client closes the send side of the stream
53
+ * @returns this instance for chaining
54
+ */
55
+ onEnd(handler: () => void): this;
56
+ /**
57
+ * Register handler for stream cancellation (client disconnected)
58
+ * @param handler - callback invoked when the underlying connection is closed by the client
59
+ * @returns this instance for chaining
60
+ */
61
+ onCancel(handler: () => void): this;
62
+ /**
63
+ * Send a response message with gRPC framing.
64
+ * @param message - the response message to serialize and send
65
+ * @returns void
66
+ */
67
+ send(message: ResponseType): void;
68
+ /**
69
+ * End the response with gRPC status trailers.
70
+ * @param status - gRPC status code (0 = OK)
71
+ * @param message - optional status message included in grpc-message trailer
72
+ * @returns void
73
+ */
74
+ end(status?: number, message?: string): void;
75
+ /**
76
+ * Send a single unary response and close the stream.
77
+ * @param message - the response message to serialize and send before closing
78
+ * @returns void
79
+ */
80
+ sendUnary(message: ResponseType): void;
81
+ /**
82
+ * Send an error response and close the stream.
83
+ * @param status - gRPC status code indicating the error type
84
+ * @param message - human-readable error message included in grpc-message trailer
85
+ * @returns void
86
+ */
87
+ sendError(status: number, message: string): void;
88
+ }
89
+ /** gRPC status codes */
90
+ export declare const GrpcStatus: {
91
+ readonly OK: 0;
92
+ readonly CANCELLED: 1;
93
+ readonly UNKNOWN: 2;
94
+ readonly INVALID_ARGUMENT: 3;
95
+ readonly DEADLINE_EXCEEDED: 4;
96
+ readonly NOT_FOUND: 5;
97
+ readonly ALREADY_EXISTS: 6;
98
+ readonly PERMISSION_DENIED: 7;
99
+ readonly RESOURCE_EXHAUSTED: 8;
100
+ readonly FAILED_PRECONDITION: 9;
101
+ readonly ABORTED: 10;
102
+ readonly OUT_OF_RANGE: 11;
103
+ readonly UNIMPLEMENTED: 12;
104
+ readonly INTERNAL: 13;
105
+ readonly UNAVAILABLE: 14;
106
+ readonly DATA_LOSS: 15;
107
+ readonly UNAUTHENTICATED: 16;
108
+ };
109
+ //# sourceMappingURL=grpc-stream.d.ts.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grpc-stream.d.ts","sourceRoot":"","sources":["../src/grpc-stream.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,kBAAkB,EAAE,mBAAmB,EAAE,MAAM,YAAY,CAAC;AAC1E,OAAO,KAAK,EAAE,eAAe,EAAE,cAAc,EAAE,MAAM,WAAW,CAAC;AAEjE;;GAEG;AACH,MAAM,WAAW,aAAa,CAAC,GAAG,GAAG,GAAG,EAAE,GAAG,GAAG,GAAG;IACjD,gBAAgB,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,MAAM,CAAC;IACvC,kBAAkB,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,GAAG,CAAC;IACzC,iBAAiB,EAAE,CAAC,GAAG,EAAE,GAAG,KAAK,MAAM,CAAC;IACxC,mBAAmB,EAAE,CAAC,GAAG,EAAE,MAAM,KAAK,GAAG,CAAC;IAC1C,aAAa,EAAE,OAAO,CAAC;IACvB,cAAc,EAAE,OAAO,CAAC;CACzB;AAED;;;;;;;;;;;GAWG;AACH,qBAAa,UAAU,CAAC,WAAW,GAAG,GAAG,EAAE,YAAY,GAAG,GAAG;IAC3D,wDAAwD;IACxD,MAAM,CAAC,EAAE,SAAgB;IAEzB,OAAO,CAAC,gBAAgB,CAAiD;IACzE,OAAO,CAAC,YAAY,CAAC,CAAa;IAClC,OAAO,CAAC,eAAe,CAAC,CAAa;IACrC,OAAO,CAAC,KAAK,CAAuB;IACpC,OAAO,CAAC,aAAa,CAAK;IAC1B,OAAO,CAAC,OAAO,CAAuC;IACtD,OAAO,CAAC,QAAQ,CAAuC;IACvD,OAAO,CAAC,UAAU,CAA2C;IAE7D;;;;;OAKG;IACH,YACE,GAAG,EAAE,eAAe,GAAG,kBAAkB,EACzC,GAAG,EAAE,cAAc,GAAG,mBAAmB,EACzC,UAAU,EAAE,aAAa,CAAC,WAAW,EAAE,YAAY,CAAC,EAyCrD;IAED;;;;OAIG;IACH,SAAS,CAAC,OAAO,EAAE,CAAC,OAAO,EAAE,WAAW,KAAK,IAAI,GAAG,OAAO,CAAC,IAAI,CAAC,GAAG,IAAI,CAGvE;IAED;;;;OAIG;IACH,KAAK,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,IAAI,CAG/B;IAED;;;;OAIG;IACH,QAAQ,CAAC,OAAO,EAAE,MAAM,IAAI,GAAG,IAAI,CAGlC;IAED;;;;OAIG;IACH,IAAI,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAOhC;IAED;;;;;OAKG;IACH,GAAG,CAAC,MAAM,GAAE,MAAU,EAAE,OAAO,CAAC,EAAE,MAAM,GAAG,IAAI,CAO9C;IAED;;;;OAIG;IACH,SAAS,CAAC,OAAO,EAAE,YAAY,GAAG,IAAI,CAGrC;IAED;;;;;OAKG;IACH,SAAS,CAAC,MAAM,EAAE,MAAM,EAAE,OAAO,EAAE,MAAM,GAAG,IAAI,CAE/C;CACF;AAED,wBAAwB;AACxB,eAAO,MAAM,UAAU;aACrB,EAAE,EAAE,CAAC;aACL,SAAS,EAAE,CAAC;aACZ,OAAO,EAAE,CAAC;aACV,gBAAgB,EAAE,CAAC;aACnB,iBAAiB,EAAE,CAAC;aACpB,SAAS,EAAE,CAAC;aACZ,cAAc,EAAE,CAAC;aACjB,iBAAiB,EAAE,CAAC;aACpB,kBAAkB,EAAE,CAAC;aACrB,mBAAmB,EAAE,CAAC;aACtB,OAAO,EAAE,EAAE;aACX,YAAY,EAAE,EAAE;aAChB,aAAa,EAAE,EAAE;aACjB,QAAQ,EAAE,EAAE;aACZ,WAAW,EAAE,EAAE;aACf,SAAS,EAAE,EAAE;aACb,eAAe,EAAE,EAAE;CACX,CAAC"}
@@ -0,0 +1,162 @@
1
+ /**
2
+ * gRPC bidirectional stream handler.
3
+ *
4
+ * Manages frame parsing (5-byte header: compressed flag + 4-byte big-endian length),
5
+ * message deserialization, and response framing for HTTP/2 gRPC streams.
6
+ *
7
+ * Supports all four gRPC patterns:
8
+ * - Unary (single request, single response)
9
+ * - Server streaming (single request, stream of responses)
10
+ * - Client streaming (stream of requests, single response)
11
+ * - Bidirectional streaming (stream of requests, stream of responses)
12
+ */
13
+ export class GrpcStream {
14
+ /** Sentinel value indicating successful stream setup */
15
+ static OK = Symbol("OK");
16
+ onMessageHandler;
17
+ onEndHandler;
18
+ onCancelHandler;
19
+ chunk = null;
20
+ messageLength = 0;
21
+ request;
22
+ response;
23
+ definition;
24
+ /**
25
+ * Create a new GrpcStream to handle a single gRPC request/response lifecycle.
26
+ * @param req - the incoming HTTP/2 request carrying the gRPC frames
27
+ * @param res - the HTTP/2 response used to write gRPC frames and trailers
28
+ * @param definition - protobuf method definition providing serialize/deserialize functions
29
+ */
30
+ constructor(req, res, definition) {
31
+ this.request = req;
32
+ this.response = res;
33
+ this.definition = definition;
34
+ // Set gRPC response headers
35
+ this.response.setHeader("Content-Type", "application/grpc");
36
+ this.response.setHeader("Grpc-Accept-Encoding", "identity");
37
+ this.response.setHeader("Grpc-Encoding", "identity");
38
+ // Parse incoming gRPC frames
39
+ req.on("data", (data) => {
40
+ if (this.chunk === null) {
41
+ this.messageLength = data.readUInt32BE(1);
42
+ this.chunk = data;
43
+ }
44
+ else {
45
+ this.chunk = Buffer.concat([this.chunk, data]);
46
+ }
47
+ // Check if we have a complete message
48
+ while (this.chunk && this.chunk.length >= 5 + this.messageLength) {
49
+ const message = this.chunk.subarray(5, 5 + this.messageLength);
50
+ const deserialized = this.definition.requestDeserialize(message);
51
+ this.onMessageHandler?.(deserialized);
52
+ // Advance to next frame
53
+ this.chunk = this.chunk.subarray(5 + this.messageLength);
54
+ if (this.chunk.length >= 5) {
55
+ this.messageLength = this.chunk.readUInt32BE(1);
56
+ }
57
+ else if (this.chunk.length === 0) {
58
+ this.chunk = null;
59
+ }
60
+ }
61
+ });
62
+ req.on("end", () => {
63
+ this.onEndHandler?.();
64
+ });
65
+ req.on("close", () => {
66
+ this.onCancelHandler?.();
67
+ });
68
+ }
69
+ /**
70
+ * Register handler for incoming messages
71
+ * @param handler - callback invoked with each deserialized request message
72
+ * @returns this instance for chaining
73
+ */
74
+ onMessage(handler) {
75
+ this.onMessageHandler = handler;
76
+ return this;
77
+ }
78
+ /**
79
+ * Register handler for stream end (client finished sending)
80
+ * @param handler - callback invoked when the client closes the send side of the stream
81
+ * @returns this instance for chaining
82
+ */
83
+ onEnd(handler) {
84
+ this.onEndHandler = handler;
85
+ return this;
86
+ }
87
+ /**
88
+ * Register handler for stream cancellation (client disconnected)
89
+ * @param handler - callback invoked when the underlying connection is closed by the client
90
+ * @returns this instance for chaining
91
+ */
92
+ onCancel(handler) {
93
+ this.onCancelHandler = handler;
94
+ return this;
95
+ }
96
+ /**
97
+ * Send a response message with gRPC framing.
98
+ * @param message - the response message to serialize and send
99
+ * @returns void
100
+ */
101
+ send(message) {
102
+ const responseBuffer = this.definition.responseSerialize(message);
103
+ const frame = Buffer.alloc(5 + responseBuffer.length);
104
+ frame.writeUInt8(0, 0); // Not compressed
105
+ frame.writeUInt32BE(responseBuffer.length, 1);
106
+ responseBuffer.copy(frame, 5);
107
+ this.response.write(frame);
108
+ }
109
+ /**
110
+ * End the response with gRPC status trailers.
111
+ * @param status - gRPC status code (0 = OK)
112
+ * @param message - optional status message included in grpc-message trailer
113
+ * @returns void
114
+ */
115
+ end(status = 0, message) {
116
+ const trailers = { "grpc-status": String(status) };
117
+ if (message) {
118
+ trailers["grpc-message"] = encodeURIComponent(message);
119
+ }
120
+ this.response.addTrailers?.(trailers);
121
+ this.response.end();
122
+ }
123
+ /**
124
+ * Send a single unary response and close the stream.
125
+ * @param message - the response message to serialize and send before closing
126
+ * @returns void
127
+ */
128
+ sendUnary(message) {
129
+ this.send(message);
130
+ this.end(0);
131
+ }
132
+ /**
133
+ * Send an error response and close the stream.
134
+ * @param status - gRPC status code indicating the error type
135
+ * @param message - human-readable error message included in grpc-message trailer
136
+ * @returns void
137
+ */
138
+ sendError(status, message) {
139
+ this.end(status, message);
140
+ }
141
+ }
142
+ /** gRPC status codes */
143
+ export const GrpcStatus = {
144
+ OK: 0,
145
+ CANCELLED: 1,
146
+ UNKNOWN: 2,
147
+ INVALID_ARGUMENT: 3,
148
+ DEADLINE_EXCEEDED: 4,
149
+ NOT_FOUND: 5,
150
+ ALREADY_EXISTS: 6,
151
+ PERMISSION_DENIED: 7,
152
+ RESOURCE_EXHAUSTED: 8,
153
+ FAILED_PRECONDITION: 9,
154
+ ABORTED: 10,
155
+ OUT_OF_RANGE: 11,
156
+ UNIMPLEMENTED: 12,
157
+ INTERNAL: 13,
158
+ UNAVAILABLE: 14,
159
+ DATA_LOSS: 15,
160
+ UNAUTHENTICATED: 16
161
+ };
162
+ //# sourceMappingURL=grpc-stream.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"grpc-stream.js","sourceRoot":"","sources":["../src/grpc-stream.ts"],"names":[],"mappings":"AAeA;;;;;;;;;;;GAWG;AACH,MAAM,OAAO,UAAU;IACrB,wDAAwD;IACxD,MAAM,CAAC,EAAE,GAAG,MAAM,CAAC,IAAI,CAAC,CAAC;IAEjB,gBAAgB,CAAiD;IACjE,YAAY,CAAc;IAC1B,eAAe,CAAc;IAC7B,KAAK,GAAkB,IAAI,CAAC;IAC5B,aAAa,GAAG,CAAC,CAAC;IAClB,OAAO,CAAuC;IAC9C,QAAQ,CAAuC;IAC/C,UAAU,CAA2C;IAE7D;;;;;OAKG;IACH,YACE,GAAyC,EACzC,GAAyC,EACzC,UAAoD;QAEpD,IAAI,CAAC,OAAO,GAAG,GAAG,CAAC;QACnB,IAAI,CAAC,QAAQ,GAAG,GAAG,CAAC;QACpB,IAAI,CAAC,UAAU,GAAG,UAAU,CAAC;QAE7B,4BAA4B;QAC5B,IAAI,CAAC,QAAQ,CAAC,SAAS,CAAC,cAAc,EAAE,kBAAkB,CAAC,CAAC;QAC5D,IAAI,CAAC,QAAQ,CAA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