@snap-rail/protocol 0.0.0-stage → 0.1.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,202 @@
1
+
2
+ Apache License
3
+ Version 2.0, January 2004
4
+ http://www.apache.org/licenses/
5
+
6
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
7
+
8
+ 1. Definitions.
9
+
10
+ "License" shall mean the terms and conditions for use, reproduction,
11
+ and distribution as defined by Sections 1 through 9 of this document.
12
+
13
+ "Licensor" shall mean the copyright owner or entity authorized by
14
+ the copyright owner that is granting the License.
15
+
16
+ "Legal Entity" shall mean the union of the acting entity and all
17
+ other entities that control, are controlled by, or are under common
18
+ control with that entity. For the purposes of this definition,
19
+ "control" means (i) the power, direct or indirect, to cause the
20
+ direction or management of such entity, whether by contract or
21
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
22
+ outstanding shares, or (iii) beneficial ownership of such entity.
23
+
24
+ "You" (or "Your") shall mean an individual or Legal Entity
25
+ exercising permissions granted by this License.
26
+
27
+ "Source" form shall mean the preferred form for making modifications,
28
+ including but not limited to software source code, documentation
29
+ source, and configuration files.
30
+
31
+ "Object" form shall mean any form resulting from mechanical
32
+ transformation or translation of a Source form, including but
33
+ not limited to compiled object code, generated documentation,
34
+ and conversions to other media types.
35
+
36
+ "Work" shall mean the work of authorship, whether in Source or
37
+ Object form, made available under the License, as indicated by a
38
+ copyright notice that is included in or attached to the work
39
+ (an example is provided in the Appendix below).
40
+
41
+ "Derivative Works" shall mean any work, whether in Source or Object
42
+ form, that is based on (or derived from) the Work and for which the
43
+ editorial revisions, annotations, elaborations, or other modifications
44
+ represent, as a whole, an original work of authorship. For the purposes
45
+ of this License, Derivative Works shall not include works that remain
46
+ separable from, or merely link (or bind by name) to the interfaces of,
47
+ the Work and Derivative Works thereof.
48
+
49
+ "Contribution" shall mean any work of authorship, including
50
+ the original version of the Work and any modifications or additions
51
+ to that Work or Derivative Works thereof, that is intentionally
52
+ submitted to Licensor for inclusion in the Work by the copyright owner
53
+ or by an individual or Legal Entity authorized to submit on behalf of
54
+ the copyright owner. For the purposes of this definition, "submitted"
55
+ means any form of electronic, verbal, or written communication sent
56
+ to the Licensor or its representatives, including but not limited to
57
+ communication on electronic mailing lists, source code control systems,
58
+ and issue tracking systems that are managed by, or on behalf of, the
59
+ Licensor for the purpose of discussing and improving the Work, but
60
+ excluding communication that is conspicuously marked or otherwise
61
+ designated in writing by the copyright owner as "Not a Contribution."
62
+
63
+ "Contributor" shall mean Licensor and any individual or Legal Entity
64
+ on behalf of whom a Contribution has been received by Licensor and
65
+ subsequently incorporated within the Work.
66
+
67
+ 2. Grant of Copyright License. Subject to the terms and conditions of
68
+ this License, each Contributor hereby grants to You a perpetual,
69
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
70
+ copyright license to reproduce, prepare Derivative Works of,
71
+ publicly display, publicly perform, sublicense, and distribute the
72
+ Work and such Derivative Works in Source or Object form.
73
+
74
+ 3. Grant of Patent License. Subject to the terms and conditions of
75
+ this License, each Contributor hereby grants to You a perpetual,
76
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
77
+ (except as stated in this section) patent license to make, have made,
78
+ use, offer to sell, sell, import, and otherwise transfer the Work,
79
+ where such license applies only to those patent claims licensable
80
+ by such Contributor that are necessarily infringed by their
81
+ Contribution(s) alone or by combination of their Contribution(s)
82
+ with the Work to which such Contribution(s) was submitted. If You
83
+ institute patent litigation against any entity (including a
84
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
85
+ or a Contribution incorporated within the Work constitutes direct
86
+ or contributory patent infringement, then any patent licenses
87
+ granted to You under this License for that Work shall terminate
88
+ as of the date such litigation is filed.
89
+
90
+ 4. Redistribution. You may reproduce and distribute copies of the
91
+ Work or Derivative Works thereof in any medium, with or without
92
+ modifications, and in Source or Object form, provided that You
93
+ meet the following conditions:
94
+
95
+ (a) You must give any other recipients of the Work or
96
+ Derivative Works a copy of this License; and
97
+
98
+ (b) You must cause any modified files to carry prominent notices
99
+ stating that You changed the files; and
100
+
101
+ (c) You must retain, in the Source form of any Derivative Works
102
+ that You distribute, all copyright, patent, trademark, and
103
+ attribution notices from the Source form of the Work,
104
+ excluding those notices that do not pertain to any part of
105
+ the Derivative Works; and
106
+
107
+ (d) If the Work includes a "NOTICE" text file as part of its
108
+ distribution, then any Derivative Works that You distribute must
109
+ include a readable copy of the attribution notices contained
110
+ within such NOTICE file, excluding those notices that do not
111
+ pertain to any part of the Derivative Works, in at least one
112
+ of the following places: within a NOTICE text file distributed
113
+ as part of the Derivative Works; within the Source form or
114
+ documentation, if provided along with the Derivative Works; or,
115
+ within a display generated by the Derivative Works, if and
116
+ wherever such third-party notices normally appear. The contents
117
+ of the NOTICE file are for informational purposes only and
118
+ do not modify the License. You may add Your own attribution
119
+ notices within Derivative Works that You distribute, alongside
120
+ or as an addendum to the NOTICE text from the Work, provided
121
+ that such additional attribution notices cannot be construed
122
+ as modifying the License.
123
+
124
+ You may add Your own copyright statement to Your modifications and
125
+ may provide additional or different license terms and conditions
126
+ for use, reproduction, or distribution of Your modifications, or
127
+ for any such Derivative Works as a whole, provided Your use,
128
+ reproduction, and distribution of the Work otherwise complies with
129
+ the conditions stated in this License.
130
+
131
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
132
+ any Contribution intentionally submitted for inclusion in the Work
133
+ by You to the Licensor shall be under the terms and conditions of
134
+ this License, without any additional terms or conditions.
135
+ Notwithstanding the above, nothing herein shall supersede or modify
136
+ the terms of any separate license agreement you may have executed
137
+ with Licensor regarding such Contributions.
138
+
139
+ 6. Trademarks. This License does not grant permission to use the trade
140
+ names, trademarks, service marks, or product names of the Licensor,
141
+ except as required for reasonable and customary use in describing the
142
+ origin of the Work and reproducing the content of the NOTICE file.
143
+
144
+ 7. Disclaimer of Warranty. Unless required by applicable law or
145
+ agreed to in writing, Licensor provides the Work (and each
146
+ Contributor provides its Contributions) on an "AS IS" BASIS,
147
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
148
+ implied, including, without limitation, any warranties or conditions
149
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
150
+ PARTICULAR PURPOSE. You are solely responsible for determining the
151
+ appropriateness of using or redistributing the Work and assume any
152
+ risks associated with Your exercise of permissions under this License.
153
+
154
+ 8. Limitation of Liability. In no event and under no legal theory,
155
+ whether in tort (including negligence), contract, or otherwise,
156
+ unless required by applicable law (such as deliberate and grossly
157
+ negligent acts) or agreed to in writing, shall any Contributor be
158
+ liable to You for damages, including any direct, indirect, special,
159
+ incidental, or consequential damages of any character arising as a
160
+ result of this License or out of the use or inability to use the
161
+ Work (including but not limited to damages for loss of goodwill,
162
+ work stoppage, computer failure or malfunction, or any and all
163
+ other commercial damages or losses), even if such Contributor
164
+ has been advised of the possibility of such damages.
165
+
166
+ 9. Accepting Warranty or Additional Liability. While redistributing
167
+ the Work or Derivative Works thereof, You may choose to offer,
168
+ and charge a fee for, acceptance of support, warranty, indemnity,
169
+ or other liability obligations and/or rights consistent with this
170
+ License. However, in accepting such obligations, You may act only
171
+ on Your own behalf and on Your sole responsibility, not on behalf
172
+ of any other Contributor, and only if You agree to indemnify,
173
+ defend, and hold each Contributor harmless for any liability
174
+ incurred by, or claims asserted against, such Contributor by reason
175
+ of your accepting any such warranty or additional liability.
176
+
177
+ END OF TERMS AND CONDITIONS
178
+
179
+ APPENDIX: How to apply the Apache License to your work.
180
+
181
+ To apply the Apache License to your work, attach the following
182
+ boilerplate notice, with the fields enclosed by brackets "[]"
183
+ replaced with your own identifying information. (Don't include
184
+ the brackets!) The text should be enclosed in the appropriate
185
+ comment syntax for the file format. We also recommend that a
186
+ file or class name and description of purpose be included on the
187
+ same "printed page" as the copyright notice for easier
188
+ identification within third-party archives.
189
+
190
+ Copyright [yyyy] [name of copyright owner]
191
+
192
+ Licensed under the Apache License, Version 2.0 (the "License");
193
+ you may not use this file except in compliance with the License.
194
+ You may obtain a copy of the License at
195
+
196
+ http://www.apache.org/licenses/LICENSE-2.0
197
+
198
+ Unless required by applicable law or agreed to in writing, software
199
+ distributed under the License is distributed on an "AS IS" BASIS,
200
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
201
+ See the License for the specific language governing permissions and
202
+ limitations under the License.
@@ -0,0 +1,54 @@
1
+ //#region lib/types/contract.js
2
+ /**
3
+ * Single-source wire contracts: one {@link defineContract} declaration per
4
+ * domain yields everything a domain's wire surface needs — the rows that
5
+ * merge into the protocol's open maps (via `interface RpcMethodMap extends
6
+ * MethodRows<typeof contract> {}` in the same module), the request schemas
7
+ * that ride with registration, and the frame payload schemas for
8
+ * registration and client parsing. The hand-written trio (Api interface +
9
+ * merge rows + schema table) said the same thing three times; here it is
10
+ * said once.
11
+ *
12
+ * A row's response value type is declared through the phantom `res` field
13
+ * (the builders lie about it so the type is reachable without a runtime
14
+ * schema); runtime rows carry only `request` and, optionally, `response`.
15
+ *
16
+ * @module @snap-rail/protocol/contract
17
+ */
18
+ /**
19
+ * Open one method row: the request schema is mandatory (it is the
20
+ * trust-boundary validator), the response value type is declared through
21
+ * `.ret<T>()` or, with a runtime schema, `.res(schema)`.
22
+ *
23
+ * @param request - the request schema.
24
+ */
25
+ function method(request) {
26
+ return {
27
+ ret() {
28
+ return { request };
29
+ },
30
+ res(response) {
31
+ return {
32
+ request,
33
+ response
34
+ };
35
+ }
36
+ };
37
+ }
38
+ /**
39
+ * Declare one domain's wire surface. Keys are full wire names; every
40
+ * conventional call site passes both tables (`methods: {}` when the domain
41
+ * only pushes frames, `frames: {}` when it only serves methods).
42
+ *
43
+ * @param domain - the wire domain (diagnostic metadata; claims are separate).
44
+ * @param def - the method and frame tables.
45
+ */
46
+ function defineContract(domain, def) {
47
+ return {
48
+ domain,
49
+ methods: def.methods,
50
+ frames: def.frames
51
+ };
52
+ }
53
+ //#endregion
54
+ export { defineContract, method };
package/lib/index.js ADDED
@@ -0,0 +1,138 @@
1
+ import { defineContract, method } from "./contract.js";
2
+ import { RpcBusinessError, RpcId, err, isRpcError, ok } from "./rpc.js";
3
+ import { z } from "zod";
4
+ //#region lib/types/schemas.js
5
+ /**
6
+ * Envelope validation at the trust boundary: the type/rpcId/method
7
+ * structure of every inbound message. Per-method payload schemas travel
8
+ * with each registration (`ctx.rpc.method`) — there is no central method
9
+ * table. Host responses are produced by trusted code and are not
10
+ * re-validated in phase 1.
11
+ *
12
+ * @module @snap-rail/protocol/schemas
13
+ */
14
+ const rpcIdSchema = z.string().min(1).transform(RpcId);
15
+ const clientRequestShape = z.object({
16
+ type: z.literal("client-request"),
17
+ rpcId: rpcIdSchema,
18
+ method: z.string().min(1),
19
+ payload: z.unknown()
20
+ });
21
+ /**
22
+ * Parse an inbound client request envelope.
23
+ * @param raw - the untrusted wire value.
24
+ * @returns the parsed envelope with a branded rpcId.
25
+ * @throws a zod error naming every envelope violation.
26
+ */
27
+ function parseClientRequest(raw) {
28
+ return clientRequestShape.parse(raw);
29
+ }
30
+ const serverRequestShape = z.object({
31
+ type: z.literal("server-request"),
32
+ rpcId: rpcIdSchema,
33
+ method: z.string().min(1),
34
+ payload: z.unknown()
35
+ });
36
+ /**
37
+ * Parse an inbound host frame on a client.
38
+ * @param raw - the untrusted wire value.
39
+ * @returns the parsed frame.
40
+ * @throws a zod error naming every envelope violation.
41
+ */
42
+ function parseServerRequest(raw) {
43
+ return serverRequestShape.parse(raw);
44
+ }
45
+ //#endregion
46
+ //#region lib/types/client.js
47
+ /**
48
+ * The client carrier family: protocol invariants live in the base class;
49
+ * platform differences are transport aspects only. Business failures come
50
+ * back as `RpcResult` (never thrown here); transport failures are thrown by
51
+ * the carrier; the two layers never mix.
52
+ *
53
+ * @module @snap-rail/protocol/client
54
+ */
55
+ /**
56
+ * Mint a fresh rpc id. `globalThis.crypto` keeps the client family free of
57
+ * Node builtins so the same code bundles into the browser renderer.
58
+ */
59
+ function freshId() {
60
+ return globalThis.crypto.randomUUID();
61
+ }
62
+ /** A thrown transport failure; carries no business semantics. */
63
+ var RpcTransportError = class extends Error {
64
+ constructor(message, options) {
65
+ super(message, options);
66
+ this.name = "RpcTransportError";
67
+ }
68
+ };
69
+ /**
70
+ * Protocol client base. Subclasses supply the unary transport; rpcId minting
71
+ * and the echo check live here and nowhere else.
72
+ */
73
+ var AbstractApiClient = class {
74
+ async call(method, payload) {
75
+ const rpcId = RpcId(freshId());
76
+ const response = await this.transport({
77
+ type: "client-request",
78
+ rpcId,
79
+ method,
80
+ payload
81
+ });
82
+ if (response.type !== "server-response") throw new RpcTransportError(`expected a server-response, received ${String(response.type)}`);
83
+ if (response.rpcId !== rpcId) throw new RpcTransportError(`rpcId echo mismatch: sent ${rpcId}, received ${response.rpcId}`);
84
+ return response.result;
85
+ }
86
+ };
87
+ /**
88
+ * The isomorphic carrier: runs the real protocol against an injected handler
89
+ * with no IPC at all. Tests exercise the exact envelope/result path a real
90
+ * carrier travels.
91
+ */
92
+ var InProcessApiClient = class extends AbstractApiClient {
93
+ queue = [];
94
+ resolvers = [];
95
+ finished = false;
96
+ transport;
97
+ /**
98
+ * @param handler - the gateway-side unary entry (`handleClientRequest`).
99
+ */
100
+ constructor(handler) {
101
+ super();
102
+ this.transport = handler;
103
+ }
104
+ /** Deliver a host frame into the client's mux stream (test/pump side). */
105
+ pushFrame(frame) {
106
+ const resolver = this.resolvers.shift();
107
+ if (resolver !== void 0) resolver({
108
+ done: false,
109
+ value: frame
110
+ });
111
+ else this.queue.push(frame);
112
+ }
113
+ /** The mux stream as an async iterable; ends when {@link end} is called. */
114
+ frames() {
115
+ return { [Symbol.asyncIterator]: () => ({ next: () => {
116
+ const frame = this.queue.shift();
117
+ if (frame !== void 0) return Promise.resolve({
118
+ done: false,
119
+ value: frame
120
+ });
121
+ if (this.finished) return Promise.resolve({
122
+ done: true,
123
+ value: void 0
124
+ });
125
+ return new Promise((resolve) => this.resolvers.push(resolve));
126
+ } }) };
127
+ }
128
+ /** End the mux stream; pending and future iterations finish. */
129
+ end() {
130
+ this.finished = true;
131
+ for (const resolve of this.resolvers.splice(0)) resolve({
132
+ done: true,
133
+ value: void 0
134
+ });
135
+ }
136
+ };
137
+ //#endregion
138
+ export { AbstractApiClient, InProcessApiClient, RpcBusinessError, RpcId, RpcTransportError, defineContract, err, isRpcError, method, ok, parseClientRequest, parseServerRequest };
package/lib/rpc.js ADDED
@@ -0,0 +1,67 @@
1
+ //#region lib/types/rpc.js
2
+ /**
3
+ * The four-quadrant message model: every logical message is classified by
4
+ * "who initiates × request/response", decoupled from the physical channel.
5
+ * Swapping the carrier (in-process, Electron IPC, a future WebSocket) leaves
6
+ * the quadrants unchanged; direction is a property of the message, never
7
+ * inferred from the channel.
8
+ *
9
+ * rpcId discipline: whoever initiates mints; a response always echoes the
10
+ * corresponding request's rpcId and never mints a new id. Pure-push frames
11
+ * mint a fresh id per push; answerable frames (a future approval/question
12
+ * family) reuse one stable id until answered.
13
+ *
14
+ * @module @snap-rail/protocol/rpc
15
+ */
16
+ /** Mint an rpc identifier. Only carriers and frame pumps mint; business code never does. */
17
+ function RpcId(value) {
18
+ return value;
19
+ }
20
+ /**
21
+ * Construct a success result.
22
+ * @param value - the method's return value.
23
+ */
24
+ function ok(value) {
25
+ return {
26
+ ok: true,
27
+ value
28
+ };
29
+ }
30
+ /**
31
+ * Construct a business-error result.
32
+ * @param code - the error code.
33
+ * @param details - code-specific details (required).
34
+ */
35
+ function err(code, details) {
36
+ return {
37
+ ok: false,
38
+ error: {
39
+ code,
40
+ details
41
+ }
42
+ };
43
+ }
44
+ /**
45
+ * Thrown by method handlers to fail with a business error; the gateway
46
+ * converts it into `{ ok: false, error }` on the wire. Carrying it as a
47
+ * throw keeps handler happy paths free of result wrapping.
48
+ */
49
+ var RpcBusinessError = class extends Error {
50
+ error;
51
+ constructor(error) {
52
+ super(`rpc business error: ${error.code}`);
53
+ this.error = error;
54
+ this.name = "RpcBusinessError";
55
+ }
56
+ };
57
+ /**
58
+ * Type guard narrowing an unknown value to {@link RpcError}.
59
+ * @param value - candidate error.
60
+ */
61
+ function isRpcError(value) {
62
+ if (value === null || typeof value !== "object") return false;
63
+ const record = value;
64
+ return typeof record.code === "string" && "details" in record;
65
+ }
66
+ //#endregion
67
+ export { RpcBusinessError, RpcId, err, isRpcError, ok };
@@ -0,0 +1,66 @@
1
+ /**
2
+ * The client carrier family: protocol invariants live in the base class;
3
+ * platform differences are transport aspects only. Business failures come
4
+ * back as `RpcResult` (never thrown here); transport failures are thrown by
5
+ * the carrier; the two layers never mix.
6
+ *
7
+ * @module @snap-rail/protocol/client
8
+ */
9
+ import type { ClientRequest, RpcResult, ServerRequest, ServerResponse } from './rpc.ts';
10
+ import type { MethodName, RequestPayload, ResponseValue } from './methods.ts';
11
+ /** A thrown transport failure; carries no business semantics. */
12
+ export declare class RpcTransportError extends Error {
13
+ constructor(message: string, options?: ErrorOptions);
14
+ }
15
+ /** Signature of the raw unary transport: send one full-form request, get its full-form response. */
16
+ export type UnaryTransport = (request: ClientRequest) => Promise<ServerResponse>;
17
+ /**
18
+ * Protocol client base. Subclasses supply the unary transport; rpcId minting
19
+ * and the echo check live here and nowhere else.
20
+ */
21
+ export declare abstract class AbstractApiClient {
22
+ /**
23
+ * The transport aspect: deliver one full-form client request and settle
24
+ * with its full-form server response.
25
+ */
26
+ protected abstract transport: UnaryTransport;
27
+ /**
28
+ * Call a unary method with the business payload directly; the carrier
29
+ * mints the rpcId and wraps the envelope.
30
+ *
31
+ * Two overloads, one open-world rule: a method known to {@link RpcMethodMap}
32
+ * (directly or via the caller's own declaration merge) is fully typed;
33
+ * any other method name is accepted as `(string, unknown)` — the caller
34
+ * owns the payload contract in that position. The same dual shape the
35
+ * cordis service surface uses: augmentation is opt-in, never required.
36
+ *
37
+ * @param method - the wire method name.
38
+ * @param payload - the business payload.
39
+ * @returns the business result; `ok: false` is a normal outcome, not an
40
+ * exception. Transport failures and rpcId echo mismatches throw.
41
+ */
42
+ call<K extends MethodName>(method: K, payload: RequestPayload<K>): Promise<RpcResult<ResponseValue<K>>>;
43
+ call(method: string, payload: unknown): Promise<RpcResult<unknown>>;
44
+ }
45
+ /**
46
+ * The isomorphic carrier: runs the real protocol against an injected handler
47
+ * with no IPC at all. Tests exercise the exact envelope/result path a real
48
+ * carrier travels.
49
+ */
50
+ export declare class InProcessApiClient extends AbstractApiClient {
51
+ private readonly queue;
52
+ private resolvers;
53
+ private finished;
54
+ protected readonly transport: UnaryTransport;
55
+ /**
56
+ * @param handler - the gateway-side unary entry (`handleClientRequest`).
57
+ */
58
+ constructor(handler: (request: ClientRequest) => Promise<ServerResponse>);
59
+ /** Deliver a host frame into the client's mux stream (test/pump side). */
60
+ pushFrame(frame: ServerRequest): void;
61
+ /** The mux stream as an async iterable; ends when {@link end} is called. */
62
+ frames(): AsyncIterable<ServerRequest>;
63
+ /** End the mux stream; pending and future iterations finish. */
64
+ end(): void;
65
+ }
66
+ //# sourceMappingURL=client.d.ts.map
@@ -0,0 +1,93 @@
1
+ /**
2
+ * The client carrier family: protocol invariants live in the base class;
3
+ * platform differences are transport aspects only. Business failures come
4
+ * back as `RpcResult` (never thrown here); transport failures are thrown by
5
+ * the carrier; the two layers never mix.
6
+ *
7
+ * @module @snap-rail/protocol/client
8
+ */
9
+ import { RpcId } from "./rpc.js";
10
+ /**
11
+ * Mint a fresh rpc id. `globalThis.crypto` keeps the client family free of
12
+ * Node builtins so the same code bundles into the browser renderer.
13
+ */
14
+ function freshId() {
15
+ return globalThis.crypto.randomUUID();
16
+ }
17
+ /** A thrown transport failure; carries no business semantics. */
18
+ export class RpcTransportError extends Error {
19
+ constructor(message, options) {
20
+ super(message, options);
21
+ this.name = 'RpcTransportError';
22
+ }
23
+ }
24
+ /**
25
+ * Protocol client base. Subclasses supply the unary transport; rpcId minting
26
+ * and the echo check live here and nowhere else.
27
+ */
28
+ export class AbstractApiClient {
29
+ async call(method, payload) {
30
+ const rpcId = RpcId(freshId());
31
+ const response = await this.transport({
32
+ type: 'client-request',
33
+ rpcId,
34
+ method,
35
+ payload,
36
+ });
37
+ if (response.type !== 'server-response') {
38
+ throw new RpcTransportError(`expected a server-response, received ${String(response.type)}`);
39
+ }
40
+ if (response.rpcId !== rpcId) {
41
+ throw new RpcTransportError(`rpcId echo mismatch: sent ${rpcId}, received ${response.rpcId}`);
42
+ }
43
+ return response.result;
44
+ }
45
+ }
46
+ /**
47
+ * The isomorphic carrier: runs the real protocol against an injected handler
48
+ * with no IPC at all. Tests exercise the exact envelope/result path a real
49
+ * carrier travels.
50
+ */
51
+ export class InProcessApiClient extends AbstractApiClient {
52
+ queue = [];
53
+ resolvers = [];
54
+ finished = false;
55
+ transport;
56
+ /**
57
+ * @param handler - the gateway-side unary entry (`handleClientRequest`).
58
+ */
59
+ constructor(handler) {
60
+ super();
61
+ this.transport = handler;
62
+ }
63
+ /** Deliver a host frame into the client's mux stream (test/pump side). */
64
+ pushFrame(frame) {
65
+ const resolver = this.resolvers.shift();
66
+ if (resolver !== undefined)
67
+ resolver({ done: false, value: frame });
68
+ else
69
+ this.queue.push(frame);
70
+ }
71
+ /** The mux stream as an async iterable; ends when {@link end} is called. */
72
+ frames() {
73
+ return {
74
+ [Symbol.asyncIterator]: () => ({
75
+ next: () => {
76
+ const frame = this.queue.shift();
77
+ if (frame !== undefined)
78
+ return Promise.resolve({ done: false, value: frame });
79
+ if (this.finished)
80
+ return Promise.resolve({ done: true, value: undefined });
81
+ return new Promise(resolve => this.resolvers.push(resolve));
82
+ },
83
+ }),
84
+ };
85
+ }
86
+ /** End the mux stream; pending and future iterations finish. */
87
+ end() {
88
+ this.finished = true;
89
+ for (const resolve of this.resolvers.splice(0))
90
+ resolve({ done: true, value: undefined });
91
+ }
92
+ }
93
+ //# sourceMappingURL=client.js.map
@@ -0,0 +1,99 @@
1
+ /**
2
+ * Single-source wire contracts: one {@link defineContract} declaration per
3
+ * domain yields everything a domain's wire surface needs — the rows that
4
+ * merge into the protocol's open maps (via `interface RpcMethodMap extends
5
+ * MethodRows<typeof contract> {}` in the same module), the request schemas
6
+ * that ride with registration, and the frame payload schemas for
7
+ * registration and client parsing. The hand-written trio (Api interface +
8
+ * merge rows + schema table) said the same thing three times; here it is
9
+ * said once.
10
+ *
11
+ * A row's response value type is declared through the phantom `res` field
12
+ * (the builders lie about it so the type is reachable without a runtime
13
+ * schema); runtime rows carry only `request` and, optionally, `response`.
14
+ *
15
+ * @module @snap-rail/protocol/contract
16
+ */
17
+ import type { z } from 'zod';
18
+ import type { RpcId, RpcResponse } from './rpc.ts';
19
+ /** One method row of a domain contract. */
20
+ export interface MethodRow<Req extends z.ZodType = z.ZodType, Res = unknown> {
21
+ /** The request schema — the trust-boundary validation at the host. */
22
+ request: Req;
23
+ /** Optional runtime response schema: adds the dispatch-time response
24
+ * self-check and the JSON Schema projection in `rpc.describe`. Absent in
25
+ * most rows: the response value type rides the phantom instead. */
26
+ response?: z.ZodType<Res>;
27
+ /** Phantom carrying the declared response value type; never present at
28
+ * runtime — the `method()` builders stamp it on the row's type only. */
29
+ readonly res: Res;
30
+ }
31
+ /**
32
+ * Open one method row: the request schema is mandatory (it is the
33
+ * trust-boundary validator), the response value type is declared through
34
+ * `.ret<T>()` or, with a runtime schema, `.res(schema)`.
35
+ *
36
+ * @param request - the request schema.
37
+ */
38
+ export declare function method<Req extends z.ZodType>(request: Req): {
39
+ /** Declare the response value type without a runtime schema. */
40
+ ret<Res>(): MethodRow<Req, Res>;
41
+ /** Declare the response value type and a schema that validates it. */
42
+ res<Res>(response: z.ZodType<Res>): MethodRow<Req, Res>;
43
+ };
44
+ /** The runtime shape every domain contract shares (what the gateway serves). */
45
+ export interface DomainContract {
46
+ /** The wire domain the contract belongs to (diagnostic metadata). */
47
+ readonly domain: string;
48
+ /** Method rows keyed by wire name (`domain.resource.verb`). */
49
+ readonly methods: Readonly<Record<string, MethodRow>>;
50
+ /** Frame payload schemas keyed by wire name (`domain/event`). */
51
+ readonly frames: Readonly<Record<string, z.ZodType>>;
52
+ }
53
+ /**
54
+ * Declare one domain's wire surface. Keys are full wire names; every
55
+ * conventional call site passes both tables (`methods: {}` when the domain
56
+ * only pushes frames, `frames: {}` when it only serves methods).
57
+ *
58
+ * @param domain - the wire domain (diagnostic metadata; claims are separate).
59
+ * @param def - the method and frame tables.
60
+ */
61
+ export declare function defineContract<const M extends Readonly<Record<string, MethodRow>>, const F extends Readonly<Record<string, z.ZodType>>>(domain: string, def: {
62
+ methods: M;
63
+ frames: F;
64
+ }): {
65
+ readonly domain: string;
66
+ readonly methods: M;
67
+ readonly frames: F;
68
+ };
69
+ /** The wire method signature one contract row yields (an `RpcMethodMap` row). */
70
+ export type WireMethodOf<Row extends MethodRow> = (payload: z.output<Row['request']>) => Promise<RpcResponse<Row['res']>>;
71
+ /**
72
+ * The `RpcMethodMap` rows a contract yields. Merge them from the contract's
73
+ * own module so importers of that module see the rows (the open-world rule):
74
+ *
75
+ * ```ts
76
+ * declare module '@snap-rail/protocol' {
77
+ * interface RpcMethodMap extends MethodRows<typeof pluginsContract> {}
78
+ * }
79
+ * ```
80
+ */
81
+ export type MethodRows<C extends DomainContract> = {
82
+ [K in keyof C['methods'] & string]: WireMethodOf<C['methods'][K]>;
83
+ };
84
+ /**
85
+ * The `FrameMap` rows a contract yields (payload = schema output); merged
86
+ * with `interface FrameMap extends FrameRows<typeof contract> {}`.
87
+ */
88
+ export type FrameRows<C extends DomainContract> = {
89
+ [K in keyof C['frames'] & string]: z.output<C['frames'][K]>;
90
+ };
91
+ /** One method handler as {@link ContractHandlers} requires: parsed payload
92
+ * in, response value out (business failures throw `RpcBusinessError`). */
93
+ export type ContractHandlerOf<Row extends MethodRow> = (payload: z.output<Row['request']>, rpcId: RpcId) => Row['res'] | Promise<Row['res']>;
94
+ /** The handler table `ctx.rpc.serveContract` requires for one contract,
95
+ * keyed by the same wire names as the contract's method rows. */
96
+ export type ContractHandlers<C extends DomainContract> = {
97
+ [K in keyof C['methods'] & string]: ContractHandlerOf<C['methods'][K]>;
98
+ };
99
+ //# sourceMappingURL=contract.d.ts.map
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Single-source wire contracts: one {@link defineContract} declaration per
3
+ * domain yields everything a domain's wire surface needs — the rows that
4
+ * merge into the protocol's open maps (via `interface RpcMethodMap extends
5
+ * MethodRows<typeof contract> {}` in the same module), the request schemas
6
+ * that ride with registration, and the frame payload schemas for
7
+ * registration and client parsing. The hand-written trio (Api interface +
8
+ * merge rows + schema table) said the same thing three times; here it is
9
+ * said once.
10
+ *
11
+ * A row's response value type is declared through the phantom `res` field
12
+ * (the builders lie about it so the type is reachable without a runtime
13
+ * schema); runtime rows carry only `request` and, optionally, `response`.
14
+ *
15
+ * @module @snap-rail/protocol/contract
16
+ */
17
+ /**
18
+ * Open one method row: the request schema is mandatory (it is the
19
+ * trust-boundary validator), the response value type is declared through
20
+ * `.ret<T>()` or, with a runtime schema, `.res(schema)`.
21
+ *
22
+ * @param request - the request schema.
23
+ */
24
+ export function method(request) {
25
+ return {
26
+ ret() {
27
+ return { request };
28
+ },
29
+ res(response) {
30
+ return { request, response };
31
+ },
32
+ };
33
+ }
34
+ /**
35
+ * Declare one domain's wire surface. Keys are full wire names; every
36
+ * conventional call site passes both tables (`methods: {}` when the domain
37
+ * only pushes frames, `frames: {}` when it only serves methods).
38
+ *
39
+ * @param domain - the wire domain (diagnostic metadata; claims are separate).
40
+ * @param def - the method and frame tables.
41
+ */
42
+ export function defineContract(domain, def) {
43
+ return { domain, methods: def.methods, frames: def.frames };
44
+ }
45
+ //# sourceMappingURL=contract.js.map
@@ -0,0 +1,26 @@
1
+ /**
2
+ * The frame table base: every push frame (a host-initiated `ServerRequest`)
3
+ * is keyed by its wire frame name in `FrameMap`, the twin of
4
+ * {@link RpcMethodMap} for the host-initiated quadrant. This module holds
5
+ * the OPEN merge base only — every domain's rows live with its owner's
6
+ * contract module (field → `@snap-rail/equipment` `./wire`, ModbusTCP →
7
+ * `@snap-rail/driver-modbus/contract`, station →
8
+ * `@snap-rail/station-rpc/contract`, production stats →
9
+ * `@snap-rail/process-production/contract`). A program sees the rows of
10
+ * every contract it imports — the open-world rule.
11
+ *
12
+ * Naming: frames are `domain/event` — kebab-case segments joined by `/` —
13
+ * while methods are `domain.resource.verb` joined by `.`. The first frame
14
+ * segment is the owning domain, the same vocabulary method domains use;
15
+ * `ctx.rpc.claimDomain` guards both.
16
+ *
17
+ * @module @snap-rail/protocol/frames
18
+ */
19
+ /** Payload type per frame name; open for declaration merging. */
20
+ export interface FrameMap {
21
+ }
22
+ /** Frame names on the wire. */
23
+ export type FrameName = keyof FrameMap & string;
24
+ /** The payload type of a frame, derived from its row. */
25
+ export type FramePayload<K extends FrameName> = FrameMap[K];
26
+ //# sourceMappingURL=frames.d.ts.map
@@ -0,0 +1,20 @@
1
+ /**
2
+ * The frame table base: every push frame (a host-initiated `ServerRequest`)
3
+ * is keyed by its wire frame name in `FrameMap`, the twin of
4
+ * {@link RpcMethodMap} for the host-initiated quadrant. This module holds
5
+ * the OPEN merge base only — every domain's rows live with its owner's
6
+ * contract module (field → `@snap-rail/equipment` `./wire`, ModbusTCP →
7
+ * `@snap-rail/driver-modbus/contract`, station →
8
+ * `@snap-rail/station-rpc/contract`, production stats →
9
+ * `@snap-rail/process-production/contract`). A program sees the rows of
10
+ * every contract it imports — the open-world rule.
11
+ *
12
+ * Naming: frames are `domain/event` — kebab-case segments joined by `/` —
13
+ * while methods are `domain.resource.verb` joined by `.`. The first frame
14
+ * segment is the owning domain, the same vocabulary method domains use;
15
+ * `ctx.rpc.claimDomain` guards both.
16
+ *
17
+ * @module @snap-rail/protocol/frames
18
+ */
19
+ export {};
20
+ //# sourceMappingURL=frames.js.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The channel-independent RPC contract between host and clients: the
3
+ * four-quadrant message model, the open method and frame merge bases,
4
+ * boundary schemas, and the client carrier family.
5
+ *
6
+ * @module @snap-rail/protocol
7
+ */
8
+ export * from './rpc.ts';
9
+ export * from './methods.ts';
10
+ export * from './frames.ts';
11
+ export * from './contract.ts';
12
+ export * from './schemas.ts';
13
+ export * from './client.ts';
14
+ //# sourceMappingURL=index.d.ts.map
@@ -0,0 +1,14 @@
1
+ /**
2
+ * The channel-independent RPC contract between host and clients: the
3
+ * four-quadrant message model, the open method and frame merge bases,
4
+ * boundary schemas, and the client carrier family.
5
+ *
6
+ * @module @snap-rail/protocol
7
+ */
8
+ export * from "./rpc.js";
9
+ export * from "./methods.js";
10
+ export * from "./frames.js";
11
+ export * from "./contract.js";
12
+ export * from "./schemas.js";
13
+ export * from "./client.js";
14
+ //# sourceMappingURL=index.js.map
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The platform domain's method rows plus the open bases themselves: the
3
+ * wire's platform surface is `host.*` and `window.*` (transport-adjacent,
4
+ * owned by the gateway and the shell). Every other domain's rows live with
5
+ * their owners and merge in from their contract modules:
6
+ * field → `@snap-rail/equipment` (`./wire`), ModbusTCP →
7
+ * `@snap-rail/driver-modbus/contract`, station → `@snap-rail/station-rpc/contract`,
8
+ * plugin admin → `@snap-rail/app-boot/contract`. A program sees the rows of
9
+ * every contract it imports — the open-world rule.
10
+ *
11
+ * Reserved-method discipline: the map holds only implemented methods; an
12
+ * unknown method fails loud at dispatch (`bad-request`) — no
13
+ * not-implemented fallback code.
14
+ *
15
+ * @module @snap-rail/protocol/methods
16
+ */
17
+ import type { RpcResponse } from './rpc.ts';
18
+ /** Host-level introspection. */
19
+ export interface HostApi {
20
+ /** Describe the running application: identity for handshakes and About panels. */
21
+ describe(payload: {}): Promise<RpcResponse<{
22
+ name: string;
23
+ version: string;
24
+ bin: string;
25
+ }>>;
26
+ }
27
+ /** One wire domain as `rpc.describe` serves it. */
28
+ export interface DomainInfo {
29
+ /** The claimed prefix (`field`, `field.modbus`). */
30
+ prefix: string;
31
+ /** The claiming plugin's fiber name. */
32
+ owner: string;
33
+ }
34
+ /** One registered method as `rpc.describe` serves it. */
35
+ export interface MethodInfo {
36
+ name: string;
37
+ /** The request schema as JSON Schema (omitted when not representable). */
38
+ requestSchema?: unknown;
39
+ /** The optional response schema as JSON Schema. */
40
+ responseSchema?: unknown;
41
+ }
42
+ /** One registered frame as `rpc.describe` serves it. */
43
+ export interface FrameInfo {
44
+ name: string;
45
+ /** The payload schema as JSON Schema (omitted when not representable). */
46
+ payloadSchema?: unknown;
47
+ }
48
+ /** Wire-level capability discovery. */
49
+ export interface RpcIntrospectApi {
50
+ /** Every live domain claim, method route, and frame registration — the
51
+ * surface an external tool (settings UI, agent, future plugin installer)
52
+ * lists before calling. */
53
+ describe(payload: {}): Promise<RpcResponse<{
54
+ domains: readonly DomainInfo[];
55
+ methods: readonly MethodInfo[];
56
+ frames: readonly FrameInfo[];
57
+ }>>;
58
+ }
59
+ /**
60
+ * Native window controls for frameless shells. Controls drive the main
61
+ * window.
62
+ */
63
+ export interface WindowApi {
64
+ /** Apply a window action (`minimize`, `toggle-maximize`, `close`); `false` when no window exists to act on. */
65
+ control(payload: {
66
+ action: 'minimize' | 'toggle-maximize' | 'close';
67
+ }): Promise<RpcResponse<{
68
+ applied: boolean;
69
+ }>>;
70
+ /** Native zip picker for the plugin installer; `null` when cancelled. */
71
+ pickZip(payload: {
72
+ title?: string | undefined;
73
+ }): Promise<RpcResponse<string | null>>;
74
+ /** Native zip saver (generated-plugin export); `null` when cancelled. */
75
+ saveZip(payload: {
76
+ title?: string | undefined;
77
+ defaultFileName: string;
78
+ }): Promise<RpcResponse<string | null>>;
79
+ /** Relaunch the app (suite switches need a fresh boot to remount). */
80
+ relaunch(payload: Record<string, never>): Promise<RpcResponse<{
81
+ applied: true;
82
+ }>>;
83
+ }
84
+ /** Every unary method callable by a client, keyed by its wire method name.
85
+ * Open for declaration merging — see the module note for where rows live. */
86
+ export interface RpcMethodMap {
87
+ 'host.describe': HostApi['describe'];
88
+ 'rpc.describe': RpcIntrospectApi['describe'];
89
+ 'window.control': WindowApi['control'];
90
+ 'window.pick-zip': WindowApi['pickZip'];
91
+ 'window.save-zip': WindowApi['saveZip'];
92
+ 'window.relaunch': WindowApi['relaunch'];
93
+ }
94
+ /** Method names on the wire. */
95
+ export type MethodName = keyof RpcMethodMap & string;
96
+ /** The request payload type of a method, derived from its signature. */
97
+ export type RequestPayload<K extends MethodName> = Parameters<RpcMethodMap[K]>[0];
98
+ /** The success value type of a method, derived from its signature. */
99
+ export type ResponseValue<K extends MethodName> = Awaited<ReturnType<RpcMethodMap[K]>> extends RpcResponse<infer T> ? T : never;
100
+ //# sourceMappingURL=methods.d.ts.map
@@ -0,0 +1,18 @@
1
+ /**
2
+ * The platform domain's method rows plus the open bases themselves: the
3
+ * wire's platform surface is `host.*` and `window.*` (transport-adjacent,
4
+ * owned by the gateway and the shell). Every other domain's rows live with
5
+ * their owners and merge in from their contract modules:
6
+ * field → `@snap-rail/equipment` (`./wire`), ModbusTCP →
7
+ * `@snap-rail/driver-modbus/contract`, station → `@snap-rail/station-rpc/contract`,
8
+ * plugin admin → `@snap-rail/app-boot/contract`. A program sees the rows of
9
+ * every contract it imports — the open-world rule.
10
+ *
11
+ * Reserved-method discipline: the map holds only implemented methods; an
12
+ * unknown method fails loud at dispatch (`bad-request`) — no
13
+ * not-implemented fallback code.
14
+ *
15
+ * @module @snap-rail/protocol/methods
16
+ */
17
+ export {};
18
+ //# sourceMappingURL=methods.js.map
@@ -0,0 +1,132 @@
1
+ /**
2
+ * The four-quadrant message model: every logical message is classified by
3
+ * "who initiates × request/response", decoupled from the physical channel.
4
+ * Swapping the carrier (in-process, Electron IPC, a future WebSocket) leaves
5
+ * the quadrants unchanged; direction is a property of the message, never
6
+ * inferred from the channel.
7
+ *
8
+ * rpcId discipline: whoever initiates mints; a response always echoes the
9
+ * corresponding request's rpcId and never mints a new id. Pure-push frames
10
+ * mint a fresh id per push; answerable frames (a future approval/question
11
+ * family) reuse one stable id until answered.
12
+ *
13
+ * @module @snap-rail/protocol/rpc
14
+ */
15
+ import type { Branded } from '@snap-rail/util';
16
+ /** Identifier correlating a request with its response. */
17
+ export type RpcId = Branded<string, 'RpcId'>;
18
+ /** Mint an rpc identifier. Only carriers and frame pumps mint; business code never does. */
19
+ export declare function RpcId(value: string): RpcId;
20
+ /** ① A client-initiated request: call a host method.
21
+ * @param rpcId - minted by the client.
22
+ * @param method - the method key; also the discriminator handlers dispatch on.
23
+ * @param payload - the business payload, validated per method at the host.
24
+ */
25
+ export interface ClientRequest {
26
+ type: 'client-request';
27
+ rpcId: RpcId;
28
+ method: string;
29
+ payload: unknown;
30
+ }
31
+ /** ② The response to a {@link ClientRequest}. Always echoes its rpcId.
32
+ * @param rpcId - echoed from the request; never minted here.
33
+ * @param result - business outcome; methods do not throw business errors.
34
+ */
35
+ export interface ServerResponse {
36
+ type: 'server-response';
37
+ rpcId: RpcId;
38
+ result: RpcResult<unknown>;
39
+ }
40
+ /** ③ A host-initiated request: a push frame (or a future answerable request).
41
+ * @param rpcId - minted by the host frame pump; fresh per push frame.
42
+ * @param method - the frame type.
43
+ * @param payload - the frame payload.
44
+ */
45
+ export interface ServerRequest {
46
+ type: 'server-request';
47
+ rpcId: RpcId;
48
+ method: string;
49
+ payload: unknown;
50
+ }
51
+ /** ④ The response to a {@link ServerRequest}. Always echoes its rpcId. */
52
+ export interface ClientResponse {
53
+ type: 'client-response';
54
+ rpcId: RpcId;
55
+ result: RpcResult<unknown>;
56
+ }
57
+ /** Every wire message; narrowed via `switch (message.type)`. */
58
+ export type RpcMessage = ClientRequest | ServerResponse | ServerRequest | ClientResponse;
59
+ /** Business outcome of a method. Transport failures are carrier exceptions; the two layers never mix. */
60
+ export type RpcResult<T> = {
61
+ ok: true;
62
+ value: T;
63
+ } | {
64
+ ok: false;
65
+ error: RpcError;
66
+ };
67
+ /** Details required per error code; adding a code = one map row (compile-checked). */
68
+ export interface RpcErrorDetailsMap {
69
+ 'bad-request': {
70
+ issues: readonly string[];
71
+ };
72
+ 'not-found': {
73
+ what: string;
74
+ };
75
+ 'conflict': {
76
+ what: string;
77
+ };
78
+ 'unavailable': {
79
+ what: string;
80
+ };
81
+ 'internal': {
82
+ hint?: string;
83
+ };
84
+ }
85
+ /** Discriminated error union; `code` discriminates, `details` narrows. */
86
+ export type RpcError = {
87
+ [K in keyof RpcErrorDetailsMap]: {
88
+ code: K;
89
+ details: RpcErrorDetailsMap[K];
90
+ };
91
+ }[keyof RpcErrorDetailsMap];
92
+ /** Narrow request form seen by typed signatures; carriers complete it into a full form. */
93
+ export type RpcRequest<P> = {
94
+ rpcId: RpcId;
95
+ payload: P;
96
+ };
97
+ /** Narrow response form seen by typed signatures. */
98
+ export type RpcResponse<T> = {
99
+ rpcId: RpcId;
100
+ result: RpcResult<T>;
101
+ };
102
+ /**
103
+ * Construct a success result.
104
+ * @param value - the method's return value.
105
+ */
106
+ export declare function ok<T>(value: T): RpcResult<T>;
107
+ /**
108
+ * Construct a business-error result.
109
+ * @param code - the error code.
110
+ * @param details - code-specific details (required).
111
+ */
112
+ export declare function err<K extends keyof RpcErrorDetailsMap>(code: K, details: RpcErrorDetailsMap[K]): {
113
+ ok: false;
114
+ error: Extract<RpcError, {
115
+ code: K;
116
+ }>;
117
+ };
118
+ /**
119
+ * Thrown by method handlers to fail with a business error; the gateway
120
+ * converts it into `{ ok: false, error }` on the wire. Carrying it as a
121
+ * throw keeps handler happy paths free of result wrapping.
122
+ */
123
+ export declare class RpcBusinessError extends Error {
124
+ readonly error: RpcError;
125
+ constructor(error: RpcError);
126
+ }
127
+ /**
128
+ * Type guard narrowing an unknown value to {@link RpcError}.
129
+ * @param value - candidate error.
130
+ */
131
+ export declare function isRpcError(value: unknown): value is RpcError;
132
+ //# sourceMappingURL=rpc.d.ts.map
@@ -0,0 +1,57 @@
1
+ /**
2
+ * The four-quadrant message model: every logical message is classified by
3
+ * "who initiates × request/response", decoupled from the physical channel.
4
+ * Swapping the carrier (in-process, Electron IPC, a future WebSocket) leaves
5
+ * the quadrants unchanged; direction is a property of the message, never
6
+ * inferred from the channel.
7
+ *
8
+ * rpcId discipline: whoever initiates mints; a response always echoes the
9
+ * corresponding request's rpcId and never mints a new id. Pure-push frames
10
+ * mint a fresh id per push; answerable frames (a future approval/question
11
+ * family) reuse one stable id until answered.
12
+ *
13
+ * @module @snap-rail/protocol/rpc
14
+ */
15
+ /** Mint an rpc identifier. Only carriers and frame pumps mint; business code never does. */
16
+ export function RpcId(value) {
17
+ return value;
18
+ }
19
+ /**
20
+ * Construct a success result.
21
+ * @param value - the method's return value.
22
+ */
23
+ export function ok(value) {
24
+ return { ok: true, value };
25
+ }
26
+ /**
27
+ * Construct a business-error result.
28
+ * @param code - the error code.
29
+ * @param details - code-specific details (required).
30
+ */
31
+ export function err(code, details) {
32
+ return { ok: false, error: { code, details } };
33
+ }
34
+ /**
35
+ * Thrown by method handlers to fail with a business error; the gateway
36
+ * converts it into `{ ok: false, error }` on the wire. Carrying it as a
37
+ * throw keeps handler happy paths free of result wrapping.
38
+ */
39
+ export class RpcBusinessError extends Error {
40
+ error;
41
+ constructor(error) {
42
+ super(`rpc business error: ${error.code}`);
43
+ this.error = error;
44
+ this.name = 'RpcBusinessError';
45
+ }
46
+ }
47
+ /**
48
+ * Type guard narrowing an unknown value to {@link RpcError}.
49
+ * @param value - candidate error.
50
+ */
51
+ export function isRpcError(value) {
52
+ if (value === null || typeof value !== 'object')
53
+ return false;
54
+ const record = value;
55
+ return typeof record.code === 'string' && 'details' in record;
56
+ }
57
+ //# sourceMappingURL=rpc.js.map
@@ -0,0 +1,25 @@
1
+ /**
2
+ * Envelope validation at the trust boundary: the type/rpcId/method
3
+ * structure of every inbound message. Per-method payload schemas travel
4
+ * with each registration (`ctx.rpc.method`) — there is no central method
5
+ * table. Host responses are produced by trusted code and are not
6
+ * re-validated in phase 1.
7
+ *
8
+ * @module @snap-rail/protocol/schemas
9
+ */
10
+ import { type ClientRequest, type ServerRequest } from './rpc.ts';
11
+ /**
12
+ * Parse an inbound client request envelope.
13
+ * @param raw - the untrusted wire value.
14
+ * @returns the parsed envelope with a branded rpcId.
15
+ * @throws a zod error naming every envelope violation.
16
+ */
17
+ export declare function parseClientRequest(raw: unknown): ClientRequest;
18
+ /**
19
+ * Parse an inbound host frame on a client.
20
+ * @param raw - the untrusted wire value.
21
+ * @returns the parsed frame.
22
+ * @throws a zod error naming every envelope violation.
23
+ */
24
+ export declare function parseServerRequest(raw: unknown): ServerRequest;
25
+ //# sourceMappingURL=schemas.d.ts.map
@@ -0,0 +1,43 @@
1
+ /**
2
+ * Envelope validation at the trust boundary: the type/rpcId/method
3
+ * structure of every inbound message. Per-method payload schemas travel
4
+ * with each registration (`ctx.rpc.method`) — there is no central method
5
+ * table. Host responses are produced by trusted code and are not
6
+ * re-validated in phase 1.
7
+ *
8
+ * @module @snap-rail/protocol/schemas
9
+ */
10
+ import { z } from 'zod';
11
+ import { RpcId } from "./rpc.js";
12
+ const rpcIdSchema = z.string().min(1).transform(RpcId);
13
+ const clientRequestShape = z.object({
14
+ type: z.literal('client-request'),
15
+ rpcId: rpcIdSchema,
16
+ method: z.string().min(1),
17
+ payload: z.unknown(),
18
+ });
19
+ /**
20
+ * Parse an inbound client request envelope.
21
+ * @param raw - the untrusted wire value.
22
+ * @returns the parsed envelope with a branded rpcId.
23
+ * @throws a zod error naming every envelope violation.
24
+ */
25
+ export function parseClientRequest(raw) {
26
+ return clientRequestShape.parse(raw);
27
+ }
28
+ const serverRequestShape = z.object({
29
+ type: z.literal('server-request'),
30
+ rpcId: rpcIdSchema,
31
+ method: z.string().min(1),
32
+ payload: z.unknown(),
33
+ });
34
+ /**
35
+ * Parse an inbound host frame on a client.
36
+ * @param raw - the untrusted wire value.
37
+ * @returns the parsed frame.
38
+ * @throws a zod error naming every envelope violation.
39
+ */
40
+ export function parseServerRequest(raw) {
41
+ return serverRequestShape.parse(raw);
42
+ }
43
+ //# sourceMappingURL=schemas.js.map
package/package.json CHANGED
@@ -1,6 +1,28 @@
1
1
  {
2
2
  "name": "@snap-rail/protocol",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
3
+ "description": "Channel-independent four-quadrant RPC contract between host and clients",
4
+ "version": "0.1.1",
5
+ "type": "module",
6
+ "main": "lib/index.js",
7
+ "types": "lib/types/index.d.ts",
8
+ "exports": {
9
+ ".": {
10
+ "types": "./lib/types/index.d.ts",
11
+ "default": "./lib/index.js"
12
+ },
13
+ "./src/*": "./src/*",
14
+ "./package.json": "./package.json"
15
+ },
16
+ "files": [
17
+ "lib/**/*.js",
18
+ "lib/types/**/*.d.ts"
19
+ ],
20
+ "license": "Apache-2.0",
21
+ "dependencies": {
22
+ "zod": "^4.4.3",
23
+ "@snap-rail/util": "^0.1.2"
24
+ },
25
+ "snapRail": {
26
+ "layer": "base"
27
+ }
6
28
  }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
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.