-
Notifications
You must be signed in to change notification settings - Fork 2
/
index.ts
208 lines (172 loc) · 6.16 KB
/
index.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
import { nanoid } from 'nanoid'
type MaybePromise<T> = T | Promise<T>
type Streamable =
| Iterable<unknown>
| AsyncIterable<unknown>
| ReadableStream
| Response
| null
interface StreamOption {
/**
* A string identifying the type of event described.
*
* If specified, an event will be dispatched on the browser
* to the listener for the specified event name;
*
* The website source code should use addEventListener()
* to listen for named events.
*
* The onmessage handler is called if no event name
* is specified for a message.
*/
event?: string
/**
* The reconnection time in milliseconds.
*
* If the connection to the server is lost,
* the browser will wait for the specified time before
* attempting to reconnect.
*/
retry?: number
}
const encoder = new TextEncoder()
export const wait = (ms: number) =>
new Promise<void>((resolve) => setTimeout(resolve, ms))
const isIterable = (
value: unknown
): value is Iterable<any> | AsyncIterable<any> => {
if (!value) return false
return (
// @ts-ignore
typeof value[Symbol.asyncIterator] === 'function' ||
// @ts-ignore
typeof value[Symbol.iterator] === 'function'
)
}
export class Stream<Data extends string | number | boolean | object> {
private $passthrough = 'value'
private controller: ReadableStreamController<any> | undefined
stream: ReadableStream<Data>
private _retry?: number
private _event?: string
private label: string = ''
private labelUint8Array = new Uint8Array()
private composeLabel() {
this.label = ''
if (this._event) this.label += `event: ${this._event}\n`
if (this._retry) this.label += `retry: ${this._retry}\n`
if (this.label) this.labelUint8Array = encoder.encode(this.label)
}
get retry() {
return this._retry
}
set retry(retry: number | undefined) {
this._retry = retry
this.composeLabel()
}
get event() {
return this._event
}
set event(event: string | undefined) {
this._event = event
this.composeLabel()
}
static concatUintArray(a: Uint8Array, b: Uint8Array) {
const arr = new Uint8Array(a.length + b.length)
arr.set(a, 0)
arr.set(b, a.length)
return arr
}
constructor(
callback?: ((stream: Stream<Data>) => void) | MaybePromise<Streamable>,
{ retry, event }: StreamOption = {}
) {
if (retry) this._retry = retry
if (event) this._event = event
if (retry || event) this.composeLabel()
switch (typeof callback) {
case 'function':
case 'undefined':
this.stream = new ReadableStream({
start: (controller) => {
this.controller = controller
;(callback as Function)?.(this)
},
cancel: (controller: ReadableStreamDefaultController) => {
controller.close()
}
})
break
default:
this.stream = new ReadableStream({
start: async (controller) => {
this.controller = controller
try {
for await (const chunk of await (callback as
| Iterable<string>
| AsyncIterable<string>))
this.send(chunk)
controller.close()
} catch {
if (callback instanceof Promise)
callback = await callback
if (callback === null) return controller.close()
const isResponse = callback instanceof Response
if (
isResponse ||
callback instanceof ReadableStream
) {
const reader = isResponse
? (callback as Response).body?.getReader()
: (callback as ReadableStream).getReader()
if (!reader) return controller.close()
while (true) {
const { done, value } = await reader.read()
this.send(value)
if (done) {
controller.close()
break
}
}
}
}
}
})
}
}
send(data: string | number | boolean | object | Uint8Array) {
if (!this.controller || data === '' || data === undefined) return
if (data instanceof Uint8Array) {
this.controller.enqueue(
this.label
? Stream.concatUintArray(this.labelUint8Array, data)
: data
)
} else
this.controller.enqueue(
encoder.encode(
typeof data === 'string' && data.includes('id:')
? data +
(this._event && !data.includes('event:')
? `\nevent: ${this._event}`
: '') +
(this._retry && !data.includes('retry:')
? `\retry: ${this.retry}`
: '')
: `id: ${nanoid()}\n${this.label}data: ${
typeof data === 'object'
? JSON.stringify(data)
: data
}\n\n`
)
)
}
close() {
this.controller?.close()
}
wait = wait
get value() {
return this.stream
}
}
export default Stream