@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,310 @@
1
+ import { createHash } from 'node:crypto';
2
+ import { PACKAGE_AUTHORIZATION_SCOPE_PATTERN } from "../index.js";
3
+ import { compareStrings } from "../internals.js";
4
+ const UNSUPPORTED_COMBINATOR = Symbol('unsupported-combinator');
5
+ /**
6
+ * Return the members of an all-string `enum`, or `undefined` when the schema has
7
+ * no `enum` or any member is not a string. A single-quoted string-literal union
8
+ * is emitted for these; mixed or non-string enums fall through to the `unknown`
9
+ * fallback rather than guessing a representation.
10
+ */
11
+ function stringEnumMembers(schema) {
12
+ const values = schema['enum'];
13
+ if (!Array.isArray(values) || values.length === 0)
14
+ return undefined;
15
+ if (!values.every((value) => typeof value === 'string'))
16
+ return undefined;
17
+ return values;
18
+ }
19
+ /**
20
+ * Return the branch schemas of a `anyOf`/`oneOf` union, `undefined` when the
21
+ * schema is not a union, or {@link UNSUPPORTED_COMBINATOR} when it is one the
22
+ * emitter refuses to interpret.
23
+ *
24
+ * TypeScript has no exclusive-or type, so `oneOf` and `anyOf` both render to
25
+ * the same `A | B` union text; Zod's `discriminatedUnion()` compiles to `oneOf`
26
+ * with a `const` discriminant per branch, which the `const` handling above
27
+ * already preserves as a literal (WFT-93). `allOf` stays unsupported.
28
+ *
29
+ * JSON Schema applies sibling combinators conjunctively, so a node carrying
30
+ * more than one is a constraint this emitter does not compose. Degrade to
31
+ * `unknown` rather than silently honoring one and dropping the rest — the same
32
+ * posture `src/json-schema/codegen-emit.ts` takes for the same case.
33
+ */
34
+ function unionBranches(schema) {
35
+ let found;
36
+ for (const keyword of ['anyOf', 'oneOf', 'allOf']) {
37
+ const value = schema[keyword];
38
+ if (!Array.isArray(value))
39
+ continue;
40
+ if (found !== undefined || keyword === 'allOf')
41
+ return UNSUPPORTED_COMBINATOR;
42
+ found = { keyword, branches: value };
43
+ }
44
+ if (found === undefined)
45
+ return undefined;
46
+ // An empty combinator array is a degenerate schema with no branches to union.
47
+ return found.branches.length > 0 ? found.branches : UNSUPPORTED_COMBINATOR;
48
+ }
49
+ function referenceName(context, name) {
50
+ const digest = createHash('sha256').update(name).digest('hex');
51
+ return `CatalogDefinition_${context.prefix}_${digest}`;
52
+ }
53
+ function referencedName(value) {
54
+ if (typeof value !== 'string' || !value.startsWith('#/$defs/'))
55
+ return undefined;
56
+ const segment = value.slice('#/$defs/'.length);
57
+ if (!segment || segment.includes('/') || /~(?![01])/u.test(segment))
58
+ return undefined;
59
+ return segment.replace(/~1/gu, '/').replace(/~0/gu, '~');
60
+ }
61
+ /** Reject cycles made only of aliases or unions, which TypeScript cannot declare. */
62
+ function guardedDefinition(context, name, path) {
63
+ if (path.has(name) || !Object.hasOwn(context.definitions, name))
64
+ return false;
65
+ const definition = context.definitions[name];
66
+ if (!isRecord(definition))
67
+ return false;
68
+ const nextPath = new Set(path).add(name);
69
+ return guardedNode(context, definition, nextPath);
70
+ }
71
+ function guardedNode(context, schema, path) {
72
+ const ref = Object.hasOwn(schema, '$ref') ? referencedName(schema['$ref']) : undefined;
73
+ if (ref !== undefined)
74
+ return guardedDefinition(context, ref, path);
75
+ const branches = unionBranches(schema);
76
+ if (branches === UNSUPPORTED_COMBINATOR)
77
+ return false;
78
+ if (branches !== undefined)
79
+ return branches.every((branch) => !isRecord(branch) || guardedNode(context, branch, path));
80
+ return true;
81
+ }
82
+ /** Parse one schema root and its reachable, root-scoped local definitions. */
83
+ export function parseSchema(schema) {
84
+ const definitions = Object.hasOwn(schema, '$defs') && isRecord(schema['$defs']) ? schema['$defs'] : {};
85
+ const context = {
86
+ root: schema,
87
+ definitions,
88
+ prefix: createHash('sha256').update(JSON.stringify(schema)).digest('hex'),
89
+ used: new Set(),
90
+ };
91
+ const root = parseNode(schema, context);
92
+ const emitted = new Map();
93
+ for (const name of context.used) {
94
+ const definition = definitions[name];
95
+ if (isRecord(definition))
96
+ emitted.set(referenceName(context, name), parseNode(definition, context));
97
+ }
98
+ return { root, definitions: emitted };
99
+ }
100
+ export function schemaToNode(schema) {
101
+ return parseSchema(schema).root;
102
+ }
103
+ function parseNode(schema, context) {
104
+ // A nested $id rebases local references; the root's definitions are no longer their document.
105
+ if (schema !== context.root && Object.hasOwn(schema, '$id'))
106
+ context = { ...context, definitions: {} };
107
+ if (Object.hasOwn(schema, '$ref')) {
108
+ const name = referencedName(schema['$ref']);
109
+ const siblings = Object.keys(schema).filter((key) => !['$ref', '$defs', 'title', 'description', '$comment'].includes(key));
110
+ if (name === undefined || siblings.length || !guardedDefinition(context, name, new Set()))
111
+ return { kind: 'primitive', text: 'unknown' };
112
+ context.used.add(name);
113
+ return { kind: 'reference', name: referenceName(context, name) };
114
+ }
115
+ const constant = schema['const'];
116
+ if (typeof constant === 'string' ||
117
+ typeof constant === 'number' ||
118
+ typeof constant === 'boolean' ||
119
+ constant === null) {
120
+ return { kind: 'primitive', text: JSON.stringify(constant) };
121
+ }
122
+ const branches = unionBranches(schema);
123
+ if (branches === UNSUPPORTED_COMBINATOR)
124
+ return { kind: 'primitive', text: 'unknown' };
125
+ if (branches !== undefined) {
126
+ const members = branches.map((member) => isRecord(member)
127
+ ? parseNode(member, context)
128
+ : { kind: 'primitive', text: 'unknown' });
129
+ if (members.some((member) => member.kind === 'primitive' && member.text === 'unknown')) {
130
+ return { kind: 'primitive', text: 'unknown' };
131
+ }
132
+ return {
133
+ kind: 'union',
134
+ members,
135
+ };
136
+ }
137
+ // A string `enum` is tighter than its `type: 'string'`, so emit the literal
138
+ // union and preserve the operation's discriminant (e.g. startorsignal's
139
+ // `outcome: 'started' | 'signalled'`) instead of widening to `string`. Members
140
+ // stay in schema order for deterministic output. Non-string enums fall through.
141
+ const stringEnum = stringEnumMembers(schema);
142
+ if (stringEnum !== undefined) {
143
+ return {
144
+ kind: 'union',
145
+ // `JSON.stringify` produces a TypeScript-valid double-quoted string literal
146
+ // with proper escaping, so enum values containing quotes, backslashes, or
147
+ // newlines emit a correct literal rather than via raw interpolation.
148
+ members: stringEnum.map((value) => ({ kind: 'primitive', text: JSON.stringify(value) })),
149
+ };
150
+ }
151
+ return typedSchemaNode(schema, context);
152
+ }
153
+ /**
154
+ * The TypeScript type for a package authorization scope. A JSON Schema
155
+ * `pattern` has no general TypeScript form, but this one does, and emitting
156
+ * `string` instead would swallow the built-in scope literals it is unioned
157
+ * with (the `scopes` of the principal operation).
158
+ */
159
+ const PACKAGE_AUTHORIZATION_SCOPE_TYPE = '`${string}.${string}:${string}`';
160
+ function stringSchemaNode(schema) {
161
+ return schema['pattern'] === PACKAGE_AUTHORIZATION_SCOPE_PATTERN.source
162
+ ? { kind: 'primitive', text: PACKAGE_AUTHORIZATION_SCOPE_TYPE }
163
+ : { kind: 'primitive', text: 'string' };
164
+ }
165
+ function typedSchemaNode(schema, context) {
166
+ const type = schema['type'];
167
+ switch (type) {
168
+ case 'string':
169
+ return stringSchemaNode(schema);
170
+ case 'number':
171
+ case 'integer':
172
+ return { kind: 'primitive', text: 'number' };
173
+ case 'boolean':
174
+ return { kind: 'primitive', text: 'boolean' };
175
+ case 'null':
176
+ return { kind: 'primitive', text: 'null' };
177
+ case 'array':
178
+ return arraySchemaNode(schema['items'], context);
179
+ }
180
+ if (Array.isArray(type)) {
181
+ return { kind: 'union', members: type.map(typeUnionMember) };
182
+ }
183
+ if (type === 'object' || isRecord(schema['properties']))
184
+ return objectSchemaNode(schema, context);
185
+ return { kind: 'primitive', text: 'unknown' };
186
+ }
187
+ function typeUnionMember(value) {
188
+ return typeof value === 'string'
189
+ ? schemaToNode({ type: value })
190
+ : { kind: 'primitive', text: 'unknown' };
191
+ }
192
+ function arraySchemaNode(items, context) {
193
+ return {
194
+ kind: 'array',
195
+ element: isRecord(items) ? parseNode(items, context) : { kind: 'primitive', text: 'unknown' },
196
+ };
197
+ }
198
+ function objectSchemaNode(schema, context) {
199
+ const properties = schema['properties'];
200
+ const additionalProperties = schema['additionalProperties'];
201
+ if (isRecord(additionalProperties) &&
202
+ (!isRecord(properties) || Object.keys(properties).length === 0)) {
203
+ return { kind: 'record', value: parseNode(additionalProperties, context) };
204
+ }
205
+ if (!isRecord(properties))
206
+ return { kind: 'record' };
207
+ const required = new Set(Array.isArray(schema['required'])
208
+ ? schema['required'].filter((entry) => typeof entry === 'string')
209
+ : []);
210
+ // Canonical property order keeps alias identity independent of insertion order.
211
+ const fields = Object.entries(properties)
212
+ .map(([name, propertySchema]) => ({
213
+ name,
214
+ optional: !required.has(name),
215
+ value: isRecord(propertySchema)
216
+ ? parseNode(propertySchema, context)
217
+ : { kind: 'primitive', text: 'unknown' },
218
+ }))
219
+ .toSorted((left, right) => compareStrings(left.name, right.name));
220
+ return { kind: 'object', fields };
221
+ }
222
+ function flattenUnion(member) {
223
+ return member.kind === 'union' ? member.members.flatMap(flattenUnion) : [member];
224
+ }
225
+ /**
226
+ * Render a {@link TypeNode} to TypeScript. When a child node's
227
+ * {@link canonicalKey} is present in `aliasNameByKey`, the alias name is
228
+ * substituted in place of inlining the shape. `suppressKey` prevents an alias
229
+ * body from referencing itself (which would emit `type X = X`).
230
+ */
231
+ export function renderNode(node, aliasNameByKey, suppressKey) {
232
+ // Render a child, substituting its alias name unless it is the suppressed self.
233
+ const renderChild = (child) => {
234
+ const key = canonicalKey(child);
235
+ if (key !== suppressKey) {
236
+ const alias = aliasNameByKey.get(key);
237
+ if (alias !== undefined)
238
+ return alias;
239
+ }
240
+ return renderNode(child, aliasNameByKey, suppressKey);
241
+ };
242
+ switch (node.kind) {
243
+ case 'primitive':
244
+ return node.text;
245
+ case 'reference':
246
+ return node.name;
247
+ case 'record':
248
+ if (node.value !== undefined && containsReference(node.value))
249
+ return `{ readonly [key: string]: ${renderChild(node.value)} }`;
250
+ return `Record<string, ${node.value === undefined ? 'unknown' : renderChild(node.value)}>`;
251
+ case 'array':
252
+ return `ReadonlyArray<${renderChild(node.element)}>`;
253
+ case 'union': {
254
+ const members = node.members.flatMap(flattenUnion);
255
+ if (members.some((member) => member.kind === 'primitive' && member.text === 'string')) {
256
+ return members
257
+ .filter((member) => member.kind !== 'primitive' || !member.text.startsWith('"'))
258
+ .map((member) => renderChild(member))
259
+ .join(' | ');
260
+ }
261
+ return node.members.map((member) => renderChild(member)).join(' | ');
262
+ }
263
+ case 'object': {
264
+ const fields = node.fields.map((field) => {
265
+ const optional = field.optional ? '?' : '';
266
+ return `readonly ${JSON.stringify(field.name)}${optional}: ${renderChild(field.value)};`;
267
+ });
268
+ return `{ ${fields.join(' ')} }`;
269
+ }
270
+ default:
271
+ throw new Error(`Unsupported schema node: ${JSON.stringify(node)}`);
272
+ }
273
+ }
274
+ function containsReference(node) {
275
+ switch (node.kind) {
276
+ case 'reference':
277
+ return true;
278
+ case 'array':
279
+ return containsReference(node.element);
280
+ case 'record':
281
+ return node.value !== undefined && containsReference(node.value);
282
+ case 'union':
283
+ return node.members.some(containsReference);
284
+ case 'object':
285
+ return node.fields.some((field) => containsReference(field.value));
286
+ case 'primitive':
287
+ return false;
288
+ default:
289
+ throw new Error(`Unsupported schema node: ${JSON.stringify(node)}`);
290
+ }
291
+ }
292
+ /**
293
+ * Render a top-level node (an operation input/output position). Unlike
294
+ * {@link renderNode}, this substitutes the alias name when the node *itself* is
295
+ * hoisted — so two operations with an identical whole-object input both collapse
296
+ * to the same alias reference.
297
+ */
298
+ export function renderRoot(node, aliasNameByKey) {
299
+ const alias = aliasNameByKey.get(canonicalKey(node));
300
+ if (alias !== undefined)
301
+ return alias;
302
+ return renderNode(node, aliasNameByKey);
303
+ }
304
+ /** Deterministic structural key for a node; equal iff the emitted text is equal. */
305
+ export function canonicalKey(node) {
306
+ return JSON.stringify(node);
307
+ }
308
+ function isRecord(value) {
309
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
310
+ }
@@ -0,0 +1,3 @@
1
+ import type { CatalogOperationSnapshot } from "../operation-catalog-snapshot.js";
2
+ /** Generate bindings only for operations that declare consumer behavior. */
3
+ export declare function svelteClientSource(operations: readonly CatalogOperationSnapshot[], subscriptions: readonly CatalogOperationSnapshot[], outputFile: string, serverName: string, commands?: boolean, providerExports?: boolean): string;
@@ -0,0 +1,61 @@
1
+ import { GENERATED_HEADER } from "./operation-client-domains.js";
2
+ /** Generate bindings only for operations that declare consumer behavior. */
3
+ export function svelteClientSource(operations, subscriptions, outputFile, serverName, commands = true, providerExports = true) {
4
+ const usedNames = new Set();
5
+ const declaredReads = operations
6
+ .filter((operation) => operation.kind === 'unary' && operation.behavior?.kind === 'read')
7
+ .map((operation) => operation.name);
8
+ const bindingName = (operation) => {
9
+ const name = operation.name
10
+ .split(/[^A-Za-z0-9]+/u)
11
+ .filter(Boolean)
12
+ .map((part) => part[0].toUpperCase() + part.slice(1))
13
+ .join('');
14
+ if (!name || usedNames.has(name))
15
+ throw new Error(`Svelte binding name collision for ${operation.name}`);
16
+ usedNames.add(name);
17
+ return name;
18
+ };
19
+ const bindings = operations.flatMap((operation) => {
20
+ const behavior = operation.behavior;
21
+ if (!behavior || (behavior.kind === 'command' && !commands))
22
+ return [];
23
+ const name = bindingName(operation);
24
+ const type = `ClientOperationTypes[${JSON.stringify(operation.name)}]`;
25
+ if (behavior.kind === 'read')
26
+ return [
27
+ `export function use${name}(host: CatalogHost, input: () => ${type}['input']) {
28
+ const read = createReactiveRead<${type}['input'], ${type}['output']>(host, ${JSON.stringify(operation.name)}, input);
29
+ return ${behavior.pagination ? `Object.assign(read, createPagination(host, ${JSON.stringify(operation.name)}, input, ${JSON.stringify(behavior.pagination)}))` : 'read'};
30
+ }`,
31
+ ];
32
+ for (const target of behavior.invalidates ?? []) {
33
+ if (!declaredReads.includes(target))
34
+ throw new Error(`Command ${operation.name} invalidates undeclared read ${target}`);
35
+ }
36
+ return [
37
+ `export function use${name}(host: CatalogHost) {
38
+ return createCommand<${type}['input'], ${type}['output']>(host, ${JSON.stringify(operation.name)}, ${JSON.stringify(behavior.invalidates ?? [])}${behavior.invalidates?.length ? '' : `, ${JSON.stringify(declaredReads)}`});
39
+ }`,
40
+ ];
41
+ });
42
+ const streams = subscriptions
43
+ .filter((operation) => operation.behavior?.kind === 'read' && operation.behavior.cursor)
44
+ .map((operation) => {
45
+ const name = bindingName(operation);
46
+ const type = `SubscriptionOperationTypes[${JSON.stringify(operation.name)}]`;
47
+ return `export function use${name}(host: CatalogHost, input: ${type}['input'], onEvent: (event: ${type}['event']) => void) {
48
+ return createSubscription(host, ${JSON.stringify(operation.name)}, input, onEvent);
49
+ }`;
50
+ });
51
+ const provider = serverName.replace(/[^A-Za-z0-9]/gu, '');
52
+ if (!/^[A-Za-z]/u.test(provider))
53
+ throw new Error('Svelte provider name must start with a letter');
54
+ return `${GENERATED_HEADER}
55
+ import { createReactiveRead, ${commands ? 'createCommand, ' : ''}${operations.some((operation) => operation.behavior?.kind === 'read' && operation.behavior.pagination) ? 'createPagination, ' : ''}${streams.length ? 'createSubscription, ' : ''}type CatalogHost } from '@lostgradient/backchannel-svelte';
56
+ import type { ClientOperationTypes } from './${outputFile}';
57
+ ${streams.length ? "import type { SubscriptionOperationTypes } from './subscription-operations.generated.ts';" : ''}
58
+ ${providerExports ? `export { default as ${provider}Provider } from '@lostgradient/backchannel-svelte/provider';\nexport { getCatalogHost as get${provider}Host } from '@lostgradient/backchannel-svelte';` : ''}
59
+ ${[...bindings, ...streams].join('\n\n')}
60
+ `;
61
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * Sequence cursors: the opaque cursor of a sequenced event feed (a non-negative sequence to the feed,
3
+ * a string to a client), and the parser of a cursor-like query value. Imports nothing, so every feed
4
+ * and transport can share it.
5
+ *
6
+ * @module server/sequence-cursor
7
+ */
8
+ export interface ParsedSequenceCursor {
9
+ error?: string;
10
+ value?: number;
11
+ }
12
+ /** Reads an optional cursor from a request parameter, or reports it as invalid. */
13
+ export declare function parseOptionalSequenceCursor(rawValue: string | null | undefined, parameterName: string): ParsedSequenceCursor;
14
+ /**
15
+ * Opaque cursor into a workflow or fleet event feed. Durable workflow and
16
+ * fleet feeds use numeric cursors; in-memory backends use an incarnation and
17
+ * sequence so a reconnect after restart can report a gap. Pass the cursor
18
+ * back as `fromCursor` to resume a feed, and never parse it in a client.
19
+ *
20
+ * @example
21
+ * ```ts
22
+ * import type { Cursor } from '@lostgradient/backchannel';
23
+ * import type { EventEnvelope } from '@lostgradient/weft';
24
+ *
25
+ * declare const envelope: EventEnvelope;
26
+ * const lastCursor: Cursor = envelope.cursor;
27
+ * void lastCursor;
28
+ * ```
29
+ */
30
+ export type Cursor = string;
31
+ /** Encode a non-negative integer sequence as an opaque cursor. */
32
+ export declare function encodeCursor(sequence: number): Cursor;
33
+ /**
34
+ * Decode an opaque cursor back to its sequence. `-1` is the initial
35
+ * sentinel for "before the first event"; malformed input returns null.
36
+ */
37
+ export declare function decodeCursor(cursor: Cursor): number | null;
38
+ /** Compares two cursors by sequence position. */
39
+ export declare function compareCursor(a: Cursor, b: Cursor): 'before' | 'at' | 'after';
40
+ /** An event envelope a replay-and-live feed can order: its sequence and its cursor. */
41
+ export type SequencedEventEnvelope = {
42
+ /** The envelope's position in the log. */
43
+ readonly sequence: number;
44
+ /** The opaque token a consumer passes back to resume after this envelope. */
45
+ readonly cursor: Cursor;
46
+ };
@@ -0,0 +1,62 @@
1
+ /**
2
+ * Sequence cursors: the opaque cursor of a sequenced event feed (a non-negative sequence to the feed,
3
+ * a string to a client), and the parser of a cursor-like query value. Imports nothing, so every feed
4
+ * and transport can share it.
5
+ *
6
+ * @module server/sequence-cursor
7
+ */
8
+ const DECIMAL_INTEGER_PATTERN = /^-?\d+$/;
9
+ /** Reads an optional cursor from a request parameter, or reports it as invalid. */
10
+ export function parseOptionalSequenceCursor(rawValue, parameterName) {
11
+ if (rawValue === null || rawValue === undefined) {
12
+ return {};
13
+ }
14
+ if (rawValue.trim().length === 0) {
15
+ return {
16
+ error: `Invalid ${parameterName}: ${rawValue}`,
17
+ };
18
+ }
19
+ if (!DECIMAL_INTEGER_PATTERN.test(rawValue)) {
20
+ return {
21
+ error: `Invalid ${parameterName}: ${rawValue}`,
22
+ };
23
+ }
24
+ const value = Number(rawValue);
25
+ if (!Number.isSafeInteger(value) || value < -1) {
26
+ return {
27
+ error: `Invalid ${parameterName}: ${rawValue}`,
28
+ };
29
+ }
30
+ return { value };
31
+ }
32
+ const CURSOR_PATTERN = /^(?:-1|\d+)$/;
33
+ /** Encode a non-negative integer sequence as an opaque cursor. */
34
+ export function encodeCursor(sequence) {
35
+ if (!Number.isInteger(sequence) || sequence < 0) {
36
+ throw new Error(`encodeCursor: sequence must be a non-negative integer, got ${sequence}`);
37
+ }
38
+ return String(sequence);
39
+ }
40
+ /**
41
+ * Decode an opaque cursor back to its sequence. `-1` is the initial
42
+ * sentinel for "before the first event"; malformed input returns null.
43
+ */
44
+ export function decodeCursor(cursor) {
45
+ if (!CURSOR_PATTERN.test(cursor))
46
+ return null;
47
+ const value = Number(cursor);
48
+ if (!Number.isSafeInteger(value) || value < -1)
49
+ return null;
50
+ return value;
51
+ }
52
+ function decodeCursorOrThrow(cursor) {
53
+ const sequence = decodeCursor(cursor);
54
+ if (sequence === null)
55
+ throw new Error('Invalid cursor');
56
+ return sequence;
57
+ }
58
+ /** Compares two cursors by sequence position. */
59
+ export function compareCursor(a, b) {
60
+ const delta = decodeCursorOrThrow(a) - decodeCursorOrThrow(b);
61
+ return delta === 0 ? 'at' : delta < 0 ? 'before' : 'after';
62
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * The JSON Schema of the `data:` line of a Server-Sent Events `event: error` frame, as the AsyncAPI
3
+ * document describes it.
4
+ *
5
+ * @module sse-error-payload-schema
6
+ */
7
+ /**
8
+ * The error frame a stream that fails after it started writes: the fault's `code`, `message` and
9
+ * allowlisted `data`, with `retryable` always and `remediation` when the fault carries one, as the
10
+ * REST, JSON-RPC and MCP projections do.
11
+ */
12
+ export declare function sseErrorPayloadSchema(): Record<string, unknown>;
@@ -0,0 +1,33 @@
1
+ /**
2
+ * The JSON Schema of the `data:` line of a Server-Sent Events `event: error` frame, as the AsyncAPI
3
+ * document describes it.
4
+ *
5
+ * @module sse-error-payload-schema
6
+ */
7
+ import { MAX_REMEDIATION_LENGTH } from "./fault-remediation.js";
8
+ /**
9
+ * The error frame a stream that fails after it started writes: the fault's `code`, `message` and
10
+ * allowlisted `data`, with `retryable` always and `remediation` when the fault carries one, as the
11
+ * REST, JSON-RPC and MCP projections do.
12
+ */
13
+ export function sseErrorPayloadSchema() {
14
+ return {
15
+ properties: {
16
+ code: { type: 'string' },
17
+ data: {},
18
+ message: { type: 'string' },
19
+ remediation: {
20
+ type: 'string',
21
+ minLength: 1,
22
+ maxLength: MAX_REMEDIATION_LENGTH,
23
+ description: 'One line of plain text saying what to do next; omitted when none is known',
24
+ },
25
+ retryable: {
26
+ type: 'boolean',
27
+ description: 'Whether repeating the identical call later can succeed',
28
+ },
29
+ },
30
+ required: ['message', 'retryable'],
31
+ type: 'object',
32
+ };
33
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Runtime JSON-RPC stdio session.
3
+ *
4
+ * `runStdioSession({ input, output, admission, registry, engine, feed, ... })`
5
+ * drives the `weft rpc-stdio` CLI subcommand. It implements the stable
6
+ * JSON-RPC stdio transport: reading newline-delimited JSON frames from
7
+ * `input`, running each through the JSON-RPC dispatcher, and writing
8
+ * responses to `output`.
9
+ *
10
+ * Admission is mandatory:
11
+ * - `{ kind: 'startup-token', token }` — the first frame must be a
12
+ * `weft.authenticate` call whose `params.token` matches. On match,
13
+ * the session principal is `stdio-local` with admin scopes. On
14
+ * mismatch, the session returns `exit 2` without starting.
15
+ * - `{ kind: 'allow-unauthenticated-local-admin' }` — session starts
16
+ * immediately with a `stdio-local` principal. The CLI flag that
17
+ * enables this reads "grants full engine access to any local
18
+ * process that can spawn this binary" in both the help text and
19
+ * the startup log.
20
+ * - `{ kind: 'require-one' }` — neither flag supplied → exit 2.
21
+ *
22
+ * The session is a thin wrapper over the WS session: the only real
23
+ * difference is the transport (newline-delimited stdin/stdout instead
24
+ * of a socket) and the admission gate. Subscribe / unsubscribe and all
25
+ * the JSON-RPC semantics come from the shared session.
26
+ */
27
+ import type { ScopeVocabulary } from "./authorization-scope.js";
28
+ import type { OperationRegistry } from "./operation-catalog.js";
29
+ /** How a stdio session decides whether to admit its peer. */
30
+ export type StdioAdmission = {
31
+ readonly kind: 'require-one';
32
+ } | {
33
+ readonly kind: 'startup-token';
34
+ readonly token: string;
35
+ } | {
36
+ readonly kind: 'allow-unauthenticated-local-admin';
37
+ };
38
+ export type StdioSessionOptions = {
39
+ readonly input: ReadableStream<Uint8Array>;
40
+ readonly output: WritableStream<Uint8Array>;
41
+ readonly admission: StdioAdmission;
42
+ readonly registry: OperationRegistry;
43
+ readonly scopeVocabulary?: ScopeVocabulary;
44
+ readonly engine: unknown;
45
+ /** The host's workflow event feed, handed to `weft.workflows.subscribe` as `host.feed`. */
46
+ readonly feed: unknown;
47
+ /**
48
+ * The document `rpc.discover` answers with. A host on Weft's engine passes
49
+ * `createWeftDiscoverDocument(registry, engine)`, which lists the engine's MCP tools.
50
+ */
51
+ readonly discoverDocument: () => Record<string, unknown>;
52
+ readonly maxFrameBytes?: number;
53
+ readonly maxSubscriptions?: number;
54
+ };
55
+ /** How a stdio session ended: the process exit code and, when it failed, why. */
56
+ export type StdioSessionResult = {
57
+ /** The process exit code. */
58
+ readonly exitCode: number;
59
+ /** Why the session failed, when it did. */
60
+ readonly reason?: string;
61
+ };
62
+ /** Serves one JSON-RPC session over a pair of streams, after admitting the peer. */
63
+ export declare function runStdioSession(options: StdioSessionOptions): Promise<StdioSessionResult>;
64
+ /**
65
+ * Constant-time string comparison. Length leak is intentional and
66
+ * acceptable here (tokens are fixed-size hex in the intended
67
+ * deployment) — the goal is to prevent a per-character timing oracle
68
+ * on same-length candidates. For startup-token mode the attacker
69
+ * would need to already control the stdin side, so this is
70
+ * defense-in-depth rather than a load-bearing mitigation.
71
+ */