-
-
Notifications
You must be signed in to change notification settings - Fork 4
/
index.js
214 lines (167 loc) · 4.2 KB
/
index.js
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
209
210
211
212
213
214
import Worker from 'web-worker';
import {pEvent} from 'p-event';
const isNode = Boolean(globalThis.process?.versions?.node);
const makeBlob = content => new globalThis.Blob([content], {type: 'text/javascript'});
// TODO: Remove this when https://github.com/developit/web-worker/issues/30 is fixed.
const makeDataUrl = content => {
const data = globalThis.Buffer.from(content).toString('base64');
return `data:text/javascript;base64,${data}`;
};
function createWorker(content) {
let url;
let worker;
const cleanup = () => {
if (url) {
URL.revokeObjectURL(url);
}
worker?.terminate();
};
if (isNode) {
worker = new Worker(makeDataUrl(content), {type: 'module'});
} else {
url = URL.createObjectURL(makeBlob(content));
worker = new Worker(url, {type: 'module'});
}
return {
worker,
cleanup,
};
}
const makeContent = function_ =>
`
globalThis.onmessage = async ({data: arguments_}) => {
try {
const output = await (${function_.toString()})(...arguments_);
globalThis.postMessage({output});
} catch (error) {
globalThis.postMessage({error});
}
};
`;
export default function makeAsynchronous(function_) {
const content = makeContent(function_);
const setup = () => createWorker(content);
async function run({worker, arguments_}) {
const promise = pEvent(worker, 'message', {
rejectionEvents: ['error', 'messageerror'],
});
worker.postMessage(arguments_);
const {data: {output, error}} = await promise;
if (error) {
throw error;
}
return output;
}
const fn = async (...arguments_) => {
const {worker, cleanup} = setup();
try {
return await run({arguments_, worker});
} finally {
cleanup();
}
};
fn.withSignal = signal => async (...arguments_) => {
signal.throwIfAborted();
const {worker, cleanup} = setup();
const abortPromise = pEvent(signal, [], {
rejectionEvents: ['abort'],
});
try {
return await Promise.race([
run({arguments_, worker}),
abortPromise,
]);
} catch (error) {
signal.throwIfAborted();
throw error;
} finally {
abortPromise.cancel();
cleanup();
}
};
return fn;
}
const makeIterableContent = function_ =>
`
const nothing = Symbol('nothing');
let iterator = nothing;
globalThis.onmessage = async ({data: arguments_}) => {
try {
if (iterator === nothing) {
iterator = await (${function_.toString()})(...arguments_);
}
const output = await iterator.next();
globalThis.postMessage({output});
} catch (error) {
globalThis.postMessage({error});
}
};
`;
export function makeAsynchronousIterable(function_) {
const content = makeIterableContent(function_);
const setup = () => createWorker(content);
const fn = (...arguments_) => ({
async * [Symbol.asyncIterator]() {
const {worker, cleanup} = setup();
try {
let isFirstMessage = true;
while (true) {
const promise = pEvent(worker, 'message', {
rejectionEvents: ['error', 'messageerror'],
});
worker.postMessage(isFirstMessage ? arguments_ : undefined);
isFirstMessage = false;
const {data: {output, error}} = await promise; // eslint-disable-line no-await-in-loop
if (error) {
throw error;
}
const {value, done} = output;
if (done) {
break;
}
yield value;
}
} finally {
cleanup();
}
},
});
fn.withSignal = signal => (...arguments_) => ({
async * [Symbol.asyncIterator]() {
signal.throwIfAborted();
const {worker, cleanup} = setup();
const abortPromise = pEvent(signal, [], {
rejectionEvents: ['abort'],
});
try {
let isFirstMessage = true;
while (true) {
const promise = Promise.race([
pEvent(worker, 'message', {
rejectionEvents: ['error', 'messageerror'],
}),
abortPromise,
]);
worker.postMessage(isFirstMessage ? arguments_ : undefined);
isFirstMessage = false;
const {data: {output, error}} = await promise; // eslint-disable-line no-await-in-loop
if (error) {
throw error;
}
const {value, done} = output;
if (done) {
break;
}
yield value;
}
} catch (error) {
signal.throwIfAborted();
throw error;
} finally {
abortPromise.cancel();
cleanup();
}
},
});
return fn;
}