@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,134 @@
1
+ /**
2
+ * Transport-neutral authorization policy types and the pipeline access check.
3
+ *
4
+ * Hosts the `AccessPolicy` / `ScopeRequirement` discriminated unions and
5
+ * `evaluateAccess`, the function `executeOperation` calls between the
6
+ * authentication step and the operation invocation. The scope vocabulary
7
+ * and JWT claim extraction live in `authorization-scope.ts` — separated to
8
+ * keep `principal.ts` and this file cycle-free. This stable authorization
9
+ * policy model ensures consistent access control across REST and JSON-RPC
10
+ * transports.
11
+ */
12
+ import {} from "./authorization-scope.js";
13
+ import { isAuthenticated } from "./principal.js";
14
+ /**
15
+ * Evaluate an `AccessPolicy` against the caller's principal. This is the
16
+ * pipeline step that translates the declarative policy into a pass/fail
17
+ * decision. Credential *validation* happens at the transport edge, BEFORE
18
+ * this function runs; by the time we're here, the principal shape tells us
19
+ * whether the caller is authenticated.
20
+ */
21
+ export function evaluateAccess(policy, principal) {
22
+ switch (policy.kind) {
23
+ case 'public':
24
+ return { allowed: true };
25
+ case 'authenticated':
26
+ if (isAuthenticated(principal))
27
+ return { allowed: true };
28
+ return {
29
+ allowed: false,
30
+ classification: 'unauthorized',
31
+ reason: 'authentication required',
32
+ };
33
+ case 'scoped':
34
+ if (!isAuthenticated(principal)) {
35
+ return {
36
+ allowed: false,
37
+ classification: 'unauthorized',
38
+ reason: 'authentication required',
39
+ };
40
+ }
41
+ return checkScopeRequirement(policy.scopes, principal.scopes);
42
+ case 'scopedAlternatives':
43
+ if (!isAuthenticated(principal)) {
44
+ return {
45
+ allowed: false,
46
+ classification: 'unauthorized',
47
+ reason: 'authentication required',
48
+ };
49
+ }
50
+ return checkScopeAlternatives(policy.alternatives, principal.scopes);
51
+ case 'optionalAuth':
52
+ if (!isAuthenticated(principal))
53
+ return { allowed: true };
54
+ return checkScopeRequirement(policy.authenticatedScopes, principal.scopes);
55
+ default:
56
+ // Defensive default — TypeScript proves this is unreachable for
57
+ // well-formed `AccessPolicy` values (the `_exhaustive: never`
58
+ // assignment fails to compile if a new variant is added without a
59
+ // matching case here). At runtime, a malformed `policy` (from JSON,
60
+ // an `any` cast, or a future variant added without updating this
61
+ // function) would otherwise return `undefined` and silently grant
62
+ // access. Throw deterministically so callers see the bug instead.
63
+ return assertExhaustive(policy);
64
+ }
65
+ }
66
+ function assertExhaustive(value) {
67
+ throw new Error(`authorization received a discriminated value with unknown kind: ${String(value.kind)}`);
68
+ }
69
+ function checkScopeRequirement(requirement, held) {
70
+ // `Array.isArray` reads the object's internal `[[IsArray]]` slot, so it
71
+ // cannot be spoofed by prototype tricks. After this guard, `.some` and
72
+ // `.filter` are guaranteed to be the real built-in methods, not
73
+ // attacker-overridden lookalikes on a poisoned object.
74
+ if (!Array.isArray(requirement.scopes)) {
75
+ throw new Error(`authorization: ${requirement.kind} ScopeRequirement.scopes is not an array at runtime`);
76
+ }
77
+ switch (requirement.kind) {
78
+ case 'anyOf': {
79
+ const hasAny = requirement.scopes.some((scope) => held.has(scope));
80
+ if (hasAny)
81
+ return { allowed: true };
82
+ return {
83
+ allowed: false,
84
+ classification: 'forbidden',
85
+ reason: `requires any of: ${requirement.scopes.join(', ')}`,
86
+ };
87
+ }
88
+ case 'allOf': {
89
+ // The non-empty tuple constraint on `ScopeRequirement.scopes` is a
90
+ // compile-time guarantee. A malformed runtime value with an empty
91
+ // array would otherwise satisfy `missing.length === 0` and silently
92
+ // return `allowed: true`, downgrading a scoped policy to "any
93
+ // authenticated principal allowed."
94
+ if (requirement.scopes.length === 0) {
95
+ throw new Error('authorization: allOf ScopeRequirement has an empty scopes array (the non-empty tuple invariant was violated at runtime)');
96
+ }
97
+ const missing = requirement.scopes.filter((scope) => !held.has(scope));
98
+ if (missing.length === 0)
99
+ return { allowed: true };
100
+ return {
101
+ allowed: false,
102
+ classification: 'forbidden',
103
+ reason: `missing required scopes: ${missing.join(', ')}`,
104
+ };
105
+ }
106
+ default:
107
+ // Same defensive pattern as `evaluateAccess`. Without this, a
108
+ // malformed `requirement.kind` with `scopes: []` would fall into the
109
+ // implicit allOf branch, satisfy `missing.length === 0`, and silently
110
+ // return `{ allowed: true }` — turning a malformed runtime policy
111
+ // into an unintended grant. Throw deterministically instead.
112
+ return assertExhaustive(requirement);
113
+ }
114
+ }
115
+ function checkScopeAlternatives(alternatives, held) {
116
+ if (!Array.isArray(alternatives)) {
117
+ throw new Error('authorization: scopedAlternatives.alternatives is not an array at runtime');
118
+ }
119
+ if (alternatives.length === 0) {
120
+ throw new Error('authorization: scopedAlternatives has an empty alternatives array (the non-empty tuple invariant was violated at runtime)');
121
+ }
122
+ const deniedReasons = [];
123
+ for (const alternative of alternatives) {
124
+ const result = checkScopeRequirement(alternative, held);
125
+ if (result.allowed)
126
+ return { allowed: true };
127
+ deniedReasons.push(result.reason);
128
+ }
129
+ return {
130
+ allowed: false,
131
+ classification: 'forbidden',
132
+ reason: `requires one of: ${deniedReasons.join('; ')}`,
133
+ };
134
+ }
@@ -0,0 +1,45 @@
1
+ /**
2
+ * Binding a replay-plus-live feed's subscriptions to the feed's own lifetime.
3
+ *
4
+ * Its own module rather than a few lines in `workflow-event-feed.ts`, which
5
+ * is already at the file-length limit — and the separation reads correctly:
6
+ * this composes the primitive from outside rather than being part of it.
7
+ *
8
+ * @module server/bind-feed-lifetime
9
+ */
10
+ import type { ReplayLiveFeed } from "./replay-live-feed-types.js";
11
+ import type { SequencedEventEnvelope } from "./sequence-cursor.js";
12
+ /**
13
+ * Binds every subscription a feed hands out to a lifetime signal.
14
+ *
15
+ * A subscriber returned by {@link createReplayLiveFeed} ends on its own
16
+ * `signal` and on nothing else: `drainLive` loops until that signal aborts,
17
+ * and a backend's `dispose()` clears its listener set without waking anybody,
18
+ * so the generator parks on a waker that can never fire again. A host that
19
+ * reaps a feed — a finished agent run, a disposed bureau — therefore has to
20
+ * tell its subscribers, not merely stop feeding them.
21
+ *
22
+ * Composing that here rather than at each subscription site is deliberate:
23
+ * the hazard belongs to the feed, so making correctness depend on every
24
+ * caller remembering to compose would leave a direct `feed.subscribe()` (what
25
+ * tests and in-process hosts use) parked forever.
26
+ *
27
+ * WHAT THIS DOES NOT PROMISE: a final envelope. Aborting the lifetime ends a
28
+ * subscriber promptly, and `drainLive` returns on an aborted signal before
29
+ * flushing whatever is still buffered — so an envelope published in the same
30
+ * synchronous stretch as the abort may never be delivered. That is the right
31
+ * trade for the signal's other job (a client cancelling should stop, not
32
+ * drain), and a producer wanting a last word would have to let the loop turn
33
+ * first, which would deliver it to a prompt reader and not a slow one. The
34
+ * subscription ending is the signal; a client that needs a reason asks.
35
+ *
36
+ * @example
37
+ * ```ts
38
+ * import { bindFeedLifetime, createReplayLiveFeed } from '@lostgradient/backchannel';
39
+ * declare const backend: Parameters<typeof createReplayLiveFeed>[0];
40
+ * const lifetime = new AbortController();
41
+ * const feed = bindFeedLifetime(createReplayLiveFeed(backend), lifetime.signal);
42
+ * // `lifetime.abort()` now ends every live subscriber.
43
+ * ```
44
+ */
45
+ export declare function bindFeedLifetime<TEnvelope extends SequencedEventEnvelope>(feed: ReplayLiveFeed<TEnvelope>, lifetime: AbortSignal): ReplayLiveFeed<TEnvelope>;
@@ -0,0 +1,55 @@
1
+ /**
2
+ * Binding a replay-plus-live feed's subscriptions to the feed's own lifetime.
3
+ *
4
+ * Its own module rather than a few lines in `workflow-event-feed.ts`, which
5
+ * is already at the file-length limit — and the separation reads correctly:
6
+ * this composes the primitive from outside rather than being part of it.
7
+ *
8
+ * @module server/bind-feed-lifetime
9
+ */
10
+ /**
11
+ * Binds every subscription a feed hands out to a lifetime signal.
12
+ *
13
+ * A subscriber returned by {@link createReplayLiveFeed} ends on its own
14
+ * `signal` and on nothing else: `drainLive` loops until that signal aborts,
15
+ * and a backend's `dispose()` clears its listener set without waking anybody,
16
+ * so the generator parks on a waker that can never fire again. A host that
17
+ * reaps a feed — a finished agent run, a disposed bureau — therefore has to
18
+ * tell its subscribers, not merely stop feeding them.
19
+ *
20
+ * Composing that here rather than at each subscription site is deliberate:
21
+ * the hazard belongs to the feed, so making correctness depend on every
22
+ * caller remembering to compose would leave a direct `feed.subscribe()` (what
23
+ * tests and in-process hosts use) parked forever.
24
+ *
25
+ * WHAT THIS DOES NOT PROMISE: a final envelope. Aborting the lifetime ends a
26
+ * subscriber promptly, and `drainLive` returns on an aborted signal before
27
+ * flushing whatever is still buffered — so an envelope published in the same
28
+ * synchronous stretch as the abort may never be delivered. That is the right
29
+ * trade for the signal's other job (a client cancelling should stop, not
30
+ * drain), and a producer wanting a last word would have to let the loop turn
31
+ * first, which would deliver it to a prompt reader and not a slow one. The
32
+ * subscription ending is the signal; a client that needs a reason asks.
33
+ *
34
+ * @example
35
+ * ```ts
36
+ * import { bindFeedLifetime, createReplayLiveFeed } from '@lostgradient/backchannel';
37
+ * declare const backend: Parameters<typeof createReplayLiveFeed>[0];
38
+ * const lifetime = new AbortController();
39
+ * const feed = bindFeedLifetime(createReplayLiveFeed(backend), lifetime.signal);
40
+ * // `lifetime.abort()` now ends every live subscriber.
41
+ * ```
42
+ */
43
+ export function bindFeedLifetime(feed, lifetime) {
44
+ return {
45
+ replay: (options) => feed.replay(options),
46
+ decodeCursor: (cursor) => feed.decodeCursor(cursor),
47
+ subscribe: (options) => feed.subscribe({
48
+ ...options,
49
+ signal: options?.signal === undefined ? lifetime : AbortSignal.any([options.signal, lifetime]),
50
+ }),
51
+ dispose: () => {
52
+ feed.dispose();
53
+ },
54
+ };
55
+ }
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Copy arbitrary `Uint8Array` data into a fresh `ArrayBuffer` for Web APIs that
3
+ * reject `SharedArrayBuffer`-backed views.
4
+ */
5
+ export declare function copyBytesToArrayBuffer(bytes: Uint8Array): ArrayBuffer;
@@ -0,0 +1,9 @@
1
+ /**
2
+ * Copy arbitrary `Uint8Array` data into a fresh `ArrayBuffer` for Web APIs that
3
+ * reject `SharedArrayBuffer`-backed views.
4
+ */
5
+ export function copyBytesToArrayBuffer(bytes) {
6
+ const copy = new Uint8Array(bytes.byteLength);
7
+ copy.set(bytes);
8
+ return copy.buffer;
9
+ }
@@ -0,0 +1,285 @@
1
+ /**
2
+ * The `error` member of a JSON-RPC failure envelope, exactly as the server
3
+ * sent it: the numeric `code`, a human-readable `message`, and whatever
4
+ * optional `data` the operation attached.
5
+ *
6
+ * Codes below `-32000` are JSON-RPC's own reserved range. `-32601` is the one
7
+ * worth recognising, since it means the server has never heard of the
8
+ * operation and is therefore older than the client. {@link CatalogClientError}
9
+ * wraps one of these and exposes that case as `isUnknownOperation`.
10
+ *
11
+ * @example
12
+ * ```ts
13
+ * import { CatalogClientError, type JsonRpcErrorObject } from '@lostgradient/backchannel/client';
14
+ *
15
+ * const wireError: JsonRpcErrorObject = {
16
+ * code: -32601,
17
+ * message: 'Method not found',
18
+ * };
19
+ *
20
+ * const error = new CatalogClientError('probe.echo', wireError);
21
+ * console.log(error.isUnknownOperation); // true
22
+ * ```
23
+ */
24
+ export type JsonRpcErrorObject = {
25
+ /** The JSON-RPC error code. */
26
+ readonly code: number;
27
+ /** A short description of the error. */
28
+ readonly message: string;
29
+ /** What the server attached to the error, when it did. */
30
+ readonly data?: unknown;
31
+ };
32
+ /**
33
+ * The outcome of one JSON-RPC call, as a discriminated union rather than a
34
+ * thrown error: `ok: true` carries the operation's result, `ok: false` carries
35
+ * the server's {@link JsonRpcErrorObject}.
36
+ *
37
+ * Narrow on `ok` before reading either side. Note that `result` is `undefined`
38
+ * for an operation that returns nothing, because a server-side `JSON.stringify`
39
+ * drops an undefined result key altogether; `ok: true` with no result is a
40
+ * success, not a malformed response.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import type { JsonRpcCallResult } from '@lostgradient/backchannel/client';
45
+ *
46
+ * declare const outcome: JsonRpcCallResult;
47
+ *
48
+ * if (outcome.ok) {
49
+ * console.log('result', outcome.result);
50
+ * } else {
51
+ * console.log('failed', outcome.error.code, outcome.error.message);
52
+ * }
53
+ * ```
54
+ */
55
+ export type JsonRpcCallResult = {
56
+ readonly ok: true;
57
+ readonly result: unknown;
58
+ } | {
59
+ readonly ok: false;
60
+ readonly error: JsonRpcErrorObject;
61
+ };
62
+ /**
63
+ * Error thrown by a catalog client when a call fails with a JSON-RPC error, or
64
+ * when a subscription's stream reports one. Carries the wire `code` so callers
65
+ * can tell version skew (the operation is absent on an older server) from a
66
+ * domain fault without reaching past the client to build HTTP requests.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * import { CatalogClientError, type CatalogTransport } from '@lostgradient/backchannel/client';
71
+ *
72
+ * declare const transport: CatalogTransport;
73
+ *
74
+ * try {
75
+ * await transport('probe.echo', { message: 'hello' });
76
+ * } catch (error) {
77
+ * if (error instanceof CatalogClientError && error.isUnknownOperation) {
78
+ * console.log('server predates this operation:', error.operationName);
79
+ * }
80
+ * }
81
+ * ```
82
+ */
83
+ export declare class CatalogClientError extends Error {
84
+ /** The JSON-RPC error code, or the HTTP status of a failed subscription request. */
85
+ readonly code: number;
86
+ /** The `data` the server attached to the error, when it did. */
87
+ readonly data: unknown;
88
+ /** The operation whose call failed. */
89
+ readonly operationName: string;
90
+ constructor(operationName: string, error: JsonRpcErrorObject);
91
+ /** True when the server did not recognize the operation (version skew). */
92
+ get isUnknownOperation(): boolean;
93
+ }
94
+ /**
95
+ * The part of `fetch` a catalog client uses: a request in, a response out. A browser's `fetch`,
96
+ * Bun's and a test double all satisfy it, which `typeof fetch` would not ask of a double in a
97
+ * runtime that adds members to `fetch`.
98
+ *
99
+ * @example
100
+ * ```ts
101
+ * import type { CatalogFetch } from '@lostgradient/backchannel/client';
102
+ *
103
+ * const answer: CatalogFetch = async () => Response.json({ jsonrpc: '2.0', id: 1, result: null });
104
+ * console.log(typeof answer);
105
+ * ```
106
+ */
107
+ export type CatalogFetch = (input: string | URL | Request, init?: RequestInit) => Promise<Response>;
108
+ /**
109
+ * What one call can carry beyond its input: an abort signal that cancels the
110
+ * request, and a `fetch` to use in place of the transport's own.
111
+ *
112
+ * Both are per call, so a component can cancel its own request when it unmounts
113
+ * and a test can answer one call without replacing the global `fetch`.
114
+ *
115
+ * @example
116
+ * ```ts
117
+ * import type { CatalogCallOptions } from '@lostgradient/backchannel/client';
118
+ *
119
+ * const controller = new AbortController();
120
+ * const options: CatalogCallOptions = {
121
+ * signal: controller.signal,
122
+ * fetch: async () => Response.json({ jsonrpc: '2.0', id: 1, result: null }),
123
+ * };
124
+ * console.log(options.signal?.aborted); // false
125
+ * ```
126
+ */
127
+ export type CatalogCallOptions = {
128
+ /** Aborting it cancels the request; the call rejects with the signal's reason. */
129
+ readonly signal?: AbortSignal | undefined;
130
+ /** Used for this call instead of the transport's `fetch` and the global one. */
131
+ readonly fetch?: CatalogFetch | undefined;
132
+ };
133
+ type CatalogOperationTypes = Record<string, {
134
+ readonly input: unknown;
135
+ readonly output: unknown;
136
+ }>;
137
+ type DryRunAnswer<Output, Input> = Input extends {
138
+ readonly dryRun: true;
139
+ } ? Extract<Output, {
140
+ readonly dryRun: true;
141
+ }> : 'dryRun' extends keyof Input ? Input extends {
142
+ readonly dryRun: false;
143
+ } ? Exclude<Output, {
144
+ readonly dryRun: true;
145
+ }> : Output : Exclude<Output, {
146
+ readonly dryRun: true;
147
+ }>;
148
+ /**
149
+ * The shape a catalog client takes: one method per operation name, each
150
+ * accepting that operation's input and an optional {@link CatalogCallOptions},
151
+ * and resolving to its output.
152
+ *
153
+ * {@link createCatalogClient} produces a value of this type. Name the type when
154
+ * you pass a client between functions: anything written against a
155
+ * `CatalogClient` works equally against a remote server, an in-process engine,
156
+ * or a stub, because the transport is already bound.
157
+ *
158
+ * @example
159
+ * ```ts
160
+ * import type { CatalogClient } from '@lostgradient/backchannel/client';
161
+ *
162
+ * type Operations = {
163
+ * 'probe.echo': {
164
+ * readonly input: { message: string };
165
+ * readonly output: { message: string };
166
+ * };
167
+ * };
168
+ *
169
+ * declare const client: CatalogClient<Operations>;
170
+ * const echo = await client['probe.echo']({ message: 'hello' }, { signal: AbortSignal.timeout(5000) });
171
+ * console.log(echo.message);
172
+ * ```
173
+ */
174
+ export type CatalogClient<Operations extends CatalogOperationTypes, DryRunNames extends keyof Operations = never> = [DryRunNames] extends [never] ? {
175
+ readonly [Name in keyof Operations]: (input: Operations[Name]['input'], options?: CatalogCallOptions) => Promise<Operations[Name]['output']>;
176
+ } : {
177
+ readonly [Name in keyof Operations]: Name extends DryRunNames ? <Input extends Operations[Name]['input']>(input: Input, options?: CatalogCallOptions) => Promise<DryRunAnswer<Operations[Name]['output'], Input>> : (input: Operations[Name]['input'], options?: CatalogCallOptions) => Promise<Operations[Name]['output']>;
178
+ };
179
+ /**
180
+ * Transport seam for a catalog client. Every generated operation method
181
+ * resolves to one call into a `CatalogTransport`, which carries the operation
182
+ * name, its input and the per-call {@link CatalogCallOptions}, and returns the
183
+ * operation's result.
184
+ *
185
+ * {@link httpJsonRpcTransport} speaks JSON-RPC over HTTP. Writing your own is
186
+ * the supported way to intercept every call in one place: recording them in a
187
+ * test, adding tracing, or routing to a fake or an in-process host.
188
+ *
189
+ * @example
190
+ * ```ts
191
+ * import { createCatalogClient, type CatalogTransport } from '@lostgradient/backchannel/client';
192
+ *
193
+ * const recording: CatalogTransport = async (operationName, input, options) => {
194
+ * console.log('calling', operationName, input, options?.signal?.aborted);
195
+ * return { message: 'hello' };
196
+ * };
197
+ *
198
+ * const client = createCatalogClient<{
199
+ * 'probe.echo': { readonly input: { message: string }; readonly output: { message: string } };
200
+ * }>(['probe.echo'], recording);
201
+ * console.log(typeof client['probe.echo']);
202
+ * ```
203
+ */
204
+ export type CatalogTransport = (operationName: string, input: unknown, options?: CatalogCallOptions) => Promise<unknown>;
205
+ /**
206
+ * Metadata needed to map a typed client operation onto REST: the HTTP method
207
+ * and path template, where each input field travels (path, query, header,
208
+ * whole body, or one body field), and what a success looks like.
209
+ *
210
+ * A generated client consumes this for you. Read it directly only when you are
211
+ * reproducing the server's routes outside the client: a gateway, a proxy, or
212
+ * documentation generated from the live surface.
213
+ *
214
+ * @example
215
+ * ```ts
216
+ * import type { ClientRestOperationBinding } from '@lostgradient/backchannel/client';
217
+ *
218
+ * const binding: ClientRestOperationBinding = {
219
+ * method: 'GET',
220
+ * path: '/probe/:id',
221
+ * inputSources: { id: { kind: 'path', pathParam: 'id' } },
222
+ * success: { kind: 'json', status: 200 },
223
+ * };
224
+ * console.log(binding.method + ' ' + binding.path);
225
+ * ```
226
+ */
227
+ export type ClientRestOperationBinding = {
228
+ /** The HTTP method. */
229
+ readonly method: string;
230
+ /** The path template, with `:name` parameters. */
231
+ readonly path: string;
232
+ /** Where each input field travels. */
233
+ readonly inputSources: Readonly<Record<string, {
234
+ readonly kind: 'path';
235
+ readonly pathParam: string;
236
+ } | {
237
+ readonly kind: 'query';
238
+ readonly queryParam: string;
239
+ readonly repeating?: boolean;
240
+ } | {
241
+ readonly kind: 'header';
242
+ readonly headerName: string;
243
+ } | {
244
+ readonly kind: 'body';
245
+ readonly mediaType?: 'application/json';
246
+ } | {
247
+ readonly kind: 'body-field';
248
+ readonly bodyField: string;
249
+ }>>;
250
+ /** What a successful response looks like. */
251
+ readonly success: {
252
+ readonly kind: 'json';
253
+ readonly status: number;
254
+ } | {
255
+ readonly kind: 'empty';
256
+ readonly status: number;
257
+ };
258
+ };
259
+ /**
260
+ * Build a catalog client from a list of operation names and a transport. Each
261
+ * name becomes a method that forwards its input and its per-call options
262
+ * through the transport, so the full catalog is reachable without
263
+ * hand-authoring a method per operation.
264
+ *
265
+ * A generated `create...Client` function is the shortcut that pairs the
266
+ * generated catalog with {@link httpJsonRpcTransport}. Call this directly when
267
+ * you supply the transport yourself, or when you want a client over a
268
+ * deliberately narrowed set of operations.
269
+ *
270
+ * @example
271
+ * ```ts
272
+ * import {
273
+ * createCatalogClient,
274
+ * httpJsonRpcTransport,
275
+ * } from '@lostgradient/backchannel/client';
276
+ *
277
+ * const client = createCatalogClient<{
278
+ * 'probe.echo': { readonly input: { message: string }; readonly output: { message: string } };
279
+ * }>(['probe.echo'], httpJsonRpcTransport({ baseUrl: 'http://localhost:7233' }));
280
+ *
281
+ * console.log(typeof client['probe.echo']);
282
+ * ```
283
+ */
284
+ export declare function createCatalogClient<Operations extends CatalogOperationTypes, DryRunNames extends keyof Operations = never>(operationNames: readonly (keyof Operations & string)[], transport: CatalogTransport): CatalogClient<Operations, DryRunNames>;
285
+ export {};
@@ -0,0 +1,74 @@
1
+ /** JSON-RPC reserved code returned when a server does not know an operation. */
2
+ const METHOD_NOT_FOUND_CODE = -32601;
3
+ /**
4
+ * Error thrown by a catalog client when a call fails with a JSON-RPC error, or
5
+ * when a subscription's stream reports one. Carries the wire `code` so callers
6
+ * can tell version skew (the operation is absent on an older server) from a
7
+ * domain fault without reaching past the client to build HTTP requests.
8
+ *
9
+ * @example
10
+ * ```ts
11
+ * import { CatalogClientError, type CatalogTransport } from '@lostgradient/backchannel/client';
12
+ *
13
+ * declare const transport: CatalogTransport;
14
+ *
15
+ * try {
16
+ * await transport('probe.echo', { message: 'hello' });
17
+ * } catch (error) {
18
+ * if (error instanceof CatalogClientError && error.isUnknownOperation) {
19
+ * console.log('server predates this operation:', error.operationName);
20
+ * }
21
+ * }
22
+ * ```
23
+ */
24
+ export class CatalogClientError extends Error {
25
+ /** The JSON-RPC error code, or the HTTP status of a failed subscription request. */
26
+ code;
27
+ /** The `data` the server attached to the error, when it did. */
28
+ data;
29
+ /** The operation whose call failed. */
30
+ operationName;
31
+ constructor(operationName, error) {
32
+ super(error.message);
33
+ this.name = 'CatalogClientError';
34
+ this.code = error.code;
35
+ this.data = error.data;
36
+ this.operationName = operationName;
37
+ }
38
+ /** True when the server did not recognize the operation (version skew). */
39
+ get isUnknownOperation() {
40
+ return this.code === METHOD_NOT_FOUND_CODE;
41
+ }
42
+ }
43
+ /**
44
+ * Build a catalog client from a list of operation names and a transport. Each
45
+ * name becomes a method that forwards its input and its per-call options
46
+ * through the transport, so the full catalog is reachable without
47
+ * hand-authoring a method per operation.
48
+ *
49
+ * A generated `create...Client` function is the shortcut that pairs the
50
+ * generated catalog with {@link httpJsonRpcTransport}. Call this directly when
51
+ * you supply the transport yourself, or when you want a client over a
52
+ * deliberately narrowed set of operations.
53
+ *
54
+ * @example
55
+ * ```ts
56
+ * import {
57
+ * createCatalogClient,
58
+ * httpJsonRpcTransport,
59
+ * } from '@lostgradient/backchannel/client';
60
+ *
61
+ * const client = createCatalogClient<{
62
+ * 'probe.echo': { readonly input: { message: string }; readonly output: { message: string } };
63
+ * }>(['probe.echo'], httpJsonRpcTransport({ baseUrl: 'http://localhost:7233' }));
64
+ *
65
+ * console.log(typeof client['probe.echo']);
66
+ * ```
67
+ */
68
+ export function createCatalogClient(operationNames, transport) {
69
+ const methods = {};
70
+ for (const operationName of operationNames) {
71
+ methods[operationName] = (input, options) => transport(operationName, input, options);
72
+ }
73
+ return methods;
74
+ }
@@ -0,0 +1,19 @@
1
+ import { type OperationRegistry } from "../operation-catalog.js";
2
+ import type { Principal } from "../principal.js";
3
+ import { type CatalogTransport } from "./catalog-client.js";
4
+ import type { SubscriptionTransport } from "./subscription-client.js";
5
+ /** The operation catalog, host and caller used to dispatch an embedded client's calls. */
6
+ export type InProcessTransportOptions = {
7
+ /** The operation catalog used by the client. */
8
+ readonly registry: OperationRegistry;
9
+ /** The host value or per-dispatch factory. */
10
+ readonly host: unknown;
11
+ /** The local caller for each dispatch. */
12
+ readonly principal: Principal;
13
+ /** Select REST dispatch semantics for operations called through REST by the remote client. */
14
+ readonly restOperationNames?: ReadonlySet<string>;
15
+ };
16
+ /** Dispatch unary calls in the current process, using the same fault envelope as JSON-RPC. */
17
+ export declare function inProcessCatalogTransport(options: InProcessTransportOptions): CatalogTransport;
18
+ /** Follow a catalog subscription in-process with the same cursor convention as SSE. */
19
+ export declare function inProcessSubscriptionTransport(options: InProcessTransportOptions): SubscriptionTransport;