@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,128 @@
1
+ import { compareStrings, normalizeJsonObject } from "./json-schema-utilities.js";
2
+ import { zodToJsonSchema } from "./zod-json-schema.js";
3
+ /**
4
+ * Capture a set of operations, and the REST routes that serve them, as a
5
+ * {@link CatalogSnapshot}.
6
+ *
7
+ * The result is deterministic: operations sorted by name, schemas normalised,
8
+ * so two snapshots of the same surface are byte-identical and a real surface
9
+ * change is the only thing that shows up in a diff. That is what makes it safe
10
+ * to commit one and regenerate clients from it.
11
+ *
12
+ * A server supplies its own `operations` and `restBindings`. Weft's
13
+ * `createCatalogSnapshot` supplies every operation and route this build
14
+ * registers.
15
+ */
16
+ export function snapshotOperationCatalog(options) {
17
+ const sourceOperations = options.operations;
18
+ const restBindings = new Map(options.restBindings.map((binding) => [binding.operationName, binding]));
19
+ const operations = sourceOperations
20
+ .map((operation) => operationToSnapshot(operation, (operation.kind ?? 'unary') === 'unary' &&
21
+ operation.transports.http &&
22
+ !operation.transports.jsonRpcHttp &&
23
+ !operation.tags.includes('Storage')
24
+ ? restBindings.get(operation.name)
25
+ : undefined))
26
+ .toSorted((left, right) => compareStrings(left.name, right.name));
27
+ return {
28
+ generatedBy: 'weft catalog snapshot',
29
+ version: 1,
30
+ operations,
31
+ };
32
+ }
33
+ /**
34
+ * Serialise a {@link CatalogSnapshot} the way Weft writes it to disk:
35
+ * two-space indentation and a trailing newline.
36
+ *
37
+ * Use this rather than `JSON.stringify` when the output is going into a file.
38
+ * The formatting is part of the contract — a vendored snapshot written any
39
+ * other way produces a whole-file diff on the next regeneration, which buries
40
+ * the surface change you actually wanted to review.
41
+ *
42
+ * @example
43
+ * ```ts
44
+ * import { stringifyCatalogSnapshot } from '@lostgradient/backchannel';
45
+ * import { createCatalogSnapshot } from '@lostgradient/weft';
46
+ *
47
+ * const serialized = stringifyCatalogSnapshot(createCatalogSnapshot());
48
+ *
49
+ * console.log(serialized.endsWith('\n')); // true
50
+ * ```
51
+ */
52
+ export function stringifyCatalogSnapshot(snapshot) {
53
+ return `${JSON.stringify(snapshot, null, 2)}\n`;
54
+ }
55
+ function operationToSnapshot(operation, restBinding) {
56
+ const eventSchema = operation.eventSchema;
57
+ return {
58
+ name: operation.name,
59
+ mcpExposable: operation.mcpExposable,
60
+ ...behaviorToSnapshot(operation),
61
+ kind: operation.kind ?? 'unary',
62
+ summary: operation.summary,
63
+ ...(operation.description === undefined ? {} : { description: operation.description }),
64
+ tags: [...operation.tags].toSorted(compareStrings),
65
+ destructive: operation.destructive ?? false,
66
+ ...(operation.supportsDryRun === true ? { supportsDryRun: true } : {}),
67
+ access: accessToSnapshot(operation.access),
68
+ ...(operation.parameterizedAccess === undefined
69
+ ? {}
70
+ : { parameterizedAccess: parameterizedAccessToSnapshot(operation.parameterizedAccess) }),
71
+ transports: { ...operation.transports },
72
+ producibleFaults: [...(operation.producibleFaults ?? [])].toSorted(compareStrings),
73
+ inputSchema: normalizeJsonObject(zodToJsonSchema(operation.inputSchema, 'input')),
74
+ outputSchema: normalizeJsonObject(zodToJsonSchema(operation.outputSchema, 'output')),
75
+ ...(eventSchema === undefined
76
+ ? {}
77
+ : { eventSchema: normalizeJsonObject(zodToJsonSchema(eventSchema, 'output')) }),
78
+ ...(restBinding === undefined
79
+ ? {}
80
+ : {
81
+ rest: {
82
+ method: restBinding.method,
83
+ path: restBinding.path,
84
+ inputSources: Object.fromEntries(Object.entries(restBinding.inputSources).filter((entry) => entry[1] !== undefined)),
85
+ success: { ...restBinding.success },
86
+ },
87
+ }),
88
+ };
89
+ }
90
+ function behaviorToSnapshot(operation) {
91
+ return {
92
+ ...(operation.behavior === undefined ? {} : { behavior: operation.behavior }),
93
+ ...(operation.conflictReasonTokens === undefined
94
+ ? {}
95
+ : { conflictReasonTokens: operation.conflictReasonTokens }),
96
+ };
97
+ }
98
+ function parameterizedAccessToSnapshot(hint) {
99
+ return {
100
+ discriminator: hint.discriminator,
101
+ ...(hint.defaultValue === undefined ? {} : { defaultValue: hint.defaultValue }),
102
+ variants: hint.variants
103
+ .map((variant) => ({
104
+ value: variant.value,
105
+ access: accessToSnapshot(variant.access),
106
+ }))
107
+ .toSorted((left, right) => compareStrings(left.value, right.value)),
108
+ };
109
+ }
110
+ function accessToSnapshot(access) {
111
+ if (access.kind === 'public')
112
+ return { kind: 'public' };
113
+ if (access.kind === 'authenticated')
114
+ return { kind: 'authenticated' };
115
+ if (access.kind === 'scoped') {
116
+ return { kind: 'scoped', scopes: [...access.scopes.scopes].toSorted(compareStrings) };
117
+ }
118
+ if (access.kind === 'optionalAuth') {
119
+ return {
120
+ kind: 'optionalAuth',
121
+ scopes: [...access.authenticatedScopes.scopes].toSorted(compareStrings),
122
+ };
123
+ }
124
+ return {
125
+ kind: 'scopedAlternatives',
126
+ alternatives: access.alternatives.map((alternative) => [...alternative.scopes].toSorted(compareStrings)),
127
+ };
128
+ }
@@ -0,0 +1 @@
1
+ export * from "./operation-catalog/index.js";
@@ -0,0 +1 @@
1
+ export * from "./operation-catalog/index.js";
@@ -0,0 +1,44 @@
1
+ /**
2
+ * Audit that an operation catalog describes itself on the wire.
3
+ *
4
+ * @module server/operation-description-audit
5
+ */
6
+ import type { ErasedOperation } from "./operation-catalog.js";
7
+ /**
8
+ * The part of an operation the description audit reads. Anything
9
+ * `defineOperation` returns satisfies it.
10
+ */
11
+ type AuditedOperation = Pick<ErasedOperation, 'name' | 'description' | 'access' | 'discoverable' | 'inputSchema'>;
12
+ /**
13
+ * List what a catalog leaves undescribed in its discovery documents.
14
+ *
15
+ * Only discoverable operations are audited: public operations, and
16
+ * non-public ones marked `discoverable: true` (the same filter that decides
17
+ * what OpenAPI and OpenRPC list). Each is reported when it has no
18
+ * `description`, and once more for every top-level input field whose JSON
19
+ * Schema carries no `description`, which is the text a zod `.describe()` puts
20
+ * on the wire. The result is empty when the catalog is fully described, so a
21
+ * catalog's own test asserts it equals `[]` and fails with the offending names.
22
+ *
23
+ * Call `.describe()` last on a nullable field: `.describe('x').nullable()` wraps
24
+ * the described schema in an `anyOf`, so the field itself carries no
25
+ * `description` and is reported, while `.nullable().describe('x')` passes.
26
+ * Placing `.describe()` before `.optional()` or `.default()` also passes.
27
+ *
28
+ * Accepts a registry (anything with `list()`) or an iterable of operations.
29
+ * Entries read `<operation>: missing description` or
30
+ * `<operation>: parameter "<field>" missing description`, sorted by operation.
31
+ *
32
+ * @example
33
+ * ```ts
34
+ * import { findUndescribedOperations } from '@lostgradient/backchannel';
35
+ * import { createLiveOperationRegistry } from '@lostgradient/weft';
36
+ *
37
+ * const undescribed = findUndescribedOperations(createLiveOperationRegistry());
38
+ * console.log(undescribed.length === 0 ? 'every operation is described' : undescribed.join('\n'));
39
+ * ```
40
+ */
41
+ export declare function findUndescribedOperations(operations: Iterable<AuditedOperation> | {
42
+ list(): Iterable<AuditedOperation>;
43
+ }): ReadonlyArray<string>;
44
+ export {};
@@ -0,0 +1,90 @@
1
+ /**
2
+ * Audit that an operation catalog describes itself on the wire.
3
+ *
4
+ * @module server/operation-description-audit
5
+ */
6
+ import { z } from 'zod';
7
+ import { isDiscoverable } from "./discovery-filter.js";
8
+ import { zodToJsonSchema } from "./zod-json-schema.js";
9
+ function isPlainObject(value) {
10
+ return typeof value === 'object' && value !== null && !Array.isArray(value);
11
+ }
12
+ function hasText(value) {
13
+ return typeof value === 'string' && value.trim() !== '';
14
+ }
15
+ function isParameterDescribed(property, definitions) {
16
+ if (!isPlainObject(property))
17
+ return false;
18
+ if (hasText(property['description']))
19
+ return true;
20
+ // A reused schema is emitted once under `$defs` and referenced; the
21
+ // description then lives on the definition the reference resolves to.
22
+ const reference = property['$ref'];
23
+ if (typeof reference !== 'string' || definitions === undefined)
24
+ return false;
25
+ const prefix = '#/$defs/';
26
+ if (!reference.startsWith(prefix))
27
+ return false;
28
+ const definitionName = reference.slice(prefix.length);
29
+ if (!Object.hasOwn(definitions, definitionName))
30
+ return false;
31
+ const target = definitions[definitionName];
32
+ return isPlainObject(target) && hasText(target['description']);
33
+ }
34
+ function undescribedParameters(operation) {
35
+ // The registry already requires an object input; a non-object has no
36
+ // parameter fields to describe.
37
+ if (!(operation.inputSchema instanceof z.ZodObject))
38
+ return [];
39
+ const schema = zodToJsonSchema(operation.inputSchema);
40
+ const properties = schema['properties'];
41
+ if (!isPlainObject(properties))
42
+ return [];
43
+ const definitions = isPlainObject(schema['$defs']) ? schema['$defs'] : undefined;
44
+ return Object.keys(properties)
45
+ .filter((name) => !isParameterDescribed(properties[name], definitions))
46
+ .toSorted();
47
+ }
48
+ /**
49
+ * List what a catalog leaves undescribed in its discovery documents.
50
+ *
51
+ * Only discoverable operations are audited: public operations, and
52
+ * non-public ones marked `discoverable: true` (the same filter that decides
53
+ * what OpenAPI and OpenRPC list). Each is reported when it has no
54
+ * `description`, and once more for every top-level input field whose JSON
55
+ * Schema carries no `description`, which is the text a zod `.describe()` puts
56
+ * on the wire. The result is empty when the catalog is fully described, so a
57
+ * catalog's own test asserts it equals `[]` and fails with the offending names.
58
+ *
59
+ * Call `.describe()` last on a nullable field: `.describe('x').nullable()` wraps
60
+ * the described schema in an `anyOf`, so the field itself carries no
61
+ * `description` and is reported, while `.nullable().describe('x')` passes.
62
+ * Placing `.describe()` before `.optional()` or `.default()` also passes.
63
+ *
64
+ * Accepts a registry (anything with `list()`) or an iterable of operations.
65
+ * Entries read `<operation>: missing description` or
66
+ * `<operation>: parameter "<field>" missing description`, sorted by operation.
67
+ *
68
+ * @example
69
+ * ```ts
70
+ * import { findUndescribedOperations } from '@lostgradient/backchannel';
71
+ * import { createLiveOperationRegistry } from '@lostgradient/weft';
72
+ *
73
+ * const undescribed = findUndescribedOperations(createLiveOperationRegistry());
74
+ * console.log(undescribed.length === 0 ? 'every operation is described' : undescribed.join('\n'));
75
+ * ```
76
+ */
77
+ export function findUndescribedOperations(operations) {
78
+ const entries = Symbol.iterator in operations ? operations : operations.list();
79
+ const problems = [];
80
+ for (const operation of entries) {
81
+ if (!isDiscoverable(operation))
82
+ continue;
83
+ if (!hasText(operation.description))
84
+ problems.push(`${operation.name}: missing description`);
85
+ for (const field of undescribedParameters(operation)) {
86
+ problems.push(`${operation.name}: parameter "${field}" missing description`);
87
+ }
88
+ }
89
+ return problems.toSorted();
90
+ }
@@ -0,0 +1,21 @@
1
+ /**
2
+ * Helpers that build and recognise a transport-neutral {@link OperationFault}, with no knowledge of
3
+ * a host's error classes.
4
+ *
5
+ * @module server/operation-fault-helpers
6
+ */
7
+ import type { OperationFault } from "./operation-fault.js";
8
+ /** Type guard distinguishing an `OperationFault` from a value type. */
9
+ export declare function isOperationFault(value: unknown): value is OperationFault;
10
+ /**
11
+ * Construct an `InvalidParams` fault with the `{ issues: [] }` data
12
+ * shape. This is the canonical 400-class fault for caller-input validation
13
+ * errors raised inside `invoke()` or `extractInput()`.
14
+ *
15
+ * Pass `weftCode` only when a typed `WeftError` is in hand (e.g. a caught
16
+ * `WorkflowNotRegisteredError`) so REST clients can branch on it through
17
+ * `isWeftFault`. It is omitted entirely when absent — never written as
18
+ * `weftCode: undefined` — so the dozens of generic validation callers keep
19
+ * their exact `{ issues: [] }` data shape.
20
+ */
21
+ export declare function invalidParamsFault(message: string, weftCode?: string): OperationFault;
@@ -0,0 +1,32 @@
1
+ /**
2
+ * Helpers that build and recognise a transport-neutral {@link OperationFault}, with no knowledge of
3
+ * a host's error classes.
4
+ *
5
+ * @module server/operation-fault-helpers
6
+ */
7
+ /** Type guard distinguishing an `OperationFault` from a value type. */
8
+ export function isOperationFault(value) {
9
+ return (typeof value === 'object' &&
10
+ value !== null &&
11
+ 'code' in value &&
12
+ 'message' in value &&
13
+ 'data' in value);
14
+ }
15
+ /**
16
+ * Construct an `InvalidParams` fault with the `{ issues: [] }` data
17
+ * shape. This is the canonical 400-class fault for caller-input validation
18
+ * errors raised inside `invoke()` or `extractInput()`.
19
+ *
20
+ * Pass `weftCode` only when a typed `WeftError` is in hand (e.g. a caught
21
+ * `WorkflowNotRegisteredError`) so REST clients can branch on it through
22
+ * `isWeftFault`. It is omitted entirely when absent — never written as
23
+ * `weftCode: undefined` — so the dozens of generic validation callers keep
24
+ * their exact `{ issues: [] }` data shape.
25
+ */
26
+ export function invalidParamsFault(message, weftCode) {
27
+ return {
28
+ code: 'InvalidParams',
29
+ message,
30
+ data: weftCode === undefined ? { issues: [] } : { issues: [], weftCode },
31
+ };
32
+ }
@@ -0,0 +1,245 @@
1
+ /**
2
+ * Transport-neutral fault model for the operation pipeline.
3
+ *
4
+ * `OperationFault` is what `executeOperation` returns when a request fails.
5
+ * It carries a stable `code` (the discriminator), a human-readable `message`
6
+ * for logs, and a typed `data` payload narrowed per-code via discriminated
7
+ * union — so transport adapters can serialize the fault into the exact
8
+ * wire shape their protocol expects without a string-sniffing layer.
9
+ *
10
+ * Two pure mapper functions translate the fault into a transport-specific
11
+ * shape:
12
+ * - `faultToHttpResponse(fault)` for REST.
13
+ * - `faultToJsonRpcError(fault)` for the JSON-RPC transports.
14
+ * Both consume `OperationFault` directly; serialization is not a method on
15
+ * the fault class because that would force every transport to know about
16
+ * every other transport's wire shape.
17
+ *
18
+ * **Scope.** The union covers operation-pipeline faults — what
19
+ * `executeOperation` produces. Pure protocol-frame errors (JSON parse
20
+ * failure, invalid JSON-RPC request envelope) live in the JSON-RPC parser
21
+ * and use the spec-mandated reserved codes (-32700 / -32600); they do NOT
22
+ * pass through this fault model. The v1 union is open for additive
23
+ * extension — future codes (e.g. `PreconditionFailed`, `PayloadTooLarge`,
24
+ * `ResourceExhausted`) can be added without breaking existing serializers
25
+ * because the per-code mapping tables are exhaustive `Record<FaultCode, T>`
26
+ * and the JSON-RPC payload extractor is an exhaustive switch.
27
+ *
28
+ * **Every fault has a `data` field.** Even codes with no payload-specific
29
+ * detail (`NotImplemented`, `EngineFailure`) carry `data: {}` so transport
30
+ * adapters never branch on `data === undefined`. This uniformity is what
31
+ * lets the exhaustive switch in `extractFaultDataPayload` stay small.
32
+ *
33
+ * The stable fault model with transport-neutral code, message, and typed
34
+ * `data` payload forms the basis of cross-transport parity: every fault is
35
+ * serialized consistently across REST and JSON-RPC transports.
36
+ */
37
+ import { type FaultCode } from "./fault-code.js";
38
+ /** Transports `executeOperation` sees; `mcp` (a catalog MCP mount) admits `mcpExposable` ones. */
39
+ export type TransportKind = 'http-rest' | 'jsonRpcHttp' | 'jsonRpcWebSocket' | 'jsonRpcStdio' | 'mcp';
40
+ /** A revision identifier: a counter or an opaque token. */
41
+ export type RevisionToken = string | number;
42
+ /** A flattened zod issue, kept loose so we don't pin a zod version here. */
43
+ export type FlattenedZodIssue = {
44
+ readonly path: ReadonlyArray<string | number>;
45
+ readonly message: string;
46
+ readonly code: string;
47
+ };
48
+ /**
49
+ * The faults `executeOperation` returns, each with its typed `data` payload.
50
+ * {@link OperationFault} adds the advice every fault may carry.
51
+ */
52
+ type OperationFaultVariant = {
53
+ code: 'Unauthorized';
54
+ message: string;
55
+ data: {
56
+ reason: string;
57
+ };
58
+ } | {
59
+ code: 'Forbidden';
60
+ message: string;
61
+ data: {
62
+ reason: string;
63
+ };
64
+ } | {
65
+ code: 'NotFound';
66
+ message: string;
67
+ data: {
68
+ resource: string;
69
+ identifier?: string | undefined;
70
+ weftCode?: string;
71
+ };
72
+ } | {
73
+ code: 'Conflict';
74
+ message: string;
75
+ data: {
76
+ reason: string;
77
+ /** Stable, machine-readable reason approved for REST disclosure. */
78
+ publicReason?: 'workflow-replaced' | undefined;
79
+ weftCode?: string;
80
+ missingTypes?: readonly string[] | undefined;
81
+ missingWorkflowCount?: number | undefined;
82
+ samplesTruncated?: boolean | undefined;
83
+ currentGeneration?: number | undefined;
84
+ compatibilityReasons?: readonly string[] | undefined;
85
+ sourceValidationReasons?: readonly string[] | undefined;
86
+ };
87
+ } | {
88
+ code: 'Unprocessable';
89
+ message: string;
90
+ data: {
91
+ reason: string;
92
+ };
93
+ } | {
94
+ code: 'PayloadTooLarge';
95
+ message: string;
96
+ data: {
97
+ maxBytes: number;
98
+ };
99
+ } | {
100
+ code: 'Timeout';
101
+ message: string;
102
+ data: {
103
+ operationName?: string | undefined;
104
+ updateId?: string | undefined;
105
+ };
106
+ } | {
107
+ code: 'NotImplemented';
108
+ message: string;
109
+ data: Record<string, never>;
110
+ } | {
111
+ code: 'UnsupportedTransport';
112
+ message: string;
113
+ data: {
114
+ transport: TransportKind;
115
+ supported: ReadonlyArray<TransportKind>;
116
+ };
117
+ } | {
118
+ code: 'SubscriptionOverflow';
119
+ message: string;
120
+ data: {
121
+ subscriptionId: string;
122
+ droppedCount: number;
123
+ };
124
+ } | {
125
+ code: 'InvalidParams';
126
+ message: string;
127
+ data: {
128
+ issues: ReadonlyArray<FlattenedZodIssue>;
129
+ weftCode?: string;
130
+ };
131
+ } | {
132
+ code: 'MethodNotFound';
133
+ message: string;
134
+ data: {
135
+ method: string;
136
+ };
137
+ } | {
138
+ code: 'StaleRevision';
139
+ message: string;
140
+ data: {
141
+ expectedRevision?: RevisionToken | undefined;
142
+ currentRevision: RevisionToken;
143
+ };
144
+ } | {
145
+ code: 'RateLimited';
146
+ message: string;
147
+ data: {
148
+ retryAfterSeconds?: number | undefined;
149
+ };
150
+ } | {
151
+ code: 'Unavailable';
152
+ message: string;
153
+ data: {
154
+ reason?: string | undefined;
155
+ retryAfterSeconds?: number | undefined;
156
+ };
157
+ } | {
158
+ code: 'UnsupportedCapability';
159
+ message: string;
160
+ data: {
161
+ capability: string;
162
+ };
163
+ } | {
164
+ code: 'EngineFailure';
165
+ message: string;
166
+ data: Record<string, never>;
167
+ };
168
+ /**
169
+ * Transport-neutral fault returned by `executeOperation`. Each variant has a
170
+ * typed `data` payload — transport adapters destructure on `code` to access
171
+ * the shape they need.
172
+ *
173
+ * Every fault may also carry `remediation`: one line of plain text saying what
174
+ * the caller can do next (`assertValidRemediation` in `fault-remediation.ts` states the limits).
175
+ * Whether repeating the identical call can help is not a field of the fault: it
176
+ * is a property of the code, in `FAULT_CODE_RETRYABLE`, and the wire projections
177
+ * add it as `retryable` ({@link faultWireAdvice}).
178
+ */
179
+ export type OperationFault = OperationFaultVariant & {
180
+ remediation?: string | undefined;
181
+ };
182
+ /**
183
+ * HTTP status code for each fault, used by `faultToHttpResponse`. Values
184
+ * align with REST conventions; both `NotImplemented` and
185
+ * `UnsupportedTransport` map to 501 because the caller asked for something
186
+ * the server cannot fulfill.
187
+ */
188
+ export declare const FAULT_CODE_TO_HTTP_STATUS: Readonly<Record<FaultCode, number>>;
189
+ /**
190
+ * Format an `InvalidParams` fault as a single human-readable error string
191
+ * suitable for the body of a JSON response. Joins each Zod issue as
192
+ * `path: message` (or just `message` at the root) with `; ` separators.
193
+ */
194
+ export declare function formatInvalidParamsMessage(fault: Extract<OperationFault, {
195
+ code: 'InvalidParams';
196
+ }>): string;
197
+ /** Options for turning a fault into a REST response. */
198
+ export type RestFaultResponseOptions = {
199
+ /** REST-only status override for a binding with an established non-canonical status. */
200
+ readonly status?: number;
201
+ /** REST-only public message override for a binding with an established response message. */
202
+ readonly message?: string;
203
+ /** The host's error codes; a `data.weftCode` this rejects is dropped. Omitted, any string passes. */
204
+ readonly isKnownErrorCode?: (value: string) => boolean;
205
+ };
206
+ /**
207
+ * The REST fault body. `weftCode` is the fine-grained error code of
208
+ * the originating error class, present only when the fault carried one; the
209
+ * coarse {@link FaultCode} is not in the body at all. The HTTP status is
210
+ * derived from it, but that mapping is not injective (`NotFound` and
211
+ * `MethodNotFound` are both 404, for example), so a REST consumer cannot
212
+ * recover the exact `FaultCode` from the status. JSON-RPC uses
213
+ * the same `weftCode` key for the coarse `FaultCode` instead (see
214
+ * `fault-to-json-rpc.ts`).
215
+ */
216
+ export type RestFaultBody = {
217
+ readonly error: string;
218
+ readonly weftCode?: string;
219
+ readonly data?: Readonly<Record<string, unknown>>;
220
+ /** Whether repeating the identical call later can succeed; always present (see {@link faultWireAdvice}). */
221
+ readonly retryable: boolean;
222
+ /** One line saying what to do next, when the fault carries one. */
223
+ readonly remediation?: string;
224
+ };
225
+ /**
226
+ * Map an `OperationFault` to the canonical additive REST body:
227
+ * `{ error, weftCode?, data?, retryable, remediation? }`. The existing string `error` and optional
228
+ * fine-grained `weftCode` (the host's error code, never a {@link FaultCode})
229
+ * remain unchanged; `data` contains only fields from the audited allowlist
230
+ * above. JSON-RPC uses its own broader projection, whose `data.weftCode` is the
231
+ * coarse `FaultCode`.
232
+ *
233
+ * `EngineFailure` is a hard exception: its exact body remains
234
+ * `{ "error": "Internal server error", "retryable": false }`, regardless of response overrides.
235
+ */
236
+ export declare function shapeOperationFaultAsJson(fault: OperationFault, options?: RestFaultResponseOptions): Response;
237
+ /** Canonical REST response used by bindings and route-dispatch fallback. */
238
+ export declare function shapeRestFaultAsJson(fault: OperationFault, options?: RestFaultResponseOptions): Response;
239
+ /**
240
+ * JSON-RPC error code for each fault. Reserved codes (-32700..-32603) keep
241
+ * the spec meanings (`InvalidParams`, `MethodNotFound`); Weft domain codes
242
+ * live in -32010..-32099 documented per design decision 4.
243
+ */
244
+ export declare const FAULT_CODE_TO_JSON_RPC_CODE: Readonly<Record<FaultCode, number>>;
245
+ export {};