@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.
- package/LICENSE +21 -0
- package/README.md +62 -2
- package/dist/access-policy-metadata.d.ts +92 -0
- package/dist/access-policy-metadata.js +87 -0
- package/dist/asyncapi-channels.d.ts +46 -0
- package/dist/asyncapi-channels.js +399 -0
- package/dist/asyncapi.d.ts +40 -0
- package/dist/asyncapi.js +165 -0
- package/dist/authentication/api-key.d.ts +4 -0
- package/dist/authentication/api-key.js +114 -0
- package/dist/authentication/audit.d.ts +115 -0
- package/dist/authentication/audit.js +75 -0
- package/dist/authentication/credential-verifiers.d.ts +60 -0
- package/dist/authentication/credential-verifiers.js +102 -0
- package/dist/authentication/crypto.d.ts +7 -0
- package/dist/authentication/crypto.js +140 -0
- package/dist/authentication/index.d.ts +80 -0
- package/dist/authentication/index.js +212 -0
- package/dist/authentication/rate-limiter.d.ts +133 -0
- package/dist/authentication/rate-limiter.js +124 -0
- package/dist/authentication/redaction.d.ts +72 -0
- package/dist/authentication/redaction.js +118 -0
- package/dist/authentication/rotating-api-key-store.d.ts +127 -0
- package/dist/authentication/rotating-api-key-store.js +126 -0
- package/dist/authentication/types.d.ts +337 -0
- package/dist/authentication/types.js +26 -0
- package/dist/authentication.d.ts +1 -0
- package/dist/authentication.js +1 -0
- package/dist/authorization-scope.d.ts +109 -0
- package/dist/authorization-scope.js +144 -0
- package/dist/authorization.d.ts +55 -0
- package/dist/authorization.js +134 -0
- package/dist/bind-feed-lifetime.d.ts +45 -0
- package/dist/bind-feed-lifetime.js +55 -0
- package/dist/byte-arrays.d.ts +5 -0
- package/dist/byte-arrays.js +9 -0
- package/dist/client/catalog-client.d.ts +285 -0
- package/dist/client/catalog-client.js +74 -0
- package/dist/client/in-process-transport.d.ts +19 -0
- package/dist/client/in-process-transport.js +136 -0
- package/dist/client/index.d.ts +14 -0
- package/dist/client/index.js +14 -0
- package/dist/client/json-rpc-http-transport.d.ts +118 -0
- package/dist/client/json-rpc-http-transport.js +127 -0
- package/dist/client/server-sent-event-parser.d.ts +55 -0
- package/dist/client/server-sent-event-parser.js +78 -0
- package/dist/client/sse-subscription-transport.d.ts +72 -0
- package/dist/client/sse-subscription-transport.js +224 -0
- package/dist/client/subscription-client.d.ts +122 -0
- package/dist/client/subscription-client.js +28 -0
- package/dist/connection-lease.d.ts +10 -0
- package/dist/connection-lease.js +8 -0
- package/dist/discovery-filter.d.ts +13 -0
- package/dist/discovery-filter.js +16 -0
- package/dist/discovery-info.d.ts +94 -0
- package/dist/discovery-info.js +38 -0
- package/dist/event-selector.d.ts +7 -0
- package/dist/event-selector.js +7 -0
- package/dist/fault-code.d.ts +84 -0
- package/dist/fault-code.js +114 -0
- package/dist/fault-remediation.d.ts +30 -0
- package/dist/fault-remediation.js +52 -0
- package/dist/fault-to-http.d.ts +11 -0
- package/dist/fault-to-http.js +13 -0
- package/dist/fault-to-json-rpc.d.ts +53 -0
- package/dist/fault-to-json-rpc.js +143 -0
- package/dist/fault-wire-safety.d.ts +45 -0
- package/dist/fault-wire-safety.js +72 -0
- package/dist/generator.d.ts +9 -0
- package/dist/generator.js +9 -0
- package/dist/handler/auth-context-principal.d.ts +37 -0
- package/dist/handler/auth-context-principal.js +67 -0
- package/dist/handler/authentication-responses.d.ts +23 -0
- package/dist/handler/authentication-responses.js +34 -0
- package/dist/handler/json-responses.d.ts +15 -0
- package/dist/handler/json-responses.js +32 -0
- package/dist/handler/operation-handler-authentication.d.ts +64 -0
- package/dist/handler/operation-handler-authentication.js +58 -0
- package/dist/handler/operation-handler-discovery.d.ts +29 -0
- package/dist/handler/operation-handler-discovery.js +55 -0
- package/dist/handler/operation-handler-mounts.d.ts +100 -0
- package/dist/handler/operation-handler-mounts.js +134 -0
- package/dist/handler/operation-handler-subscription.d.ts +34 -0
- package/dist/handler/operation-handler-subscription.js +112 -0
- package/dist/handler/operation-handler.d.ts +162 -0
- package/dist/handler/operation-handler.js +236 -0
- package/dist/handler/workspace-release.d.ts +6 -0
- package/dist/handler/workspace-release.js +75 -0
- package/dist/in-memory-replay-live-backend.d.ts +47 -0
- package/dist/in-memory-replay-live-backend.js +129 -0
- package/dist/index.d.ts +37 -0
- package/dist/index.js +30 -0
- package/dist/internal/cryptography/encryption.d.ts +108 -0
- package/dist/internal/cryptography/encryption.js +241 -0
- package/dist/internal/cryptography/hash.d.ts +72 -0
- package/dist/internal/cryptography/hash.js +233 -0
- package/dist/internal/cryptography/index.d.ts +4 -0
- package/dist/internal/cryptography/index.js +2 -0
- package/dist/internals.d.ts +58 -0
- package/dist/internals.js +54 -0
- package/dist/json-rpc-dispatch.d.ts +88 -0
- package/dist/json-rpc-dispatch.js +154 -0
- package/dist/json-rpc-framing.d.ts +42 -0
- package/dist/json-rpc-framing.js +50 -0
- package/dist/json-rpc-http.d.ts +36 -0
- package/dist/json-rpc-http.js +191 -0
- package/dist/json-rpc-parse.d.ts +69 -0
- package/dist/json-rpc-parse.js +206 -0
- package/dist/json-rpc-protocol.d.ts +76 -0
- package/dist/json-rpc-protocol.js +54 -0
- package/dist/json-rpc-session-runtime.d.ts +55 -0
- package/dist/json-rpc-session-runtime.js +111 -0
- package/dist/json-rpc-websocket-subscription-pump.d.ts +9 -0
- package/dist/json-rpc-websocket-subscription-pump.js +46 -0
- package/dist/json-rpc-websocket-subscriptions.d.ts +10 -0
- package/dist/json-rpc-websocket-subscriptions.js +33 -0
- package/dist/json-rpc-websocket-types.d.ts +34 -0
- package/dist/json-rpc-websocket-types.js +1 -0
- package/dist/json-rpc-websocket-validation.d.ts +45 -0
- package/dist/json-rpc-websocket-validation.js +154 -0
- package/dist/json-rpc-websocket.d.ts +20 -0
- package/dist/json-rpc-websocket.js +363 -0
- package/dist/json-schema-utilities.d.ts +5 -0
- package/dist/json-schema-utilities.js +17 -0
- package/dist/mcp-discovery-names.d.ts +11 -0
- package/dist/mcp-discovery-names.js +11 -0
- package/dist/openapi-canonical-json.d.ts +10 -0
- package/dist/openapi-canonical-json.js +23 -0
- package/dist/openapi-error-responses.d.ts +15 -0
- package/dist/openapi-error-responses.js +104 -0
- package/dist/openapi-schemas.d.ts +17 -0
- package/dist/openapi-schemas.js +94 -0
- package/dist/openapi.d.ts +60 -0
- package/dist/openapi.js +351 -0
- package/dist/openrpc-document-schema.d.ts +255 -0
- package/dist/openrpc-document-schema.js +84 -0
- package/dist/openrpc-errors.d.ts +93 -0
- package/dist/openrpc-errors.js +134 -0
- package/dist/openrpc.d.ts +66 -0
- package/dist/openrpc.js +260 -0
- package/dist/operation-catalog/behavior-types.d.ts +34 -0
- package/dist/operation-catalog/behavior-types.js +1 -0
- package/dist/operation-catalog/behavior-validation.d.ts +3 -0
- package/dist/operation-catalog/behavior-validation.js +298 -0
- package/dist/operation-catalog/dispatch-allowlist.d.ts +4 -0
- package/dist/operation-catalog/dispatch-allowlist.js +7 -0
- package/dist/operation-catalog/dispatch-preparation.d.ts +24 -0
- package/dist/operation-catalog/dispatch-preparation.js +49 -0
- package/dist/operation-catalog/index.d.ts +19 -0
- package/dist/operation-catalog/index.js +17 -0
- package/dist/operation-catalog/operation-dispatch.d.ts +14 -0
- package/dist/operation-catalog/operation-dispatch.js +115 -0
- package/dist/operation-catalog/operation-interceptors.d.ts +15 -0
- package/dist/operation-catalog/operation-interceptors.js +1 -0
- package/dist/operation-catalog/operation-metadata.d.ts +5 -0
- package/dist/operation-catalog/operation-metadata.js +104 -0
- package/dist/operation-catalog/pipeline-helpers.d.ts +70 -0
- package/dist/operation-catalog/pipeline-helpers.js +242 -0
- package/dist/operation-catalog/pipeline-stages.d.ts +23 -0
- package/dist/operation-catalog/pipeline-stages.js +226 -0
- package/dist/operation-catalog/pipeline.d.ts +7 -0
- package/dist/operation-catalog/pipeline.js +33 -0
- package/dist/operation-catalog/registry.d.ts +17 -0
- package/dist/operation-catalog/registry.js +132 -0
- package/dist/operation-catalog/stream-pipeline.d.ts +37 -0
- package/dist/operation-catalog/stream-pipeline.js +129 -0
- package/dist/operation-catalog/subscription-lifecycle.d.ts +6 -0
- package/dist/operation-catalog/subscription-lifecycle.js +27 -0
- package/dist/operation-catalog/types.d.ts +392 -0
- package/dist/operation-catalog/types.js +40 -0
- package/dist/operation-catalog/universal-faults.d.ts +11 -0
- package/dist/operation-catalog/universal-faults.js +15 -0
- package/dist/operation-catalog-snapshot.d.ts +215 -0
- package/dist/operation-catalog-snapshot.js +128 -0
- package/dist/operation-catalog.d.ts +1 -0
- package/dist/operation-catalog.js +1 -0
- package/dist/operation-description-audit.d.ts +44 -0
- package/dist/operation-description-audit.js +90 -0
- package/dist/operation-fault-helpers.d.ts +21 -0
- package/dist/operation-fault-helpers.js +32 -0
- package/dist/operation-fault.d.ts +245 -0
- package/dist/operation-fault.js +235 -0
- package/dist/operation-registry.d.ts +46 -0
- package/dist/operation-registry.js +46 -0
- package/dist/operations/closable-iterable.d.ts +23 -0
- package/dist/operations/closable-iterable.js +51 -0
- package/dist/operations/get-principal.d.ts +106 -0
- package/dist/operations/get-principal.js +107 -0
- package/dist/operations/sse-stream.d.ts +67 -0
- package/dist/operations/sse-stream.js +264 -0
- package/dist/principal.d.ts +253 -0
- package/dist/principal.js +254 -0
- package/dist/replay-live-feed-internals.d.ts +47 -0
- package/dist/replay-live-feed-internals.js +215 -0
- package/dist/replay-live-feed-types.d.ts +66 -0
- package/dist/replay-live-feed-types.js +7 -0
- package/dist/replay-live-feed.d.ts +49 -0
- package/dist/replay-live-feed.js +126 -0
- package/dist/rest-binding.d.ts +215 -0
- package/dist/rest-binding.js +95 -0
- package/dist/rest-body.d.ts +17 -0
- package/dist/rest-body.js +95 -0
- package/dist/route-model.d.ts +305 -0
- package/dist/route-model.js +320 -0
- package/dist/runtime/cors.d.ts +161 -0
- package/dist/runtime/cors.js +265 -0
- package/dist/scripts/generate-operation-client.d.ts +186 -0
- package/dist/scripts/generate-operation-client.js +561 -0
- package/dist/scripts/operation-behaviors.d.ts +3 -0
- package/dist/scripts/operation-behaviors.js +16 -0
- package/dist/scripts/operation-client-aliases.d.ts +32 -0
- package/dist/scripts/operation-client-aliases.js +255 -0
- package/dist/scripts/operation-client-domains.d.ts +21 -0
- package/dist/scripts/operation-client-domains.js +74 -0
- package/dist/scripts/operation-client-schema.d.ts +46 -0
- package/dist/scripts/operation-client-schema.js +310 -0
- package/dist/scripts/operation-client-svelte.d.ts +3 -0
- package/dist/scripts/operation-client-svelte.js +61 -0
- package/dist/sequence-cursor.d.ts +46 -0
- package/dist/sequence-cursor.js +62 -0
- package/dist/sse-error-payload-schema.d.ts +12 -0
- package/dist/sse-error-payload-schema.js +33 -0
- package/dist/stdio-session.d.ts +71 -0
- package/dist/stdio-session.js +347 -0
- package/dist/zod-json-schema.d.ts +22 -0
- package/dist/zod-json-schema.js +49 -0
- package/package.json +38 -3
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
import { drainLive, replayUpTo, shouldDeliverEnvelope } from "./replay-live-feed-internals.js";
|
|
2
|
+
const decodeCursor = (cursor) => /^(?:-1|\d+)$/.test(cursor) && Number.isSafeInteger(Number(cursor)) ? Number(cursor) : null;
|
|
3
|
+
const encodeCursor = (sequence) => String(sequence);
|
|
4
|
+
const DEFAULT_LIVE_BUFFER_SIZE = 1000;
|
|
5
|
+
/** Builds a {@link ReplayLiveFeed} over a backend. `liveBufferSize` bounds the envelopes buffered for a subscriber that reads slowly. */
|
|
6
|
+
export function createReplayLiveFeed(backend, options) {
|
|
7
|
+
const bufferSize = options?.liveBufferSize ?? DEFAULT_LIVE_BUFFER_SIZE;
|
|
8
|
+
const decode = (cursor) => backend.decodeCursor?.(cursor) ??
|
|
9
|
+
(() => {
|
|
10
|
+
const sequence = decodeCursor(cursor);
|
|
11
|
+
return sequence === null ? 'invalid' : { sequence };
|
|
12
|
+
})();
|
|
13
|
+
const decodeOrThrow = (cursor) => {
|
|
14
|
+
const result = decode(cursor);
|
|
15
|
+
if (result === 'invalid')
|
|
16
|
+
throw new Error('Invalid cursor');
|
|
17
|
+
return result;
|
|
18
|
+
};
|
|
19
|
+
const continuation = (sequence) => backend.encodeCursor?.(sequence) ?? (sequence < 0 ? '-1' : encodeCursor(sequence));
|
|
20
|
+
const subscriptionGap = async function* (cursor, snapshot, signal) {
|
|
21
|
+
if (signal?.aborted ||
|
|
22
|
+
cursor === undefined ||
|
|
23
|
+
backend.createGapEnvelope === undefined ||
|
|
24
|
+
decode(cursor) !== 'gap')
|
|
25
|
+
return;
|
|
26
|
+
const firstRetainedSequence = backend.snapshotFirstRetainedSequence === undefined
|
|
27
|
+
? snapshot + 1
|
|
28
|
+
: await backend.snapshotFirstRetainedSequence();
|
|
29
|
+
if (signal?.aborted)
|
|
30
|
+
return;
|
|
31
|
+
yield backend.createGapEnvelope({
|
|
32
|
+
requestedCursor: cursor,
|
|
33
|
+
firstRetainedSequence,
|
|
34
|
+
continuationCursor: continuation(firstRetainedSequence - 1),
|
|
35
|
+
});
|
|
36
|
+
};
|
|
37
|
+
const gap = async function* (fromCursor, replayOperation) {
|
|
38
|
+
if (fromCursor !== undefined && decodeOrThrow(fromCursor) === 'gap') {
|
|
39
|
+
const firstRetainedSequence = (await backend.snapshotFirstRetainedSequence?.()) ??
|
|
40
|
+
(await backend.snapshotTailSequence()) + 1;
|
|
41
|
+
const createGapEnvelope = backend.createGapEnvelope === undefined
|
|
42
|
+
? undefined
|
|
43
|
+
: (input) => backend.createGapEnvelope(input);
|
|
44
|
+
if (createGapEnvelope !== undefined)
|
|
45
|
+
yield createGapEnvelope({
|
|
46
|
+
requestedCursor: fromCursor,
|
|
47
|
+
firstRetainedSequence,
|
|
48
|
+
continuationCursor: continuation(firstRetainedSequence - 1),
|
|
49
|
+
});
|
|
50
|
+
}
|
|
51
|
+
yield* replayOperation();
|
|
52
|
+
};
|
|
53
|
+
async function* replay(args) {
|
|
54
|
+
const decoded = args?.fromCursor === undefined ? { sequence: -1 } : decodeOrThrow(args.fromCursor);
|
|
55
|
+
let yielded = 0;
|
|
56
|
+
for await (const envelope of gap(args?.fromCursor, () => backend.replay({
|
|
57
|
+
afterSequence: decoded === 'gap' ? -1 : decoded.sequence,
|
|
58
|
+
...(args?.fromCursor === undefined ? {} : { requestedCursor: args.fromCursor }),
|
|
59
|
+
}))) {
|
|
60
|
+
if (args?.limit !== undefined && yielded >= args.limit)
|
|
61
|
+
return;
|
|
62
|
+
yield envelope;
|
|
63
|
+
yielded += 1;
|
|
64
|
+
}
|
|
65
|
+
}
|
|
66
|
+
function subscribe(args) {
|
|
67
|
+
const buffer = [];
|
|
68
|
+
let overflowed = false;
|
|
69
|
+
let waker = null;
|
|
70
|
+
let cleanedUp = false;
|
|
71
|
+
const signal = args?.signal;
|
|
72
|
+
const fromCursor = args?.fromCursor;
|
|
73
|
+
const decoded = fromCursor === undefined ? { sequence: -1 } : decodeOrThrow(fromCursor);
|
|
74
|
+
const requestedAfter = decoded === 'gap' ? -1 : decoded.sequence;
|
|
75
|
+
const unsubscribe = backend.subscribeLive((envelope) => {
|
|
76
|
+
if (!shouldDeliverEnvelope(envelope, args))
|
|
77
|
+
return;
|
|
78
|
+
if (buffer.length >= bufferSize)
|
|
79
|
+
overflowed = true;
|
|
80
|
+
else
|
|
81
|
+
buffer.push(envelope);
|
|
82
|
+
const wake = waker;
|
|
83
|
+
waker = null;
|
|
84
|
+
wake?.();
|
|
85
|
+
});
|
|
86
|
+
const wake = () => {
|
|
87
|
+
const pending = waker;
|
|
88
|
+
waker = null;
|
|
89
|
+
pending?.();
|
|
90
|
+
};
|
|
91
|
+
const cleanup = () => {
|
|
92
|
+
if (cleanedUp)
|
|
93
|
+
return;
|
|
94
|
+
cleanedUp = true;
|
|
95
|
+
signal?.removeEventListener('abort', onAbort);
|
|
96
|
+
unsubscribe();
|
|
97
|
+
wake();
|
|
98
|
+
};
|
|
99
|
+
const onAbort = () => cleanup();
|
|
100
|
+
signal?.addEventListener('abort', onAbort, { once: true });
|
|
101
|
+
if (signal?.aborted)
|
|
102
|
+
cleanup();
|
|
103
|
+
async function* generate() {
|
|
104
|
+
try {
|
|
105
|
+
if (signal?.aborted)
|
|
106
|
+
return;
|
|
107
|
+
const snapshot = await backend.snapshotTailSequence();
|
|
108
|
+
yield* subscriptionGap(fromCursor, snapshot, signal);
|
|
109
|
+
if (signal?.aborted)
|
|
110
|
+
return;
|
|
111
|
+
yield* replayUpTo(backend, requestedAfter, snapshot, signal, args, fromCursor, decode);
|
|
112
|
+
if (signal?.aborted)
|
|
113
|
+
return;
|
|
114
|
+
args?.onReplayComplete?.();
|
|
115
|
+
yield* drainLive(buffer, snapshot, signal, () => overflowed, (next) => {
|
|
116
|
+
waker = next;
|
|
117
|
+
});
|
|
118
|
+
}
|
|
119
|
+
finally {
|
|
120
|
+
cleanup();
|
|
121
|
+
}
|
|
122
|
+
}
|
|
123
|
+
return generate();
|
|
124
|
+
}
|
|
125
|
+
return { replay, subscribe, decodeCursor: decode, dispose() { } };
|
|
126
|
+
}
|
|
@@ -0,0 +1,215 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `RestBinding<Input, Output>` — the REST-facing wrapper that references
|
|
3
|
+
* a transport-neutral `OperationDefinition` by name. The binding owns
|
|
4
|
+
* all HTTP-specific concerns that don't belong on the operation:
|
|
5
|
+
* method, path, where each input field is extracted from (path /
|
|
6
|
+
* query / header / body), and how the output is shaped into an HTTP
|
|
7
|
+
* response.
|
|
8
|
+
*
|
|
9
|
+
* This module deliberately does NOT import `route-model.ts`: bindings
|
|
10
|
+
* describe operation-backed HTTP routes, while that model describes the
|
|
11
|
+
* remaining REST-only meta and discovery endpoints.
|
|
12
|
+
*/
|
|
13
|
+
import type { OperationFault } from "./operation-fault.js";
|
|
14
|
+
import type { RestBodyReadOptions } from "./rest-body.js";
|
|
15
|
+
import type { HttpMethod } from "./route-model.js";
|
|
16
|
+
/**
|
|
17
|
+
* Thrown by `bindingPathMatches` when a URL path parameter contains malformed
|
|
18
|
+
* percent-encoding. The top-level handler catches it and returns a 400.
|
|
19
|
+
*/
|
|
20
|
+
export declare class MalformedRouteParameterError extends Error {
|
|
21
|
+
/** Stable machine-readable discriminant; equals the class name, as a `WeftError`'s does. */
|
|
22
|
+
readonly code = "MalformedRouteParameterError";
|
|
23
|
+
constructor();
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Where a single top-level field of the operation's `inputSchema`
|
|
27
|
+
* comes from in a REST request. The OpenAPI generator reads this to
|
|
28
|
+
* emit accurate path / query / header / requestBody schema pieces.
|
|
29
|
+
*/
|
|
30
|
+
export type ParamSource = {
|
|
31
|
+
readonly kind: 'path';
|
|
32
|
+
readonly pathParam: string;
|
|
33
|
+
} | {
|
|
34
|
+
readonly kind: 'query';
|
|
35
|
+
readonly queryParam: string;
|
|
36
|
+
readonly repeating?: boolean;
|
|
37
|
+
} | {
|
|
38
|
+
readonly kind: 'header';
|
|
39
|
+
readonly headerName: string;
|
|
40
|
+
} | {
|
|
41
|
+
readonly kind: 'body';
|
|
42
|
+
readonly mediaType?: 'application/json' | 'application/octet-stream';
|
|
43
|
+
} | {
|
|
44
|
+
readonly kind: 'body-field';
|
|
45
|
+
readonly bodyField: string;
|
|
46
|
+
};
|
|
47
|
+
/**
|
|
48
|
+
* How the operation's output is turned into an HTTP response.
|
|
49
|
+
* - `json` — standard `Response.json(output, { status })`.
|
|
50
|
+
* - `empty` — 204 No Content; output is ignored.
|
|
51
|
+
* - `streaming` — the operation's output is an async iterable of
|
|
52
|
+
* bytes/events; the transport adapter streams directly.
|
|
53
|
+
*/
|
|
54
|
+
export type ResponseShape = {
|
|
55
|
+
readonly kind: 'json';
|
|
56
|
+
readonly status: number;
|
|
57
|
+
} | {
|
|
58
|
+
readonly kind: 'empty';
|
|
59
|
+
readonly status: number;
|
|
60
|
+
} | {
|
|
61
|
+
readonly kind: 'streaming';
|
|
62
|
+
readonly mediaType: 'text/event-stream' | 'application/octet-stream' | 'application/x-ndjson';
|
|
63
|
+
};
|
|
64
|
+
/**
|
|
65
|
+
* The part of a REST binding the documents and the catalog snapshot describe: where the route is
|
|
66
|
+
* and how its input and response travel. Any {@link RestBinding} satisfies it whatever its input
|
|
67
|
+
* and output types, so the generic document generators take bindings without naming those types.
|
|
68
|
+
*/
|
|
69
|
+
export type RestBindingDescription = {
|
|
70
|
+
readonly method: HttpMethod;
|
|
71
|
+
readonly path: string;
|
|
72
|
+
readonly pathParamNames: ReadonlyArray<string>;
|
|
73
|
+
readonly operationName: string;
|
|
74
|
+
readonly transportKind?: 'unary' | 'sse' | 'websocket-subscription';
|
|
75
|
+
readonly inputSources: Partial<Record<string, ParamSource>>;
|
|
76
|
+
readonly success: ResponseShape;
|
|
77
|
+
};
|
|
78
|
+
/** What the REST input readers need from their caller: the body limit. */
|
|
79
|
+
export type RestInputContext = RestBodyReadOptions;
|
|
80
|
+
/**
|
|
81
|
+
* Binds a REST mount point to an `OperationDefinition`. Generic over
|
|
82
|
+
* `Input` / `Output` so `extractInput` returns a value the operation's
|
|
83
|
+
* schema accepts, and `shapeSuccess` consumes the output without casts.
|
|
84
|
+
*/
|
|
85
|
+
export type RestBinding<Input, Output> = {
|
|
86
|
+
/** The HTTP method. */
|
|
87
|
+
readonly method: HttpMethod;
|
|
88
|
+
/** Express-style path with `:name` placeholders (e.g., `/v1/workflows/:id`). */
|
|
89
|
+
readonly path: string;
|
|
90
|
+
/** Ordered list of path param names; must match the `:name` tokens in `path`. */
|
|
91
|
+
readonly pathParamNames: ReadonlyArray<string>;
|
|
92
|
+
/** Operation-catalog name this binding dispatches to. */
|
|
93
|
+
readonly operationName: string;
|
|
94
|
+
/**
|
|
95
|
+
* Long-lived transport specialization for structural catalog checks.
|
|
96
|
+
* Omitted bindings are ordinary unary REST request/response operations.
|
|
97
|
+
*/
|
|
98
|
+
readonly transportKind?: 'unary' | 'sse' | 'websocket-subscription';
|
|
99
|
+
/**
|
|
100
|
+
* Declarative map from top-level `Input` field names to their REST
|
|
101
|
+
* source. Fields omitted from this map are not extracted from the
|
|
102
|
+
* request by the OpenAPI generator's schema emission — `extractInput`
|
|
103
|
+
* remains the authoritative runtime source. Keys are constrained to
|
|
104
|
+
* string-typed keys of `Input` so a typo becomes a compile error
|
|
105
|
+
* rather than a silent no-op at generator time.
|
|
106
|
+
*/
|
|
107
|
+
readonly inputSources: Partial<Record<Extract<keyof Input, string>, ParamSource>>;
|
|
108
|
+
/**
|
|
109
|
+
* Read the REST request and produce the operation's typed `Input`.
|
|
110
|
+
* Called before `executeOperation`; the returned value is what the
|
|
111
|
+
* pipeline's schema parse step sees.
|
|
112
|
+
*/
|
|
113
|
+
readonly extractInput: (request: Request, pathParams: Record<string, string>, context: RestInputContext) => Promise<Input>;
|
|
114
|
+
/** Canonical response shape — OpenAPI reads this, handler may override via `shapeSuccess`. */
|
|
115
|
+
readonly success: ResponseShape;
|
|
116
|
+
/**
|
|
117
|
+
* Optional override for response construction. When absent, transport
|
|
118
|
+
* adapters default to `jsonResponse(output, success.status)`, which emits
|
|
119
|
+
* `JSON.stringify(output)` with `Content-Type: application/json` (or
|
|
120
|
+
* `new Response(null, { status })` for `empty`). Provide this
|
|
121
|
+
* when the wire representation differs from `output` verbatim.
|
|
122
|
+
*
|
|
123
|
+
* Receives the original `Request` so REST-only response shaping —
|
|
124
|
+
* `Accept` header negotiation (json vs msgpack), redirect URL
|
|
125
|
+
* construction, etc. — can stay in the binding without leaking
|
|
126
|
+
* HTTP-specific state into the operation's `Output` type. Other
|
|
127
|
+
* transports (JSON-RPC HTTP/WS/stdio) never call `shapeSuccess`;
|
|
128
|
+
* they emit `output` directly via the canonical envelope, so the
|
|
129
|
+
* operation contract stays transport-neutral.
|
|
130
|
+
*/
|
|
131
|
+
readonly shapeSuccess?: (output: Output, request: Request) => Response;
|
|
132
|
+
/**
|
|
133
|
+
* Optional override for fault → HTTP response mapping. When absent,
|
|
134
|
+
* the transport adapter falls back to `faultToHttpResponse`, which emits
|
|
135
|
+
* the same flat audited `{ error, weftCode?, data?, retryable, remediation? }` body as
|
|
136
|
+
* `shapeRestFault`. This is distinct from the JSON-RPC fault object
|
|
137
|
+
* (`faultToJsonRpcError`), which uses `{ code, message, data }` with a numeric
|
|
138
|
+
* `code` and a broader data projection. REST and JSON-RPC deliberately differ
|
|
139
|
+
* in fault shape, so each transport owns its own projection.
|
|
140
|
+
*
|
|
141
|
+
* REST operations provide this to shape faults the way a REST client
|
|
142
|
+
* expects: most use `shapeRestFault`, which masks an `EngineFailure` to a
|
|
143
|
+
* flat `{ error: "Internal server error" }` with status `500` (never
|
|
144
|
+
* leaking internal detail over REST), adds audited safe context under a
|
|
145
|
+
* `data` sibling for other faults, and maps the remaining fault codes to
|
|
146
|
+
* their HTTP statuses. A few operations supply a bespoke shaper to special-case
|
|
147
|
+
* a particular fault — typically to override its message or to handle one code
|
|
148
|
+
* explicitly — while delegating the rest. The status often matches what the
|
|
149
|
+
* shared map would already produce; the shaper exists for the operation-specific
|
|
150
|
+
* detail (for example, `get-workflow-result` returns the custom message
|
|
151
|
+
* `"Timeout waiting for workflow result"` on a `Timeout`, and `get-stream-chunks`
|
|
152
|
+
* handles `InvalidParams` inline). This per-operation hook is the current
|
|
153
|
+
* contract.
|
|
154
|
+
*/
|
|
155
|
+
readonly shapeFault?: (fault: OperationFault) => Response;
|
|
156
|
+
};
|
|
157
|
+
/**
|
|
158
|
+
* The router stores heterogeneous bindings whose `Input`/`Output` pairs
|
|
159
|
+
* all differ. `RestBinding<Input, Output>` is strictly-typed at the
|
|
160
|
+
* author boundary (so `defineOperation` + binding factories catch
|
|
161
|
+
* mistakes), but at the router level those generics are irrelevant —
|
|
162
|
+
* every binding produces a `Response` regardless of its output type.
|
|
163
|
+
*
|
|
164
|
+
* `RestBinding<any, any>` is the idiomatic way to express "a binding
|
|
165
|
+
* with SOME Input/Output pair the router doesn't care about." A stricter
|
|
166
|
+
* `unknown, unknown` form fails under `exactOptionalPropertyTypes`
|
|
167
|
+
* because `shapeSuccess: (Output) => Response` cannot be safely widened
|
|
168
|
+
* to `(unknown) => Response` (function parameters are contravariant).
|
|
169
|
+
*/
|
|
170
|
+
export type UnknownRestBinding = RestBinding<any, any>;
|
|
171
|
+
/**
|
|
172
|
+
* Match a binding's `:name` path pattern against a concrete URL path.
|
|
173
|
+
* Returns a map of path-param names → URL-decoded values, or `null`
|
|
174
|
+
* when the path does not match the pattern's structure.
|
|
175
|
+
*
|
|
176
|
+
* An empty segment (`/foo//bar`) is treated as a non-match: an empty
|
|
177
|
+
* path param would propagate to the engine as a confusingly-shaped
|
|
178
|
+
* "missing" identifier, and surfacing the shape error at the router
|
|
179
|
+
* (404) produces a cleaner wire response than a downstream 400.
|
|
180
|
+
*
|
|
181
|
+
* WHATWG URL path normalization collapses `.` and `..` path segments (and
|
|
182
|
+
* their percent-encoded forms) before `handleRequest()` ever sees
|
|
183
|
+
* `url.pathname` — this function never observes those segments as literal
|
|
184
|
+
* text, so a single trailing `:id`/`:operationId` segment can never match a
|
|
185
|
+
* resource whose id is literally `.` or `..`, no matter how it is encoded.
|
|
186
|
+
* This is no longer just a documented gap: `assertValidWorkflowId` (WFT-95)
|
|
187
|
+
* and `isValidOperationId` reject those exact strings at admission, so a
|
|
188
|
+
* caller-facing workflow or operation id can never legitimately be `.` or
|
|
189
|
+
* `..` in the first place — this URL-normalization quirk is closed by
|
|
190
|
+
* validation rather than left as something callers must work around.
|
|
191
|
+
*/
|
|
192
|
+
export declare function bindingPathMatches(pattern: string, actualPath: string): Record<string, string> | null;
|
|
193
|
+
/**
|
|
194
|
+
* Runtime guard: a `RestBinding` is only dispatchable if it references
|
|
195
|
+
* a live `OperationDefinition` that declares `transports.http === true`
|
|
196
|
+
* AND the binding's `operationName` matches the operation's name. The
|
|
197
|
+
* OpenAPI generator and the REST router consult this to exclude
|
|
198
|
+
* bindings whose operation no longer mounts on HTTP.
|
|
199
|
+
*
|
|
200
|
+
* The binding and operation are typed independently here. Structural
|
|
201
|
+
* compatibility between `Input`/`Output` is not checked at the type
|
|
202
|
+
* level — that's the registry's job at registration, and enforcing it
|
|
203
|
+
* here would require the caller to thread matching generics through
|
|
204
|
+
* every call site. This runtime guard only asserts the two concrete
|
|
205
|
+
* runtime properties the router depends on: name equality and HTTP
|
|
206
|
+
* availability.
|
|
207
|
+
*/
|
|
208
|
+
export declare function isRestBindingCompatibleWithOperation(binding: {
|
|
209
|
+
readonly operationName: string;
|
|
210
|
+
}, operation: {
|
|
211
|
+
readonly name: string;
|
|
212
|
+
readonly transports: {
|
|
213
|
+
readonly http: boolean;
|
|
214
|
+
};
|
|
215
|
+
}): boolean;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* `RestBinding<Input, Output>` — the REST-facing wrapper that references
|
|
3
|
+
* a transport-neutral `OperationDefinition` by name. The binding owns
|
|
4
|
+
* all HTTP-specific concerns that don't belong on the operation:
|
|
5
|
+
* method, path, where each input field is extracted from (path /
|
|
6
|
+
* query / header / body), and how the output is shaped into an HTTP
|
|
7
|
+
* response.
|
|
8
|
+
*
|
|
9
|
+
* This module deliberately does NOT import `route-model.ts`: bindings
|
|
10
|
+
* describe operation-backed HTTP routes, while that model describes the
|
|
11
|
+
* remaining REST-only meta and discovery endpoints.
|
|
12
|
+
*/
|
|
13
|
+
/**
|
|
14
|
+
* Thrown by `bindingPathMatches` when a URL path parameter contains malformed
|
|
15
|
+
* percent-encoding. The top-level handler catches it and returns a 400.
|
|
16
|
+
*/
|
|
17
|
+
export class MalformedRouteParameterError extends Error {
|
|
18
|
+
/** Stable machine-readable discriminant; equals the class name, as a `WeftError`'s does. */
|
|
19
|
+
code = 'MalformedRouteParameterError';
|
|
20
|
+
constructor() {
|
|
21
|
+
super('Malformed route parameter encoding');
|
|
22
|
+
this.name = this.code;
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
/**
|
|
26
|
+
* Match a binding's `:name` path pattern against a concrete URL path.
|
|
27
|
+
* Returns a map of path-param names → URL-decoded values, or `null`
|
|
28
|
+
* when the path does not match the pattern's structure.
|
|
29
|
+
*
|
|
30
|
+
* An empty segment (`/foo//bar`) is treated as a non-match: an empty
|
|
31
|
+
* path param would propagate to the engine as a confusingly-shaped
|
|
32
|
+
* "missing" identifier, and surfacing the shape error at the router
|
|
33
|
+
* (404) produces a cleaner wire response than a downstream 400.
|
|
34
|
+
*
|
|
35
|
+
* WHATWG URL path normalization collapses `.` and `..` path segments (and
|
|
36
|
+
* their percent-encoded forms) before `handleRequest()` ever sees
|
|
37
|
+
* `url.pathname` — this function never observes those segments as literal
|
|
38
|
+
* text, so a single trailing `:id`/`:operationId` segment can never match a
|
|
39
|
+
* resource whose id is literally `.` or `..`, no matter how it is encoded.
|
|
40
|
+
* This is no longer just a documented gap: `assertValidWorkflowId` (WFT-95)
|
|
41
|
+
* and `isValidOperationId` reject those exact strings at admission, so a
|
|
42
|
+
* caller-facing workflow or operation id can never legitimately be `.` or
|
|
43
|
+
* `..` in the first place — this URL-normalization quirk is closed by
|
|
44
|
+
* validation rather than left as something callers must work around.
|
|
45
|
+
*/
|
|
46
|
+
export function bindingPathMatches(pattern, actualPath) {
|
|
47
|
+
const patternSegments = pattern.split('/');
|
|
48
|
+
const actualSegments = actualPath.split('/');
|
|
49
|
+
if (patternSegments.length !== actualSegments.length)
|
|
50
|
+
return null;
|
|
51
|
+
const params = {};
|
|
52
|
+
for (let index = 0; index < patternSegments.length; index += 1) {
|
|
53
|
+
const patternSegment = patternSegments[index] ?? '';
|
|
54
|
+
const actualSegment = actualSegments[index] ?? '';
|
|
55
|
+
if (patternSegment.startsWith(':')) {
|
|
56
|
+
if (actualSegment.length === 0)
|
|
57
|
+
return null;
|
|
58
|
+
const name = patternSegment.slice(1);
|
|
59
|
+
try {
|
|
60
|
+
params[name] = decodeURIComponent(actualSegment);
|
|
61
|
+
}
|
|
62
|
+
catch {
|
|
63
|
+
// Malformed percent-encoding (e.g. `%` or `%GG`) — the caller
|
|
64
|
+
// (handleRequest) catches this and returns a 400.
|
|
65
|
+
throw new MalformedRouteParameterError();
|
|
66
|
+
}
|
|
67
|
+
}
|
|
68
|
+
else if (patternSegment !== actualSegment) {
|
|
69
|
+
return null;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return params;
|
|
73
|
+
}
|
|
74
|
+
/**
|
|
75
|
+
* Runtime guard: a `RestBinding` is only dispatchable if it references
|
|
76
|
+
* a live `OperationDefinition` that declares `transports.http === true`
|
|
77
|
+
* AND the binding's `operationName` matches the operation's name. The
|
|
78
|
+
* OpenAPI generator and the REST router consult this to exclude
|
|
79
|
+
* bindings whose operation no longer mounts on HTTP.
|
|
80
|
+
*
|
|
81
|
+
* The binding and operation are typed independently here. Structural
|
|
82
|
+
* compatibility between `Input`/`Output` is not checked at the type
|
|
83
|
+
* level — that's the registry's job at registration, and enforcing it
|
|
84
|
+
* here would require the caller to thread matching generics through
|
|
85
|
+
* every call site. This runtime guard only asserts the two concrete
|
|
86
|
+
* runtime properties the router depends on: name equality and HTTP
|
|
87
|
+
* availability.
|
|
88
|
+
*/
|
|
89
|
+
export function isRestBindingCompatibleWithOperation(binding, operation) {
|
|
90
|
+
if (binding.operationName !== operation.name)
|
|
91
|
+
return false;
|
|
92
|
+
if (!operation.transports.http)
|
|
93
|
+
return false;
|
|
94
|
+
return true;
|
|
95
|
+
}
|
|
@@ -0,0 +1,17 @@
|
|
|
1
|
+
import type { OperationFault } from "./operation-fault.js";
|
|
2
|
+
/** The default limit on a REST request body: 1 MiB. */
|
|
3
|
+
export declare const DEFAULT_REST_MAX_BODY_BYTES: number;
|
|
4
|
+
/** Options for reading a REST request body. */
|
|
5
|
+
export type RestBodyReadOptions = {
|
|
6
|
+
/** The largest body to accept, in bytes. */
|
|
7
|
+
readonly maxBodyBytes?: number;
|
|
8
|
+
};
|
|
9
|
+
export declare function payloadTooLargeFault(maxBytes: number): OperationFault;
|
|
10
|
+
/** Reads a request body, refusing one larger than the limit with a `PayloadTooLarge` fault. */
|
|
11
|
+
export declare function readRestBodyBounded(request: Request, options?: RestBodyReadOptions): Promise<Uint8Array>;
|
|
12
|
+
/** Reads a request body within the size limit and decodes it as UTF-8. */
|
|
13
|
+
export declare function readRestTextBody(request: Request, options?: RestBodyReadOptions): Promise<string>;
|
|
14
|
+
/** Reads a request body within the size limit and parses it as JSON. */
|
|
15
|
+
export declare function readRestJsonBody(request: Request, options?: RestBodyReadOptions): Promise<unknown>;
|
|
16
|
+
/** Reads a JSON request body within the size limit, or `undefined` when the body is empty. */
|
|
17
|
+
export declare function readOptionalRestJsonBody(request: Request, options?: RestBodyReadOptions): Promise<unknown>;
|
|
@@ -0,0 +1,95 @@
|
|
|
1
|
+
/** The default limit on a REST request body: 1 MiB. */
|
|
2
|
+
export const DEFAULT_REST_MAX_BODY_BYTES = 1 * 1024 * 1024;
|
|
3
|
+
const CONTENT_LENGTH_PATTERN = /^(0|[1-9]\d*)$/;
|
|
4
|
+
export function payloadTooLargeFault(maxBytes) {
|
|
5
|
+
return {
|
|
6
|
+
code: 'PayloadTooLarge',
|
|
7
|
+
message: 'Payload Too Large',
|
|
8
|
+
data: { maxBytes },
|
|
9
|
+
};
|
|
10
|
+
}
|
|
11
|
+
function invalidContentLengthFault() {
|
|
12
|
+
return {
|
|
13
|
+
code: 'InvalidParams',
|
|
14
|
+
message: 'Invalid Content-Length header',
|
|
15
|
+
data: { issues: [] },
|
|
16
|
+
};
|
|
17
|
+
}
|
|
18
|
+
function resolveMaxBodyBytes(options) {
|
|
19
|
+
const maxBytes = options?.maxBodyBytes ?? DEFAULT_REST_MAX_BODY_BYTES;
|
|
20
|
+
if (!Number.isSafeInteger(maxBytes) || maxBytes < 0) {
|
|
21
|
+
throw new Error('REST body size limit must be a non-negative safe integer');
|
|
22
|
+
}
|
|
23
|
+
return maxBytes;
|
|
24
|
+
}
|
|
25
|
+
function assertDeclaredContentLengthWithinLimit(request, maxBytes) {
|
|
26
|
+
const header = request.headers.get('content-length');
|
|
27
|
+
if (header === null)
|
|
28
|
+
return;
|
|
29
|
+
if (!CONTENT_LENGTH_PATTERN.test(header)) {
|
|
30
|
+
throw invalidContentLengthFault();
|
|
31
|
+
}
|
|
32
|
+
const declared = Number(header);
|
|
33
|
+
if (!Number.isSafeInteger(declared) || declared < 0) {
|
|
34
|
+
throw invalidContentLengthFault();
|
|
35
|
+
}
|
|
36
|
+
if (declared > maxBytes) {
|
|
37
|
+
throw payloadTooLargeFault(maxBytes);
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
async function cancelReaderAfterPayloadOverflow(reader) {
|
|
41
|
+
try {
|
|
42
|
+
await reader.cancel();
|
|
43
|
+
}
|
|
44
|
+
catch {
|
|
45
|
+
// The payload limit has already been crossed. Preserve the 413 fault even
|
|
46
|
+
// when an underlying runtime or client body rejects cancellation.
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
/** Reads a request body, refusing one larger than the limit with a `PayloadTooLarge` fault. */
|
|
50
|
+
export async function readRestBodyBounded(request, options) {
|
|
51
|
+
const maxBytes = resolveMaxBodyBytes(options);
|
|
52
|
+
assertDeclaredContentLengthWithinLimit(request, maxBytes);
|
|
53
|
+
const body = request.body;
|
|
54
|
+
if (body === null)
|
|
55
|
+
return new Uint8Array();
|
|
56
|
+
const reader = body.getReader();
|
|
57
|
+
const chunks = [];
|
|
58
|
+
let total = 0;
|
|
59
|
+
try {
|
|
60
|
+
while (true) {
|
|
61
|
+
const { done, value } = await reader.read();
|
|
62
|
+
if (done)
|
|
63
|
+
break;
|
|
64
|
+
total += value.byteLength;
|
|
65
|
+
if (total > maxBytes) {
|
|
66
|
+
await cancelReaderAfterPayloadOverflow(reader);
|
|
67
|
+
throw payloadTooLargeFault(maxBytes);
|
|
68
|
+
}
|
|
69
|
+
chunks.push(value);
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
finally {
|
|
73
|
+
reader.releaseLock();
|
|
74
|
+
}
|
|
75
|
+
const bytes = new Uint8Array(total);
|
|
76
|
+
let offset = 0;
|
|
77
|
+
for (const chunk of chunks) {
|
|
78
|
+
bytes.set(chunk, offset);
|
|
79
|
+
offset += chunk.byteLength;
|
|
80
|
+
}
|
|
81
|
+
return bytes;
|
|
82
|
+
}
|
|
83
|
+
/** Reads a request body within the size limit and decodes it as UTF-8. */
|
|
84
|
+
export async function readRestTextBody(request, options) {
|
|
85
|
+
return new TextDecoder('utf-8').decode(await readRestBodyBounded(request, options));
|
|
86
|
+
}
|
|
87
|
+
/** Reads a request body within the size limit and parses it as JSON. */
|
|
88
|
+
export async function readRestJsonBody(request, options) {
|
|
89
|
+
return JSON.parse(await readRestTextBody(request, options));
|
|
90
|
+
}
|
|
91
|
+
/** Reads a JSON request body within the size limit, or `undefined` when the body is empty. */
|
|
92
|
+
export async function readOptionalRestJsonBody(request, options) {
|
|
93
|
+
const text = await readRestTextBody(request, options);
|
|
94
|
+
return text.trim() === '' ? undefined : JSON.parse(text);
|
|
95
|
+
}
|