@lostgradient/backchannel 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (227) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +62 -2
  3. package/dist/access-policy-metadata.d.ts +92 -0
  4. package/dist/access-policy-metadata.js +87 -0
  5. package/dist/asyncapi-channels.d.ts +46 -0
  6. package/dist/asyncapi-channels.js +399 -0
  7. package/dist/asyncapi.d.ts +40 -0
  8. package/dist/asyncapi.js +165 -0
  9. package/dist/authentication/api-key.d.ts +4 -0
  10. package/dist/authentication/api-key.js +114 -0
  11. package/dist/authentication/audit.d.ts +115 -0
  12. package/dist/authentication/audit.js +75 -0
  13. package/dist/authentication/credential-verifiers.d.ts +60 -0
  14. package/dist/authentication/credential-verifiers.js +102 -0
  15. package/dist/authentication/crypto.d.ts +7 -0
  16. package/dist/authentication/crypto.js +140 -0
  17. package/dist/authentication/index.d.ts +80 -0
  18. package/dist/authentication/index.js +212 -0
  19. package/dist/authentication/rate-limiter.d.ts +133 -0
  20. package/dist/authentication/rate-limiter.js +124 -0
  21. package/dist/authentication/redaction.d.ts +72 -0
  22. package/dist/authentication/redaction.js +118 -0
  23. package/dist/authentication/rotating-api-key-store.d.ts +127 -0
  24. package/dist/authentication/rotating-api-key-store.js +126 -0
  25. package/dist/authentication/types.d.ts +337 -0
  26. package/dist/authentication/types.js +26 -0
  27. package/dist/authentication.d.ts +1 -0
  28. package/dist/authentication.js +1 -0
  29. package/dist/authorization-scope.d.ts +109 -0
  30. package/dist/authorization-scope.js +144 -0
  31. package/dist/authorization.d.ts +55 -0
  32. package/dist/authorization.js +134 -0
  33. package/dist/bind-feed-lifetime.d.ts +45 -0
  34. package/dist/bind-feed-lifetime.js +55 -0
  35. package/dist/byte-arrays.d.ts +5 -0
  36. package/dist/byte-arrays.js +9 -0
  37. package/dist/client/catalog-client.d.ts +285 -0
  38. package/dist/client/catalog-client.js +74 -0
  39. package/dist/client/in-process-transport.d.ts +19 -0
  40. package/dist/client/in-process-transport.js +136 -0
  41. package/dist/client/index.d.ts +14 -0
  42. package/dist/client/index.js +14 -0
  43. package/dist/client/json-rpc-http-transport.d.ts +118 -0
  44. package/dist/client/json-rpc-http-transport.js +127 -0
  45. package/dist/client/server-sent-event-parser.d.ts +55 -0
  46. package/dist/client/server-sent-event-parser.js +78 -0
  47. package/dist/client/sse-subscription-transport.d.ts +72 -0
  48. package/dist/client/sse-subscription-transport.js +224 -0
  49. package/dist/client/subscription-client.d.ts +122 -0
  50. package/dist/client/subscription-client.js +28 -0
  51. package/dist/connection-lease.d.ts +10 -0
  52. package/dist/connection-lease.js +8 -0
  53. package/dist/discovery-filter.d.ts +13 -0
  54. package/dist/discovery-filter.js +16 -0
  55. package/dist/discovery-info.d.ts +94 -0
  56. package/dist/discovery-info.js +38 -0
  57. package/dist/event-selector.d.ts +7 -0
  58. package/dist/event-selector.js +7 -0
  59. package/dist/fault-code.d.ts +84 -0
  60. package/dist/fault-code.js +114 -0
  61. package/dist/fault-remediation.d.ts +30 -0
  62. package/dist/fault-remediation.js +52 -0
  63. package/dist/fault-to-http.d.ts +11 -0
  64. package/dist/fault-to-http.js +13 -0
  65. package/dist/fault-to-json-rpc.d.ts +53 -0
  66. package/dist/fault-to-json-rpc.js +143 -0
  67. package/dist/fault-wire-safety.d.ts +45 -0
  68. package/dist/fault-wire-safety.js +72 -0
  69. package/dist/generator.d.ts +9 -0
  70. package/dist/generator.js +9 -0
  71. package/dist/handler/auth-context-principal.d.ts +37 -0
  72. package/dist/handler/auth-context-principal.js +67 -0
  73. package/dist/handler/authentication-responses.d.ts +23 -0
  74. package/dist/handler/authentication-responses.js +34 -0
  75. package/dist/handler/json-responses.d.ts +15 -0
  76. package/dist/handler/json-responses.js +32 -0
  77. package/dist/handler/operation-handler-authentication.d.ts +64 -0
  78. package/dist/handler/operation-handler-authentication.js +58 -0
  79. package/dist/handler/operation-handler-discovery.d.ts +29 -0
  80. package/dist/handler/operation-handler-discovery.js +55 -0
  81. package/dist/handler/operation-handler-mounts.d.ts +100 -0
  82. package/dist/handler/operation-handler-mounts.js +134 -0
  83. package/dist/handler/operation-handler-subscription.d.ts +34 -0
  84. package/dist/handler/operation-handler-subscription.js +112 -0
  85. package/dist/handler/operation-handler.d.ts +162 -0
  86. package/dist/handler/operation-handler.js +236 -0
  87. package/dist/handler/workspace-release.d.ts +6 -0
  88. package/dist/handler/workspace-release.js +75 -0
  89. package/dist/in-memory-replay-live-backend.d.ts +47 -0
  90. package/dist/in-memory-replay-live-backend.js +129 -0
  91. package/dist/index.d.ts +37 -0
  92. package/dist/index.js +30 -0
  93. package/dist/internal/cryptography/encryption.d.ts +108 -0
  94. package/dist/internal/cryptography/encryption.js +241 -0
  95. package/dist/internal/cryptography/hash.d.ts +72 -0
  96. package/dist/internal/cryptography/hash.js +233 -0
  97. package/dist/internal/cryptography/index.d.ts +4 -0
  98. package/dist/internal/cryptography/index.js +2 -0
  99. package/dist/internals.d.ts +58 -0
  100. package/dist/internals.js +54 -0
  101. package/dist/json-rpc-dispatch.d.ts +88 -0
  102. package/dist/json-rpc-dispatch.js +154 -0
  103. package/dist/json-rpc-framing.d.ts +42 -0
  104. package/dist/json-rpc-framing.js +50 -0
  105. package/dist/json-rpc-http.d.ts +36 -0
  106. package/dist/json-rpc-http.js +191 -0
  107. package/dist/json-rpc-parse.d.ts +69 -0
  108. package/dist/json-rpc-parse.js +206 -0
  109. package/dist/json-rpc-protocol.d.ts +76 -0
  110. package/dist/json-rpc-protocol.js +54 -0
  111. package/dist/json-rpc-session-runtime.d.ts +55 -0
  112. package/dist/json-rpc-session-runtime.js +111 -0
  113. package/dist/json-rpc-websocket-subscription-pump.d.ts +9 -0
  114. package/dist/json-rpc-websocket-subscription-pump.js +46 -0
  115. package/dist/json-rpc-websocket-subscriptions.d.ts +10 -0
  116. package/dist/json-rpc-websocket-subscriptions.js +33 -0
  117. package/dist/json-rpc-websocket-types.d.ts +34 -0
  118. package/dist/json-rpc-websocket-types.js +1 -0
  119. package/dist/json-rpc-websocket-validation.d.ts +45 -0
  120. package/dist/json-rpc-websocket-validation.js +154 -0
  121. package/dist/json-rpc-websocket.d.ts +20 -0
  122. package/dist/json-rpc-websocket.js +363 -0
  123. package/dist/json-schema-utilities.d.ts +5 -0
  124. package/dist/json-schema-utilities.js +17 -0
  125. package/dist/mcp-discovery-names.d.ts +11 -0
  126. package/dist/mcp-discovery-names.js +11 -0
  127. package/dist/openapi-canonical-json.d.ts +10 -0
  128. package/dist/openapi-canonical-json.js +23 -0
  129. package/dist/openapi-error-responses.d.ts +15 -0
  130. package/dist/openapi-error-responses.js +104 -0
  131. package/dist/openapi-schemas.d.ts +17 -0
  132. package/dist/openapi-schemas.js +94 -0
  133. package/dist/openapi.d.ts +60 -0
  134. package/dist/openapi.js +351 -0
  135. package/dist/openrpc-document-schema.d.ts +255 -0
  136. package/dist/openrpc-document-schema.js +84 -0
  137. package/dist/openrpc-errors.d.ts +93 -0
  138. package/dist/openrpc-errors.js +134 -0
  139. package/dist/openrpc.d.ts +66 -0
  140. package/dist/openrpc.js +260 -0
  141. package/dist/operation-catalog/behavior-types.d.ts +34 -0
  142. package/dist/operation-catalog/behavior-types.js +1 -0
  143. package/dist/operation-catalog/behavior-validation.d.ts +3 -0
  144. package/dist/operation-catalog/behavior-validation.js +298 -0
  145. package/dist/operation-catalog/dispatch-allowlist.d.ts +4 -0
  146. package/dist/operation-catalog/dispatch-allowlist.js +7 -0
  147. package/dist/operation-catalog/dispatch-preparation.d.ts +24 -0
  148. package/dist/operation-catalog/dispatch-preparation.js +49 -0
  149. package/dist/operation-catalog/index.d.ts +19 -0
  150. package/dist/operation-catalog/index.js +17 -0
  151. package/dist/operation-catalog/operation-dispatch.d.ts +14 -0
  152. package/dist/operation-catalog/operation-dispatch.js +115 -0
  153. package/dist/operation-catalog/operation-interceptors.d.ts +15 -0
  154. package/dist/operation-catalog/operation-interceptors.js +1 -0
  155. package/dist/operation-catalog/operation-metadata.d.ts +5 -0
  156. package/dist/operation-catalog/operation-metadata.js +104 -0
  157. package/dist/operation-catalog/pipeline-helpers.d.ts +70 -0
  158. package/dist/operation-catalog/pipeline-helpers.js +242 -0
  159. package/dist/operation-catalog/pipeline-stages.d.ts +23 -0
  160. package/dist/operation-catalog/pipeline-stages.js +226 -0
  161. package/dist/operation-catalog/pipeline.d.ts +7 -0
  162. package/dist/operation-catalog/pipeline.js +33 -0
  163. package/dist/operation-catalog/registry.d.ts +17 -0
  164. package/dist/operation-catalog/registry.js +132 -0
  165. package/dist/operation-catalog/stream-pipeline.d.ts +37 -0
  166. package/dist/operation-catalog/stream-pipeline.js +129 -0
  167. package/dist/operation-catalog/subscription-lifecycle.d.ts +6 -0
  168. package/dist/operation-catalog/subscription-lifecycle.js +27 -0
  169. package/dist/operation-catalog/types.d.ts +392 -0
  170. package/dist/operation-catalog/types.js +40 -0
  171. package/dist/operation-catalog/universal-faults.d.ts +11 -0
  172. package/dist/operation-catalog/universal-faults.js +15 -0
  173. package/dist/operation-catalog-snapshot.d.ts +215 -0
  174. package/dist/operation-catalog-snapshot.js +128 -0
  175. package/dist/operation-catalog.d.ts +1 -0
  176. package/dist/operation-catalog.js +1 -0
  177. package/dist/operation-description-audit.d.ts +44 -0
  178. package/dist/operation-description-audit.js +90 -0
  179. package/dist/operation-fault-helpers.d.ts +21 -0
  180. package/dist/operation-fault-helpers.js +32 -0
  181. package/dist/operation-fault.d.ts +245 -0
  182. package/dist/operation-fault.js +235 -0
  183. package/dist/operation-registry.d.ts +46 -0
  184. package/dist/operation-registry.js +46 -0
  185. package/dist/operations/closable-iterable.d.ts +23 -0
  186. package/dist/operations/closable-iterable.js +51 -0
  187. package/dist/operations/get-principal.d.ts +106 -0
  188. package/dist/operations/get-principal.js +107 -0
  189. package/dist/operations/sse-stream.d.ts +67 -0
  190. package/dist/operations/sse-stream.js +264 -0
  191. package/dist/principal.d.ts +253 -0
  192. package/dist/principal.js +254 -0
  193. package/dist/replay-live-feed-internals.d.ts +47 -0
  194. package/dist/replay-live-feed-internals.js +215 -0
  195. package/dist/replay-live-feed-types.d.ts +66 -0
  196. package/dist/replay-live-feed-types.js +7 -0
  197. package/dist/replay-live-feed.d.ts +49 -0
  198. package/dist/replay-live-feed.js +126 -0
  199. package/dist/rest-binding.d.ts +215 -0
  200. package/dist/rest-binding.js +95 -0
  201. package/dist/rest-body.d.ts +17 -0
  202. package/dist/rest-body.js +95 -0
  203. package/dist/route-model.d.ts +305 -0
  204. package/dist/route-model.js +320 -0
  205. package/dist/runtime/cors.d.ts +161 -0
  206. package/dist/runtime/cors.js +265 -0
  207. package/dist/scripts/generate-operation-client.d.ts +186 -0
  208. package/dist/scripts/generate-operation-client.js +561 -0
  209. package/dist/scripts/operation-behaviors.d.ts +3 -0
  210. package/dist/scripts/operation-behaviors.js +16 -0
  211. package/dist/scripts/operation-client-aliases.d.ts +32 -0
  212. package/dist/scripts/operation-client-aliases.js +255 -0
  213. package/dist/scripts/operation-client-domains.d.ts +21 -0
  214. package/dist/scripts/operation-client-domains.js +74 -0
  215. package/dist/scripts/operation-client-schema.d.ts +46 -0
  216. package/dist/scripts/operation-client-schema.js +310 -0
  217. package/dist/scripts/operation-client-svelte.d.ts +3 -0
  218. package/dist/scripts/operation-client-svelte.js +61 -0
  219. package/dist/sequence-cursor.d.ts +46 -0
  220. package/dist/sequence-cursor.js +62 -0
  221. package/dist/sse-error-payload-schema.d.ts +12 -0
  222. package/dist/sse-error-payload-schema.js +33 -0
  223. package/dist/stdio-session.d.ts +71 -0
  224. package/dist/stdio-session.js +347 -0
  225. package/dist/zod-json-schema.d.ts +22 -0
  226. package/dist/zod-json-schema.js +49 -0
  227. package/package.json +38 -3
@@ -0,0 +1,55 @@
1
+ /**
2
+ * The socket-side runtime of a JSON-RPC WebSocket session that names no server: what a socket must
3
+ * offer (`data`, `send`, `close`), the per-socket state the session keeps, and the functions that
4
+ * open a session on a socket, feed it frames, and close it. Runtime-free, so any host that can
5
+ * hand over a socket of this shape can serve a catalog.
6
+ *
7
+ * @module server/json-rpc-session-runtime
8
+ */
9
+ import { type JsonRpcWebSocketSession } from "./json-rpc-websocket.js";
10
+ import type { OperationRegistry } from "./operation-catalog.js";
11
+ import { type Principal } from "./principal.js";
12
+ /** The part of a WebSocket a session uses. Bun's `ServerWebSocket` satisfies it. */
13
+ export type JsonRpcSocket<Data> = {
14
+ readonly data: Data;
15
+ send(message: string): unknown;
16
+ close(code?: number, reason?: string): void;
17
+ };
18
+ /** What a session keeps on its socket. */
19
+ export interface JsonRpcSocketData {
20
+ /** The path the socket upgraded on. */
21
+ pathname: string;
22
+ /** The kind of connection, for logging. */
23
+ connectionType: string;
24
+ /** The authenticated caller. */
25
+ principal?: Principal;
26
+ /** The session attached to the socket. */
27
+ jsonRpcSession?: JsonRpcWebSocketSession;
28
+ /** Current workspace authority, captured from the authenticated upgrade request. */
29
+ revalidateWorkspace?: () => Promise<boolean>;
30
+ /** Serialize admission checks without waiting for admitted operations to finish. */
31
+ workspaceRequestTail?: Promise<void>;
32
+ /** Preserve outgoing frame order while each frame resolves current authority. */
33
+ workspaceReleaseTail?: Promise<void>;
34
+ /** Fence pending checks and frames after revocation or socket closure. */
35
+ workspaceClosed?: boolean;
36
+ }
37
+ /** Wraps a socket as an emitter that rechecks workspace authority before each frame. */
38
+ export declare function workspaceEmitter(ws: Pick<JsonRpcSocket<JsonRpcSocketData>, 'data' | 'send' | 'close'>): {
39
+ send(message: string): void;
40
+ };
41
+ /** Routes one incoming WebSocket frame to the session attached to the socket. */
42
+ export declare function handleJsonRpcWebSocketMessage(ws: Pick<JsonRpcSocket<JsonRpcSocketData>, 'data' | 'close'>, rawMessage: string | Uint8Array): void;
43
+ /** Opens a JSON-RPC session on a socket and registers it among the active sessions. */
44
+ export declare function openGenericJsonRpcWebSocketSession(options: {
45
+ ws: Pick<JsonRpcSocket<JsonRpcSocketData>, 'data' | 'send' | 'close'>;
46
+ registry: OperationRegistry;
47
+ host: unknown;
48
+ activeSessions: Set<JsonRpcWebSocketSession>;
49
+ discoverDocument?: () => Record<string, unknown>;
50
+ }): void;
51
+ /** Closes a session and releases its subscriptions. */
52
+ export declare function closeJsonRpcWebSocketSession(options: {
53
+ session: JsonRpcWebSocketSession | undefined;
54
+ activeSessions: Set<JsonRpcWebSocketSession>;
55
+ }): void;
@@ -0,0 +1,111 @@
1
+ /**
2
+ * The socket-side runtime of a JSON-RPC WebSocket session that names no server: what a socket must
3
+ * offer (`data`, `send`, `close`), the per-socket state the session keeps, and the functions that
4
+ * open a session on a socket, feed it frames, and close it. Runtime-free, so any host that can
5
+ * hand over a socket of this shape can serve a catalog.
6
+ *
7
+ * @module server/json-rpc-session-runtime
8
+ */
9
+ import { createJsonRpcWebSocketSession, } from "./json-rpc-websocket.js";
10
+ import { anonymousPrincipal } from "./principal.js";
11
+ async function workspaceAllowed(ws) {
12
+ if (ws.data.workspaceClosed)
13
+ return false;
14
+ let allowed = false;
15
+ try {
16
+ allowed = (await ws.data.revalidateWorkspace?.()) ?? true;
17
+ }
18
+ catch {
19
+ /* Fail closed. */
20
+ }
21
+ if (ws.data.workspaceClosed)
22
+ return false;
23
+ if (!allowed) {
24
+ ws.data.workspaceClosed = true;
25
+ ws.close(1008, 'Workspace membership required');
26
+ await ws.data.jsonRpcSession?.close();
27
+ }
28
+ return allowed;
29
+ }
30
+ /** Wraps a socket as an emitter that rechecks workspace authority before each frame. */
31
+ export function workspaceEmitter(ws) {
32
+ return {
33
+ send(message) {
34
+ if (ws.data.revalidateWorkspace === undefined) {
35
+ ws.send(message);
36
+ return;
37
+ }
38
+ ws.data.workspaceReleaseTail = (ws.data.workspaceReleaseTail ?? Promise.resolve())
39
+ .then(async () => {
40
+ if (await workspaceAllowed(ws))
41
+ ws.send(message);
42
+ return undefined;
43
+ })
44
+ .catch(() => {
45
+ ws.data.workspaceClosed = true;
46
+ ws.close(1011, 'Workspace stream closed');
47
+ });
48
+ },
49
+ };
50
+ }
51
+ async function admitWorkspaceMessage(ws, session, text) {
52
+ if (!(await workspaceAllowed(ws)))
53
+ return;
54
+ void session.handleMessage(text).catch(() => {
55
+ ws.data.workspaceClosed = true;
56
+ ws.close(1011, 'Workspace request failed');
57
+ });
58
+ }
59
+ /** Routes one incoming WebSocket frame to the session attached to the socket. */
60
+ export function handleJsonRpcWebSocketMessage(ws, rawMessage) {
61
+ const session = ws.data.jsonRpcSession;
62
+ if (!session) {
63
+ console.error('[weft] /jsonrpc WS frame received with no session attached — closing');
64
+ ws.close(1011, 'no jsonrpc session attached');
65
+ return;
66
+ }
67
+ const text = typeof rawMessage === 'string' ? rawMessage : new TextDecoder().decode(rawMessage);
68
+ if (ws.data.revalidateWorkspace !== undefined) {
69
+ ws.data.workspaceRequestTail = (ws.data.workspaceRequestTail ?? Promise.resolve())
70
+ .then(() => admitWorkspaceMessage(ws, session, text))
71
+ .catch(() => {
72
+ ws.data.workspaceClosed = true;
73
+ ws.close(1011, 'Workspace request failed');
74
+ });
75
+ return;
76
+ }
77
+ session.handleMessage(text).catch((error) => {
78
+ console.error('[weft] /jsonrpc WS message error', error);
79
+ });
80
+ }
81
+ /** Opens a JSON-RPC session on a socket and registers it among the active sessions. */
82
+ export function openGenericJsonRpcWebSocketSession(options) {
83
+ try {
84
+ const session = createJsonRpcWebSocketSession({
85
+ registry: options.registry,
86
+ engine: options.host,
87
+ principal: options.ws.data.principal ?? anonymousPrincipal(),
88
+ emitter: workspaceEmitter(options.ws),
89
+ transport: 'jsonRpcWebSocket',
90
+ ...(options.discoverDocument === undefined
91
+ ? {}
92
+ : { discoverDocument: options.discoverDocument }),
93
+ });
94
+ options.ws.data.jsonRpcSession = session;
95
+ options.activeSessions.add(session);
96
+ }
97
+ catch (error) {
98
+ console.error('[weft] generic JSON-RPC WS session construction failed', error);
99
+ options.ws.close(1011, 'session construction failed');
100
+ }
101
+ }
102
+ /** Closes a session and releases its subscriptions. */
103
+ export function closeJsonRpcWebSocketSession(options) {
104
+ const { session, activeSessions } = options;
105
+ if (!session)
106
+ return;
107
+ activeSessions.delete(session);
108
+ void session.close().catch((error) => {
109
+ console.error('[weft] /jsonrpc WS session close error', error);
110
+ });
111
+ }
@@ -0,0 +1,9 @@
1
+ export declare function pumpSubscriptionIterable(options: {
2
+ subscriptionId: string;
3
+ iterable: AsyncIterable<unknown>;
4
+ signal: AbortSignal;
5
+ closeSubscription: () => Promise<void>;
6
+ shouldSuppressOutput: () => boolean;
7
+ emit: (message: Record<string, unknown>) => void;
8
+ onComplete: () => void;
9
+ }): Promise<void>;
@@ -0,0 +1,46 @@
1
+ import { JSON_RPC_VERSION } from "./json-rpc-protocol.js";
2
+ import { createSubscriptionErrorTerminatedFrame, SESSION_METHODS, } from "./json-rpc-websocket-subscriptions.js";
3
+ export async function pumpSubscriptionIterable(options) {
4
+ const { subscriptionId, iterable, signal, closeSubscription, shouldSuppressOutput, emit, onComplete, } = options;
5
+ let closeStarted = false;
6
+ async function closeOnce() {
7
+ if (closeStarted)
8
+ return;
9
+ closeStarted = true;
10
+ await closeSubscription();
11
+ }
12
+ const abortSubscription = () => {
13
+ void closeOnce().catch(() => { });
14
+ };
15
+ signal.addEventListener('abort', abortSubscription, { once: true });
16
+ try {
17
+ for await (const envelope of iterable) {
18
+ if (signal.aborted) {
19
+ await closeOnce().catch(() => { });
20
+ break;
21
+ }
22
+ emit({
23
+ jsonrpc: JSON_RPC_VERSION,
24
+ method: SESSION_METHODS.DELIVER,
25
+ params: { subscriptionId, envelope },
26
+ });
27
+ }
28
+ if (!signal.aborted && !shouldSuppressOutput()) {
29
+ emit({
30
+ jsonrpc: JSON_RPC_VERSION,
31
+ method: SESSION_METHODS.TERMINATED,
32
+ params: { subscriptionId, reason: 'server-closed' },
33
+ });
34
+ }
35
+ }
36
+ catch (error) {
37
+ if (!signal.aborted && !shouldSuppressOutput()) {
38
+ emit(createSubscriptionErrorTerminatedFrame(subscriptionId, error));
39
+ }
40
+ }
41
+ finally {
42
+ signal.removeEventListener('abort', abortSubscription);
43
+ await closeOnce().catch(() => { });
44
+ onComplete();
45
+ }
46
+ }
@@ -0,0 +1,10 @@
1
+ export declare const SESSION_METHODS: {
2
+ readonly SUBSCRIBE: "weft.workflows.subscribe";
3
+ readonly FLEET_SUBSCRIBE: "weft.events.subscribe";
4
+ readonly UNSUBSCRIBE: "weft.workflows.unsubscribe";
5
+ readonly DELIVER: "weft.events.deliver";
6
+ readonly TERMINATED: "weft.events.terminated";
7
+ };
8
+ export declare const WORKFLOW_EVENTS_OPERATION_NAME = "weft.workflows.events";
9
+ export declare const FLEET_EVENTS_OPERATION_NAME = "weft.events.subscribe";
10
+ export declare function createSubscriptionErrorTerminatedFrame(subscriptionId: string, error: unknown): Record<string, unknown>;
@@ -0,0 +1,33 @@
1
+ import { JSON_RPC_VERSION } from "./json-rpc-protocol.js";
2
+ import { SubscriptionElementValidationError } from "./operation-catalog.js";
3
+ import { isOperationFault } from "./operation-fault-helpers.js";
4
+ export const SESSION_METHODS = {
5
+ SUBSCRIBE: 'weft.workflows.subscribe',
6
+ FLEET_SUBSCRIBE: 'weft.events.subscribe',
7
+ UNSUBSCRIBE: 'weft.workflows.unsubscribe',
8
+ DELIVER: 'weft.events.deliver',
9
+ TERMINATED: 'weft.events.terminated',
10
+ };
11
+ export const WORKFLOW_EVENTS_OPERATION_NAME = 'weft.workflows.events';
12
+ export const FLEET_EVENTS_OPERATION_NAME = 'weft.events.subscribe';
13
+ const ENGINE_FAILURE_FAULT = {
14
+ code: 'EngineFailure',
15
+ message: 'internal error',
16
+ data: {},
17
+ };
18
+ export function createSubscriptionErrorTerminatedFrame(subscriptionId, error) {
19
+ if (error instanceof SubscriptionElementValidationError) {
20
+ return createSubscriptionTerminatedFrame(subscriptionId, 'validation-failed', error.fault);
21
+ }
22
+ if (isOperationFault(error)) {
23
+ return createSubscriptionTerminatedFrame(subscriptionId, 'server-closed', error);
24
+ }
25
+ return createSubscriptionTerminatedFrame(subscriptionId, 'server-closed', ENGINE_FAILURE_FAULT);
26
+ }
27
+ function createSubscriptionTerminatedFrame(subscriptionId, reason, fault) {
28
+ return {
29
+ jsonrpc: JSON_RPC_VERSION,
30
+ method: SESSION_METHODS.TERMINATED,
31
+ params: { subscriptionId, reason, fault },
32
+ };
33
+ }
@@ -0,0 +1,34 @@
1
+ import type { ConnectionLease } from "./connection-lease.js";
2
+ import type { OperationRegistry } from "./operation-catalog.js";
3
+ import type { Principal } from "./principal.js";
4
+ /** Where a JSON-RPC WebSocket session sends its outgoing frames. */
5
+ export type JsonRpcWebSocketEmitter = {
6
+ /** Sends one frame to the peer. */
7
+ send(message: string): void;
8
+ };
9
+ export type JsonRpcWebSocketSessionOptions = {
10
+ readonly registry: OperationRegistry;
11
+ readonly engine: unknown;
12
+ readonly principal: Principal;
13
+ readonly emitter: JsonRpcWebSocketEmitter;
14
+ /**
15
+ * The host's workflow event feed, handed to `weft.workflows.subscribe` as `host.feed`. The
16
+ * session only checks that it is present; the operation that reads it knows its type.
17
+ */
18
+ readonly feed?: unknown;
19
+ /** The host's fleet event feed, handed to `weft.events.subscribe` as `host.fleetFeed`. */
20
+ readonly fleetFeed?: unknown;
21
+ readonly acquireWorkflowSubscription?: () => ConnectionLease;
22
+ readonly acquireFleetSubscription?: () => ConnectionLease;
23
+ readonly maxSubscriptions?: number;
24
+ readonly maxFrameBytes?: number;
25
+ readonly transport?: 'jsonRpcHttp' | 'jsonRpcWebSocket' | 'jsonRpcStdio';
26
+ readonly discoverDocument?: () => Record<string, unknown>;
27
+ };
28
+ /** One JSON-RPC session over a WebSocket: feed it incoming frames, and close it when the socket closes. */
29
+ export type JsonRpcWebSocketSession = {
30
+ /** Handles one incoming frame. */
31
+ handleMessage(frame: string): Promise<void>;
32
+ /** Closes the session and releases its subscriptions. */
33
+ close(): Promise<void>;
34
+ };
@@ -0,0 +1 @@
1
+ export {};
@@ -0,0 +1,45 @@
1
+ import type { EventSelector } from "./event-selector.js";
2
+ import { type JsonRpcId } from "./json-rpc-protocol.js";
3
+ import type { Cursor } from "./sequence-cursor.js";
4
+ type JsonRpcErrorPayload = {
5
+ readonly code: number;
6
+ readonly message: string;
7
+ readonly data?: Record<string, unknown>;
8
+ };
9
+ export type SubscribeParamsValidation = {
10
+ readonly ok: true;
11
+ readonly workflowId: string;
12
+ readonly selector: EventSelector;
13
+ readonly fromCursor: Cursor | undefined;
14
+ } | {
15
+ readonly ok: false;
16
+ readonly error: JsonRpcErrorPayload;
17
+ };
18
+ export type MessageFrameValidation = {
19
+ readonly ok: false;
20
+ readonly error: JsonRpcErrorPayload;
21
+ readonly id: null;
22
+ } | {
23
+ readonly ok: true;
24
+ readonly parsed: Record<string, unknown>;
25
+ readonly method: unknown;
26
+ readonly id: JsonRpcId | undefined;
27
+ readonly params: Record<string, unknown> | undefined;
28
+ readonly hasRequestId: boolean;
29
+ readonly rawId: unknown;
30
+ };
31
+ export declare function validateSubscribeParams(params: Record<string, unknown> | undefined): SubscribeParamsValidation;
32
+ /**
33
+ * The number of bytes `text` takes encoded as UTF-8, counting a lone surrogate as the three bytes
34
+ * of U+FFFD, as `Buffer.byteLength` does. Allocates nothing, so a frame over the limit is measured
35
+ * without a copy.
36
+ */
37
+ export declare function utf8ByteLength(text: string): number;
38
+ export declare function validateMessageFrame(frame: string, maxFrameBytes: number): MessageFrameValidation;
39
+ export declare function validateSessionPrimitiveFrame(frame: Extract<MessageFrameValidation, {
40
+ ok: true;
41
+ }>): {
42
+ readonly error: JsonRpcErrorPayload;
43
+ readonly id: JsonRpcId | null;
44
+ } | null;
45
+ export {};
@@ -0,0 +1,154 @@
1
+ import { faultErrorData } from "./fault-to-json-rpc.js";
2
+ import { JSON_RPC_ERROR_CODES, JSON_RPC_VERSION, isValidJsonRpcId, } from "./json-rpc-protocol.js";
3
+ import { isPlainObject } from "./json-schema-utilities.js";
4
+ export function validateSubscribeParams(params) {
5
+ const workflowId = params?.['workflowId'];
6
+ if (typeof workflowId !== 'string' || workflowId.length === 0) {
7
+ return invalidParams('params.workflowId must be a non-empty string');
8
+ }
9
+ const selector = validateSubscribeSelector(params?.['selector']);
10
+ if (!selector.ok)
11
+ return selector;
12
+ const fromCursor = params?.['fromCursor'];
13
+ if (fromCursor !== undefined && typeof fromCursor !== 'string') {
14
+ return invalidParams('params.fromCursor must be a string when present');
15
+ }
16
+ return { ok: true, workflowId, selector: selector.selector, fromCursor };
17
+ }
18
+ function validateSubscribeSelector(rawSelector) {
19
+ if (rawSelector === undefined)
20
+ return { ok: true, selector: 'events' };
21
+ if (rawSelector === 'events' || rawSelector === 'tokens') {
22
+ return { ok: true, selector: rawSelector };
23
+ }
24
+ return invalidParams("params.selector must be 'events' or 'tokens'");
25
+ }
26
+ /**
27
+ * The number of bytes `text` takes encoded as UTF-8, counting a lone surrogate as the three bytes
28
+ * of U+FFFD, as `Buffer.byteLength` does. Allocates nothing, so a frame over the limit is measured
29
+ * without a copy.
30
+ */
31
+ export function utf8ByteLength(text) {
32
+ let bytes = 0;
33
+ for (let index = 0; index < text.length; index += 1) {
34
+ const unit = text.charCodeAt(index);
35
+ if (unit < 0x80) {
36
+ bytes += 1;
37
+ }
38
+ else if (unit < 0x800) {
39
+ bytes += 2;
40
+ }
41
+ else if (unit >= 0xd800 && unit <= 0xdbff && index + 1 < text.length) {
42
+ const next = text.charCodeAt(index + 1);
43
+ if (next >= 0xdc00 && next <= 0xdfff) {
44
+ bytes += 4;
45
+ index += 1;
46
+ }
47
+ else {
48
+ bytes += 3;
49
+ }
50
+ }
51
+ else {
52
+ bytes += 3;
53
+ }
54
+ }
55
+ return bytes;
56
+ }
57
+ export function validateMessageFrame(frame, maxFrameBytes) {
58
+ const frameByteLength = utf8ByteLength(frame);
59
+ if (frameByteLength > maxFrameBytes) {
60
+ return {
61
+ ok: false,
62
+ error: {
63
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
64
+ message: `frame size exceeds limit of ${maxFrameBytes} bytes`,
65
+ },
66
+ id: null,
67
+ };
68
+ }
69
+ let parsed;
70
+ try {
71
+ parsed = JSON.parse(frame);
72
+ }
73
+ catch {
74
+ return {
75
+ ok: false,
76
+ error: { code: JSON_RPC_ERROR_CODES.PARSE_ERROR, message: 'Parse error' },
77
+ id: null,
78
+ };
79
+ }
80
+ if (Array.isArray(parsed)) {
81
+ return {
82
+ ok: false,
83
+ error: {
84
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
85
+ message: 'batch frames are not supported over WebSocket',
86
+ },
87
+ id: null,
88
+ };
89
+ }
90
+ if (!isPlainObject(parsed)) {
91
+ return {
92
+ ok: false,
93
+ error: {
94
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
95
+ message: 'request must be a JSON object',
96
+ },
97
+ id: null,
98
+ };
99
+ }
100
+ const rawId = parsed['id'];
101
+ const hasRequestId = Object.hasOwn(parsed, 'id');
102
+ return {
103
+ ok: true,
104
+ parsed,
105
+ method: parsed['method'],
106
+ id: isValidJsonRpcId(rawId) ? rawId : undefined,
107
+ params: isPlainObject(parsed['params']) ? parsed['params'] : undefined,
108
+ hasRequestId,
109
+ rawId,
110
+ };
111
+ }
112
+ export function validateSessionPrimitiveFrame(frame) {
113
+ if (frame.parsed['jsonrpc'] !== JSON_RPC_VERSION) {
114
+ return {
115
+ error: {
116
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
117
+ message: `jsonrpc field must be exactly "${JSON_RPC_VERSION}"`,
118
+ },
119
+ id: frame.id ?? null,
120
+ };
121
+ }
122
+ if (frame.hasRequestId && !isValidJsonRpcId(frame.rawId)) {
123
+ return {
124
+ error: {
125
+ code: JSON_RPC_ERROR_CODES.INVALID_REQUEST,
126
+ message: 'id must be a string, number, null, or absent',
127
+ },
128
+ id: null,
129
+ };
130
+ }
131
+ if (Object.hasOwn(frame.parsed, 'params') &&
132
+ frame.parsed['params'] !== undefined &&
133
+ !isPlainObject(frame.parsed['params'])) {
134
+ return {
135
+ error: {
136
+ code: JSON_RPC_ERROR_CODES.INVALID_PARAMS,
137
+ message: 'params must be an object when present',
138
+ data: faultErrorData('InvalidParams'),
139
+ },
140
+ id: frame.id ?? null,
141
+ };
142
+ }
143
+ return null;
144
+ }
145
+ function invalidParams(message) {
146
+ return {
147
+ ok: false,
148
+ error: {
149
+ code: JSON_RPC_ERROR_CODES.INVALID_PARAMS,
150
+ message,
151
+ data: faultErrorData('InvalidParams'),
152
+ },
153
+ };
154
+ }
@@ -0,0 +1,20 @@
1
+ /**
2
+ * WebSocket JSON-RPC session adapter.
3
+ *
4
+ * Each `/jsonrpc` WebSocket connection gets one `JsonRpcWebSocketSession`
5
+ * that binds the authenticated principal at upgrade time and reuses it
6
+ * for every frame. The session:
7
+ * - Parses incoming frames as single JSON-RPC requests (batches over
8
+ * WS are rejected per stable operation-catalog contract).
9
+ * - Dispatches `weft.workflows.subscribe` / `weft.workflows.unsubscribe`
10
+ * as first-class session primitives against the `WorkflowEventFeed`.
11
+ * - Delegates all other methods to the standard `dispatchJsonRpc`.
12
+ * - Emits live envelopes as `weft.events.deliver` notifications keyed
13
+ * by the assigned `subscriptionId`.
14
+ * - Guarantees every active subscription is torn down on `close()`
15
+ * (or socket disconnect at the transport layer).
16
+ */
17
+ import type { JsonRpcWebSocketSession, JsonRpcWebSocketSessionOptions } from "./json-rpc-websocket-types.js";
18
+ export type { JsonRpcWebSocketEmitter, JsonRpcWebSocketSession, JsonRpcWebSocketSessionOptions, } from "./json-rpc-websocket-types.js";
19
+ /** Builds a JSON-RPC session over an emitter and an operation registry. */
20
+ export declare function createJsonRpcWebSocketSession(options: JsonRpcWebSocketSessionOptions): JsonRpcWebSocketSession;