@ts-pf/stream 0.7.0 → 1.0.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/README.md +29 -3
- package/dist/codec.js +2 -2
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/sse-codec.d.ts +24 -0
- package/dist/sse-codec.d.ts.map +1 -0
- package/dist/sse-codec.js +116 -0
- package/dist/sse-codec.js.map +1 -0
- package/dist/sse.d.ts +9 -0
- package/dist/sse.d.ts.map +1 -0
- package/dist/sse.js +192 -0
- package/dist/sse.js.map +1 -0
- package/package.json +12 -10
- package/skills/ts-pf-stream/SKILL.md +24 -7
package/README.md
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
# @ts-pf/stream
|
|
2
2
|
|
|
3
|
-
Opt-in
|
|
3
|
+
Opt-in codecs for root `AsyncIterable` input and output. JSON calls stay JSON. `StreamCodec` frames streams as `application/jsonl` (one existing RPC envelope per line); `SseCodec` frames stream **output** as `text/event-stream`.
|
|
4
4
|
|
|
5
5
|
Agent skill: [`skills/ts-pf-stream/`](skills/ts-pf-stream/). Sync with `npx skills experimental_sync -y`.
|
|
6
6
|
|
|
@@ -21,8 +21,34 @@ procedure.output(stream(z.object({ token: z.string() })))
|
|
|
21
21
|
|
|
22
22
|
An input `stream(item)` takes items of the item schema's input type from the sender; the handler iterates parsed items.
|
|
23
23
|
|
|
24
|
-
Use the same codec on the handler and the link. A `stream()` procedure on the default `
|
|
24
|
+
Use the same codec on the handler and the link. A `stream()` procedure on the default `JsonCodec` (or `MultipartCodec`) answers `400 BAD_REQUEST` `Stream procedure requires a streaming codec` before the handler runs.
|
|
25
25
|
|
|
26
26
|
Put cleanup on the handler's `signal`, not in a generator's `finally`: a cancel calls the stream's `return()`, and an async generator that was never pulled completes on `return()` without running its body, so its `finally` never runs, and a generator waiting on an `await` between yields does not see `return()` until its next `yield`. Over HTTP the handler's `signal` is `request.signal`, which fires on disconnect when your host aborts it.
|
|
27
27
|
|
|
28
|
-
|
|
28
|
+
## Server-sent events
|
|
29
|
+
|
|
30
|
+
`SseCodec` frames root `AsyncIterable` output as `text/event-stream`. JSON calls stay JSON, and input streams stay `application/jsonl`. Contracts use the same `stream()`:
|
|
31
|
+
|
|
32
|
+
```ts
|
|
33
|
+
import { procedure } from '@ts-pf/contract'
|
|
34
|
+
import { z } from 'zod'
|
|
35
|
+
import { SseCodec, stream } from '@ts-pf/stream'
|
|
36
|
+
|
|
37
|
+
import { FetchHandler } from '@ts-pf/server-http'
|
|
38
|
+
import { FetchLink } from '@ts-pf/client-http'
|
|
39
|
+
|
|
40
|
+
const codec = new SseCodec() // optional { inner, keepAliveMs } — default 15_000; 0 disables pings
|
|
41
|
+
new FetchHandler(app, { codec })
|
|
42
|
+
new FetchLink({ url: '/rpc', codec })
|
|
43
|
+
|
|
44
|
+
procedure.output(stream(z.object({ token: z.string() })))
|
|
45
|
+
```
|
|
46
|
+
|
|
47
|
+
An `event: error` after the stream started rejects the iterator with a `PFError` whose `status` is `undefined` (the response was already 200); switch on `code`. `SSE_CONTENT_TYPE` is the response content type. `SseCodec` was `@ts-pf/sse` before 1.0.
|
|
48
|
+
|
|
49
|
+
## API
|
|
50
|
+
|
|
51
|
+
- `StreamCodec`, `stream()`
|
|
52
|
+
- `SseCodec`, `SSE_CONTENT_TYPE`
|
|
53
|
+
|
|
54
|
+
Wire spec: [`packages/protocol/PROTOCOL.md`](../protocol/PROTOCOL.md) (Message streams, SSE).
|
package/dist/codec.js
CHANGED
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { isJsonContentType,
|
|
1
|
+
import { isJsonContentType, JsonCodec, jsonBodySource, mimeType, } from '@ts-pf/http';
|
|
2
2
|
import { PFError, toWireError, } from '@ts-pf/protocol';
|
|
3
3
|
import { isItemStream } from './item-stream.js';
|
|
4
4
|
import { badRequest, encodeJsonl, JSONL_CONTENT_TYPE, readJsonlLines, } from './jsonl.js';
|
|
@@ -41,7 +41,7 @@ export class StreamCodec {
|
|
|
41
41
|
streams = true;
|
|
42
42
|
inner;
|
|
43
43
|
constructor(options) {
|
|
44
|
-
this.inner = options?.inner ?? new
|
|
44
|
+
this.inner = options?.inner ?? new JsonCodec();
|
|
45
45
|
}
|
|
46
46
|
async encodeRequest(req) {
|
|
47
47
|
if (isItemStream(req.input)) {
|
package/dist/index.d.ts
CHANGED
package/dist/index.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.d.ts","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA"}
|
package/dist/index.js
CHANGED
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA"}
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../src/index.ts"],"names":[],"mappings":"AAAA,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,MAAM,EAAE,MAAM,aAAa,CAAA;AACpC,OAAO,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAC3C,OAAO,EAAE,QAAQ,EAAE,MAAM,gBAAgB,CAAA"}
|
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
import { type EnvelopeTextCodec, type RpcBodySource, type RpcCodec, type RpcEncodedBody } from '@ts-pf/http';
|
|
2
|
+
import { type RpcRequest, type RpcResponse } from '@ts-pf/protocol';
|
|
3
|
+
export declare class SseCodec implements RpcCodec {
|
|
4
|
+
/** SSE output; stream input is JSONL (through `StreamCodec`). */
|
|
5
|
+
readonly streams: boolean;
|
|
6
|
+
private readonly inner;
|
|
7
|
+
private readonly stream;
|
|
8
|
+
private readonly keepAliveMs;
|
|
9
|
+
constructor(options?: {
|
|
10
|
+
inner?: EnvelopeTextCodec;
|
|
11
|
+
keepAliveMs?: number;
|
|
12
|
+
});
|
|
13
|
+
encodeRequest(req: RpcRequest): RpcEncodedBody | Promise<RpcEncodedBody>;
|
|
14
|
+
decodeRequest(source: RpcBodySource): Promise<RpcRequest>;
|
|
15
|
+
encodeSuccess<T>(output: T): Promise<RpcEncodedBody>;
|
|
16
|
+
encodeFailure(error: {
|
|
17
|
+
code: string;
|
|
18
|
+
message: string;
|
|
19
|
+
data?: unknown;
|
|
20
|
+
}): RpcEncodedBody | Promise<RpcEncodedBody>;
|
|
21
|
+
decodeResponse<T = unknown>(source: RpcBodySource): Promise<RpcResponse<T>>;
|
|
22
|
+
private readOutputEvents;
|
|
23
|
+
}
|
|
24
|
+
//# sourceMappingURL=sse-codec.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse-codec.d.ts","sourceRoot":"","sources":["../src/sse-codec.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,iBAAiB,EAItB,KAAK,aAAa,EAClB,KAAK,QAAQ,EACb,KAAK,cAAc,EACpB,MAAM,aAAa,CAAA;AACpB,OAAO,EAGL,KAAK,UAAU,EACf,KAAK,WAAW,EAEjB,MAAM,iBAAiB,CAAA;AA4BxB,qBAAa,QAAS,YAAW,QAAQ;IACvC,iEAAiE;IACjE,QAAQ,CAAC,OAAO,EAAE,OAAO,CAAO;IAChC,OAAO,CAAC,QAAQ,CAAC,KAAK,CAAmB;IACzC,OAAO,CAAC,QAAQ,CAAC,MAAM,CAAa;IACpC,OAAO,CAAC,QAAQ,CAAC,WAAW,CAAQ;gBAExB,OAAO,CAAC,EAAE;QAAE,KAAK,CAAC,EAAE,iBAAiB,CAAC;QAAC,WAAW,CAAC,EAAE,MAAM,CAAA;KAAE;IAMzE,aAAa,CAAC,GAAG,EAAE,UAAU,GAAG,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;IAIlE,aAAa,CAAC,MAAM,EAAE,aAAa,GAAG,OAAO,CAAC,UAAU,CAAC;IAOzD,aAAa,CAAC,CAAC,EAAE,MAAM,EAAE,CAAC,GAAG,OAAO,CAAC,cAAc,CAAC;IAkB1D,aAAa,CAAC,KAAK,EAAE;QACnB,IAAI,EAAE,MAAM,CAAA;QACZ,OAAO,EAAE,MAAM,CAAA;QACf,IAAI,CAAC,EAAE,OAAO,CAAA;KACf,GAAG,cAAc,GAAG,OAAO,CAAC,cAAc,CAAC;IAItC,cAAc,CAAC,CAAC,GAAG,OAAO,EAC9B,MAAM,EAAE,aAAa,GACpB,OAAO,CAAC,WAAW,CAAC,CAAC,CAAC,CAAC;YAWX,gBAAgB;CAmDhC"}
|
|
@@ -0,0 +1,116 @@
|
|
|
1
|
+
import { JsonCodec, jsonBodySource, mimeType, } from '@ts-pf/http';
|
|
2
|
+
import { PFError, toWireError, } from '@ts-pf/protocol';
|
|
3
|
+
import { StreamCodec } from './codec.js';
|
|
4
|
+
import { isItemStream } from './item-stream.js';
|
|
5
|
+
import { encodeSse, readSseEvents, SSE_CONTENT_TYPE } from './sse.js';
|
|
6
|
+
/** In-band failure after the stream started: an unknown throw is `INTERNAL`. */
|
|
7
|
+
function failureLine(error) {
|
|
8
|
+
const failure = { ok: false, error: toWireError(error) };
|
|
9
|
+
return JSON.stringify(failure);
|
|
10
|
+
}
|
|
11
|
+
function isSseContentType(contentType) {
|
|
12
|
+
return mimeType(contentType) === SSE_CONTENT_TYPE;
|
|
13
|
+
}
|
|
14
|
+
function badRequest(message) {
|
|
15
|
+
return new PFError({ code: 'BAD_REQUEST', status: 400, message });
|
|
16
|
+
}
|
|
17
|
+
function assertItem(value) {
|
|
18
|
+
if (isItemStream(value)) {
|
|
19
|
+
throw badRequest('Nested streams are not supported');
|
|
20
|
+
}
|
|
21
|
+
if (typeof Blob !== 'undefined' && value instanceof Blob) {
|
|
22
|
+
throw badRequest('File values are not supported in streams');
|
|
23
|
+
}
|
|
24
|
+
}
|
|
25
|
+
export class SseCodec {
|
|
26
|
+
/** SSE output; stream input is JSONL (through `StreamCodec`). */
|
|
27
|
+
streams = true;
|
|
28
|
+
inner;
|
|
29
|
+
stream;
|
|
30
|
+
keepAliveMs;
|
|
31
|
+
constructor(options) {
|
|
32
|
+
this.inner = options?.inner ?? new JsonCodec();
|
|
33
|
+
this.stream = new StreamCodec({ inner: this.inner });
|
|
34
|
+
this.keepAliveMs = options?.keepAliveMs ?? 15_000;
|
|
35
|
+
}
|
|
36
|
+
encodeRequest(req) {
|
|
37
|
+
return this.stream.encodeRequest(req);
|
|
38
|
+
}
|
|
39
|
+
async decodeRequest(source) {
|
|
40
|
+
if (isSseContentType(source.contentType)) {
|
|
41
|
+
throw badRequest('SSE is not supported as a request content type');
|
|
42
|
+
}
|
|
43
|
+
return this.stream.decodeRequest(source);
|
|
44
|
+
}
|
|
45
|
+
async encodeSuccess(output) {
|
|
46
|
+
if (isItemStream(output)) {
|
|
47
|
+
return {
|
|
48
|
+
contentType: SSE_CONTENT_TYPE,
|
|
49
|
+
body: encodeSse(output, async (item) => {
|
|
50
|
+
assertItem(item);
|
|
51
|
+
return (await this.inner.encodeSuccess(item)).body;
|
|
52
|
+
}, failureLine, this.keepAliveMs),
|
|
53
|
+
};
|
|
54
|
+
}
|
|
55
|
+
return this.stream.encodeSuccess(output);
|
|
56
|
+
}
|
|
57
|
+
encodeFailure(error) {
|
|
58
|
+
return this.stream.encodeFailure(error);
|
|
59
|
+
}
|
|
60
|
+
async decodeResponse(source) {
|
|
61
|
+
if (isSseContentType(source.contentType)) {
|
|
62
|
+
const stream = source.body();
|
|
63
|
+
if (!stream) {
|
|
64
|
+
throw badRequest('Missing stream body');
|
|
65
|
+
}
|
|
66
|
+
return { ok: true, output: this.readOutputEvents(stream) };
|
|
67
|
+
}
|
|
68
|
+
return this.stream.decodeResponse(source);
|
|
69
|
+
}
|
|
70
|
+
async *readOutputEvents(stream) {
|
|
71
|
+
let closed = false;
|
|
72
|
+
for await (const event of readSseEvents(stream)) {
|
|
73
|
+
if (event.event === 'close') {
|
|
74
|
+
closed = true;
|
|
75
|
+
return;
|
|
76
|
+
}
|
|
77
|
+
if (event.event === 'error') {
|
|
78
|
+
const decoded = await this.inner.decodeResponse(jsonBodySource(event.data));
|
|
79
|
+
if (!decoded.ok) {
|
|
80
|
+
throw new PFError({
|
|
81
|
+
code: decoded.error.code,
|
|
82
|
+
message: decoded.error.message,
|
|
83
|
+
...(decoded.error.data !== undefined
|
|
84
|
+
? { data: decoded.error.data }
|
|
85
|
+
: {}),
|
|
86
|
+
});
|
|
87
|
+
}
|
|
88
|
+
throw new PFError({
|
|
89
|
+
code: 'INTERNAL',
|
|
90
|
+
message: 'Invalid error event',
|
|
91
|
+
});
|
|
92
|
+
}
|
|
93
|
+
if (event.event !== 'message') {
|
|
94
|
+
continue;
|
|
95
|
+
}
|
|
96
|
+
const decoded = await this.inner.decodeResponse(jsonBodySource(event.data));
|
|
97
|
+
if (!decoded.ok) {
|
|
98
|
+
throw new PFError({
|
|
99
|
+
code: decoded.error.code,
|
|
100
|
+
message: decoded.error.message,
|
|
101
|
+
...(decoded.error.data !== undefined
|
|
102
|
+
? { data: decoded.error.data }
|
|
103
|
+
: {}),
|
|
104
|
+
});
|
|
105
|
+
}
|
|
106
|
+
yield decoded.output;
|
|
107
|
+
}
|
|
108
|
+
if (!closed) {
|
|
109
|
+
throw new PFError({
|
|
110
|
+
code: 'INTERNAL',
|
|
111
|
+
message: 'Stream truncated',
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
//# sourceMappingURL=sse-codec.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse-codec.js","sourceRoot":"","sources":["../src/sse-codec.ts"],"names":[],"mappings":"AAAA,OAAO,EAEL,SAAS,EACT,cAAc,EACd,QAAQ,GAIT,MAAM,aAAa,CAAA;AACpB,OAAO,EACL,OAAO,EAIP,WAAW,GACZ,MAAM,iBAAiB,CAAA;AACxB,OAAO,EAAE,WAAW,EAAE,MAAM,YAAY,CAAA;AACxC,OAAO,EAAE,YAAY,EAAE,MAAM,kBAAkB,CAAA;AAC/C,OAAO,EAAE,SAAS,EAAE,aAAa,EAAE,gBAAgB,EAAE,MAAM,UAAU,CAAA;AAErE,gFAAgF;AAChF,SAAS,WAAW,CAAC,KAAc;IACjC,MAAM,OAAO,GAAe,EAAE,EAAE,EAAE,KAAK,EAAE,KAAK,EAAE,WAAW,CAAC,KAAK,CAAC,EAAE,CAAA;IACpE,OAAO,IAAI,CAAC,SAAS,CAAC,OAAO,CAAC,CAAA;AAChC,CAAC;AAED,SAAS,gBAAgB,CAAC,WAA0B;IAClD,OAAO,QAAQ,CAAC,WAAW,CAAC,KAAK,gBAAgB,CAAA;AACnD,CAAC;AAED,SAAS,UAAU,CAAC,OAAe;IACjC,OAAO,IAAI,OAAO,CAAC,EAAE,IAAI,EAAE,aAAa,EAAE,MAAM,EAAE,GAAG,EAAE,OAAO,EAAE,CAAC,CAAA;AACnE,CAAC;AAED,SAAS,UAAU,CAAC,KAAc;IAChC,IAAI,YAAY,CAAC,KAAK,CAAC,EAAE,CAAC;QACxB,MAAM,UAAU,CAAC,kCAAkC,CAAC,CAAA;IACtD,CAAC;IACD,IAAI,OAAO,IAAI,KAAK,WAAW,IAAI,KAAK,YAAY,IAAI,EAAE,CAA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|
+
data: string;
|
|
5
|
+
};
|
|
6
|
+
export declare function readSseEvents(stream: ReadableStream<Uint8Array>): AsyncGenerator<SseEvent>;
|
|
7
|
+
export declare function encodeSse(items: AsyncIterable<unknown>, writeLine: (item: unknown) => string | Promise<string>, onError: (error: unknown) => string, keepAliveMs: number): ReadableStream<Uint8Array>;
|
|
8
|
+
export {};
|
|
9
|
+
//# sourceMappingURL=sse.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse.d.ts","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,eAAO,MAAM,gBAAgB,sBAAsB,CAAA;AAEnD,KAAK,QAAQ,GAAG;IACd,KAAK,EAAE,MAAM,CAAA;IACb,IAAI,EAAE,MAAM,CAAA;CACb,CAAA;AAgCD,wBAAuB,aAAa,CAClC,MAAM,EAAE,cAAc,CAAC,UAAU,CAAC,GACjC,cAAc,CAAC,QAAQ,CAAC,CA4E1B;AAED,wBAAgB,SAAS,CACvB,KAAK,EAAE,aAAa,CAAC,OAAO,CAAC,EAC7B,SAAS,EAAE,CAAC,IAAI,EAAE,OAAO,KAAK,MAAM,GAAG,OAAO,CAAC,MAAM,CAAC,EACtD,OAAO,EAAE,CAAC,KAAK,EAAE,OAAO,KAAK,MAAM,EACnC,WAAW,EAAE,MAAM,GAClB,cAAc,CAAC,UAAU,CAAC,CA8E5B"}
|
package/dist/sse.js
ADDED
|
@@ -0,0 +1,192 @@
|
|
|
1
|
+
export const SSE_CONTENT_TYPE = 'text/event-stream';
|
|
2
|
+
const COMMENT = ':\n\n';
|
|
3
|
+
const CLOSE_EVENT = 'event: close\n\n';
|
|
4
|
+
function encodeEvent(event, data) {
|
|
5
|
+
return `event: ${event}\ndata: ${data}\n\n`;
|
|
6
|
+
}
|
|
7
|
+
function splitLines(buffer) {
|
|
8
|
+
const lines = [];
|
|
9
|
+
let i = 0;
|
|
10
|
+
while (i < buffer.length) {
|
|
11
|
+
const cr = buffer.indexOf('\r', i);
|
|
12
|
+
const lf = buffer.indexOf('\n', i);
|
|
13
|
+
if (cr === -1 && lf === -1) {
|
|
14
|
+
break;
|
|
15
|
+
}
|
|
16
|
+
if (lf !== -1 && (cr === -1 || lf < cr)) {
|
|
17
|
+
lines.push(buffer.slice(i, lf));
|
|
18
|
+
i = lf + 1;
|
|
19
|
+
continue;
|
|
20
|
+
}
|
|
21
|
+
if (cr === buffer.length - 1) {
|
|
22
|
+
break;
|
|
23
|
+
}
|
|
24
|
+
lines.push(buffer.slice(i, cr));
|
|
25
|
+
i = buffer[cr + 1] === '\n' ? cr + 2 : cr + 1;
|
|
26
|
+
}
|
|
27
|
+
return { lines, rest: buffer.slice(i) };
|
|
28
|
+
}
|
|
29
|
+
export async function* readSseEvents(stream) {
|
|
30
|
+
const reader = stream.getReader();
|
|
31
|
+
const decoder = new TextDecoder();
|
|
32
|
+
let buffer = '';
|
|
33
|
+
let dataBuf = '';
|
|
34
|
+
let eventType = '';
|
|
35
|
+
let sawBom = false;
|
|
36
|
+
const dispatch = () => {
|
|
37
|
+
const type = eventType === '' ? 'message' : eventType;
|
|
38
|
+
let data = dataBuf;
|
|
39
|
+
if (data.endsWith('\n')) {
|
|
40
|
+
data = data.slice(0, -1);
|
|
41
|
+
}
|
|
42
|
+
dataBuf = '';
|
|
43
|
+
eventType = '';
|
|
44
|
+
if (type === 'close') {
|
|
45
|
+
return { event: 'close', data };
|
|
46
|
+
}
|
|
47
|
+
if (data === '') {
|
|
48
|
+
return null;
|
|
49
|
+
}
|
|
50
|
+
return { event: type, data };
|
|
51
|
+
};
|
|
52
|
+
const processLine = (line) => {
|
|
53
|
+
if (line === '') {
|
|
54
|
+
return dispatch();
|
|
55
|
+
}
|
|
56
|
+
if (line.startsWith(':')) {
|
|
57
|
+
return null;
|
|
58
|
+
}
|
|
59
|
+
const colon = line.indexOf(':');
|
|
60
|
+
const field = colon === -1 ? line : line.slice(0, colon);
|
|
61
|
+
let value = colon === -1 ? '' : line.slice(colon + 1);
|
|
62
|
+
if (value.startsWith(' ')) {
|
|
63
|
+
value = value.slice(1);
|
|
64
|
+
}
|
|
65
|
+
if (field === 'event') {
|
|
66
|
+
eventType = value;
|
|
67
|
+
}
|
|
68
|
+
else if (field === 'data') {
|
|
69
|
+
dataBuf += `${value}\n`;
|
|
70
|
+
}
|
|
71
|
+
return null;
|
|
72
|
+
};
|
|
73
|
+
try {
|
|
74
|
+
while (true) {
|
|
75
|
+
const { value, done } = await reader.read();
|
|
76
|
+
if (done) {
|
|
77
|
+
return;
|
|
78
|
+
}
|
|
79
|
+
let chunk = decoder.decode(value, { stream: true });
|
|
80
|
+
if (!sawBom) {
|
|
81
|
+
sawBom = true;
|
|
82
|
+
if (chunk.charCodeAt(0) === 0xfeff) {
|
|
83
|
+
chunk = chunk.slice(1);
|
|
84
|
+
}
|
|
85
|
+
}
|
|
86
|
+
buffer += chunk;
|
|
87
|
+
const split = splitLines(buffer);
|
|
88
|
+
buffer = split.rest;
|
|
89
|
+
for (const line of split.lines) {
|
|
90
|
+
const event = processLine(line);
|
|
91
|
+
if (event) {
|
|
92
|
+
yield event;
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
}
|
|
96
|
+
}
|
|
97
|
+
finally {
|
|
98
|
+
try {
|
|
99
|
+
await reader.cancel();
|
|
100
|
+
}
|
|
101
|
+
catch {
|
|
102
|
+
reader.releaseLock();
|
|
103
|
+
}
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
export function encodeSse(items, writeLine, onError, keepAliveMs) {
|
|
107
|
+
const encoder = new TextEncoder();
|
|
108
|
+
const iterator = items[Symbol.asyncIterator]();
|
|
109
|
+
let timer;
|
|
110
|
+
let closed = false;
|
|
111
|
+
let returned = false;
|
|
112
|
+
const comment = encoder.encode(COMMENT);
|
|
113
|
+
const stop = () => {
|
|
114
|
+
closed = true;
|
|
115
|
+
if (timer !== undefined) {
|
|
116
|
+
clearInterval(timer);
|
|
117
|
+
timer = undefined;
|
|
118
|
+
}
|
|
119
|
+
};
|
|
120
|
+
// The producer is still live (consumer cancel, or an item that could not
|
|
121
|
+
// be written): close it once.
|
|
122
|
+
const stopProducer = () => {
|
|
123
|
+
if (!returned) {
|
|
124
|
+
returned = true;
|
|
125
|
+
returnQuietly(iterator);
|
|
126
|
+
}
|
|
127
|
+
};
|
|
128
|
+
const fail = (controller, error) => {
|
|
129
|
+
controller.enqueue(encoder.encode(encodeEvent('error', onError(error))));
|
|
130
|
+
stop();
|
|
131
|
+
controller.close();
|
|
132
|
+
};
|
|
133
|
+
return new ReadableStream({
|
|
134
|
+
start(controller) {
|
|
135
|
+
controller.enqueue(comment);
|
|
136
|
+
if (keepAliveMs > 0) {
|
|
137
|
+
timer = setInterval(() => {
|
|
138
|
+
if (closed) {
|
|
139
|
+
return;
|
|
140
|
+
}
|
|
141
|
+
try {
|
|
142
|
+
controller.enqueue(comment);
|
|
143
|
+
}
|
|
144
|
+
catch {
|
|
145
|
+
stop();
|
|
146
|
+
}
|
|
147
|
+
}, keepAliveMs);
|
|
148
|
+
}
|
|
149
|
+
},
|
|
150
|
+
async pull(controller) {
|
|
151
|
+
let next;
|
|
152
|
+
try {
|
|
153
|
+
next = await iterator.next();
|
|
154
|
+
}
|
|
155
|
+
catch (error) {
|
|
156
|
+
fail(controller, error);
|
|
157
|
+
return;
|
|
158
|
+
}
|
|
159
|
+
if (next.done) {
|
|
160
|
+
controller.enqueue(encoder.encode(CLOSE_EVENT));
|
|
161
|
+
stop();
|
|
162
|
+
controller.close();
|
|
163
|
+
return;
|
|
164
|
+
}
|
|
165
|
+
try {
|
|
166
|
+
const line = await writeLine(next.value);
|
|
167
|
+
controller.enqueue(encoder.encode(encodeEvent('message', line)));
|
|
168
|
+
}
|
|
169
|
+
catch (error) {
|
|
170
|
+
stopProducer();
|
|
171
|
+
fail(controller, error);
|
|
172
|
+
}
|
|
173
|
+
},
|
|
174
|
+
cancel() {
|
|
175
|
+
stop();
|
|
176
|
+
stopProducer();
|
|
177
|
+
},
|
|
178
|
+
});
|
|
179
|
+
}
|
|
180
|
+
/**
|
|
181
|
+
* `iterator.return()` as cleanup: a sync throw or a rejection is dropped, not
|
|
182
|
+
* left as an unhandled rejection. The stream has already ended for the reader.
|
|
183
|
+
*/
|
|
184
|
+
function returnQuietly(iterator) {
|
|
185
|
+
try {
|
|
186
|
+
Promise.resolve(iterator.return?.()).catch(() => { });
|
|
187
|
+
}
|
|
188
|
+
catch {
|
|
189
|
+
// Cleanup only.
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
//# sourceMappingURL=sse.js.map
|
package/dist/sse.js.map
ADDED
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"sse.js","sourceRoot":"","sources":["../src/sse.ts"],"names":[],"mappings":"AAAA,MAAM,CAAC,MAAM,gBAAgB,GAAG,mBAAmB,CAAA;AAOnD,MAAM,OAAO,GAAG,OAAO,CAAA;AACvB,MAAM,WAAW,GAAG,kBAAkB,CAAA;AAEtC,SAAS,WAAW,CAAC,KAAa,EAAE,IAAY;IAC9C,OAAO,UAAU,KAAK,WAAW,IAAI,MAAM,CAAA;AAC7C,CAAC;AAED,SAAS,UAAU,CAAC,MAAc;IAChC,MAAM,KAAK,GAAa,EAAE,CAAA;IAC1B,IAAI,CAAC,GAAG,CAAC,CAAA;IACT,OAAO,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,CAAC;QACzB,MAAM,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;QAClC,MAAM,EAAE,GAAG,MAAM,CAAC,OAAO,CAAC,IAAI,EAAE,CAAC,CAAC,CAAA;QAClC,IAAI,EAAE,KAAK,CAAC,CAAC,IAAI,EAAE,KAAK,CAAC,CAAC,EAAE,CAAC;YAC3B,MAAK;QACP,CAAC;QACD,IAAI,EAAE,KAAK,CAAC,CAAC,IAAI,CAAC,EAAE,KAAK,CAAC,CAAC,IAAI,EAAE,GAAG,EAAE,CAAC,EAAE,CAAC;Y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|
{
|
|
2
2
|
"name": "@ts-pf/stream",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"description": "Opt-in StreamCodec and stream() for root AsyncIterable
|
|
3
|
+
"version": "1.0.0",
|
|
4
|
+
"description": "Opt-in StreamCodec (JSONL) and SseCodec (text/event-stream) with stream() for root AsyncIterable",
|
|
5
5
|
"keywords": [
|
|
6
6
|
"ts-pf",
|
|
7
7
|
"typescript",
|
|
@@ -12,7 +12,9 @@
|
|
|
12
12
|
"contract-first",
|
|
13
13
|
"streaming",
|
|
14
14
|
"jsonl",
|
|
15
|
-
"async-iterable"
|
|
15
|
+
"async-iterable",
|
|
16
|
+
"sse",
|
|
17
|
+
"server-sent-events"
|
|
16
18
|
],
|
|
17
19
|
"license": "MIT",
|
|
18
20
|
"engines": {
|
|
@@ -50,15 +52,15 @@
|
|
|
50
52
|
},
|
|
51
53
|
"dependencies": {
|
|
52
54
|
"@standard-schema/spec": "^1.0.0",
|
|
53
|
-
"@ts-pf/contract": "0.
|
|
54
|
-
"@ts-pf/http": "0.
|
|
55
|
-
"@ts-pf/protocol": "0.
|
|
55
|
+
"@ts-pf/contract": "^1.0.0",
|
|
56
|
+
"@ts-pf/http": "^1.0.0",
|
|
57
|
+
"@ts-pf/protocol": "^1.0.0"
|
|
56
58
|
},
|
|
57
59
|
"devDependencies": {
|
|
58
|
-
"@ts-pf/client": "0.
|
|
59
|
-
"@ts-pf/client-http": "0.
|
|
60
|
-
"@ts-pf/server": "0.
|
|
61
|
-
"@ts-pf/server-http": "0.
|
|
60
|
+
"@ts-pf/client": "^1.0.0",
|
|
61
|
+
"@ts-pf/client-http": "^1.0.0",
|
|
62
|
+
"@ts-pf/server": "^1.0.0",
|
|
63
|
+
"@ts-pf/server-http": "^1.0.0",
|
|
62
64
|
"zod": "^4.0.0"
|
|
63
65
|
}
|
|
64
66
|
}
|
|
@@ -1,11 +1,11 @@
|
|
|
1
1
|
---
|
|
2
2
|
name: ts-pf-stream
|
|
3
|
-
description: "Use when streaming root AsyncIterable over ts-pf with stream()
|
|
3
|
+
description: "Use when streaming root AsyncIterable over ts-pf with stream(), StreamCodec (JSONL), or SseCodec (text/event-stream output). Triggers: @ts-pf/stream, StreamCodec, SseCodec, SSE_CONTENT_TYPE, stream(), application/jsonl, server-sent events, @ts-pf/sse."
|
|
4
4
|
---
|
|
5
5
|
|
|
6
6
|
# @ts-pf/stream
|
|
7
7
|
|
|
8
|
-
Opt-in
|
|
8
|
+
Opt-in codecs for root `AsyncIterable` input and output. JSON calls stay JSON. `StreamCodec` frames streams as `application/jsonl`; `SseCodec` frames stream output as `text/event-stream`.
|
|
9
9
|
|
|
10
10
|
Install: `npm i @ts-pf/stream`
|
|
11
11
|
|
|
@@ -33,7 +33,7 @@ Root only. Same codec on handler and link. A failure line after the stream start
|
|
|
33
33
|
new FetchHandler(app, { codec, validation: { output: true } })
|
|
34
34
|
```
|
|
35
35
|
|
|
36
|
-
A `stream()` procedure on a non-streaming codec (the default `
|
|
36
|
+
A `stream()` procedure on a non-streaming codec (the default `JsonCodec`, `MultipartCodec`) is `400 BAD_REQUEST` `Stream procedure requires a streaming codec` before the handler runs.
|
|
37
37
|
|
|
38
38
|
Cleanup hangs off `signal`, not a generator's `finally`. A client cancel (or a message `cancel` before the handler resolved) calls the stream's `return()` once, but an async generator that was never pulled completes on `return()` without running its body, so its `finally` never runs, and a generator waiting on an `await` between yields does not see `return()` until its next `yield`. Over HTTP the handler's `signal` is `request.signal`, which fires on disconnect when your host aborts it:
|
|
39
39
|
|
|
@@ -45,18 +45,35 @@ chat: impl.chat.handler(async function* ({ signal }) {
|
|
|
45
45
|
})
|
|
46
46
|
```
|
|
47
47
|
|
|
48
|
+
### Server-sent events
|
|
49
|
+
|
|
50
|
+
`SseCodec` frames stream **output** as `text/event-stream`; input streams stay JSONL. Same `stream()` contracts, same rule: the same codec on handler and link.
|
|
51
|
+
|
|
52
|
+
```ts
|
|
53
|
+
import { SseCodec } from '@ts-pf/stream'
|
|
54
|
+
import { FetchHandler } from '@ts-pf/server-http'
|
|
55
|
+
import { FetchLink } from '@ts-pf/client-http'
|
|
56
|
+
|
|
57
|
+
const codec = new SseCodec() // optional { inner, keepAliveMs } — default 15_000; 0 disables pings
|
|
58
|
+
new FetchHandler(app, { codec })
|
|
59
|
+
new FetchLink({ url: '/rpc', codec })
|
|
60
|
+
```
|
|
61
|
+
|
|
62
|
+
An `event: error` after the stream started rejects the iterator with a `PFError` whose `status` is `undefined`; switch on `code`. `@ts-pf/sse` was merged into this package at 1.0: import `SseCodec` / `SSE_CONTENT_TYPE` from `@ts-pf/stream`.
|
|
63
|
+
|
|
48
64
|
## API
|
|
49
65
|
|
|
50
|
-
- `StreamCodec`
|
|
51
|
-
- `
|
|
66
|
+
- `StreamCodec`, `stream()`
|
|
67
|
+
- `SseCodec`, `SSE_CONTENT_TYPE`
|
|
52
68
|
|
|
53
69
|
## Pair with
|
|
54
70
|
|
|
55
71
|
- `ts-pf-server-http` / `ts-pf-client-http`
|
|
56
|
-
- SSE output framing: `ts-pf-sse` (`SseCodec`; this package still owns `stream()`)
|
|
57
72
|
|
|
58
73
|
## Don't
|
|
59
74
|
|
|
60
75
|
- Nested streams or File/Blob in items (`BAD_REQUEST`).
|
|
61
76
|
- Rely on a generator's `finally` for cleanup (skipped if the stream is cancelled before the first pull, delayed while the generator waits on an `await`); close resources from `signal`.
|
|
62
|
-
-
|
|
77
|
+
- Install `@ts-pf/sse` (merged here at 1.0; the old package is not updated).
|
|
78
|
+
- EventSource clients, Last-Event-ID, EventPublisher.
|
|
79
|
+
- Fold SSE into `@ts-pf/server-http`.
|