concatenate.ts
4.23 KB
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
/*
Copyright 2018 Google LLC
Use of this source code is governed by an MIT-style
license that can be found in the LICENSE file or at
https://opensource.org/licenses/MIT.
*/
import {assert} from 'workbox-core/_private/assert.js';
import {Deferred} from 'workbox-core/_private/Deferred.js';
import {logger} from 'workbox-core/_private/logger.js';
import {StreamSource} from './_types.js';
import {WorkboxError} from 'workbox-core/_private/WorkboxError.js';
import './_version.js';
/**
* Takes either a Response, a ReadableStream, or a
* [BodyInit](https://fetch.spec.whatwg.org/#bodyinit) and returns the
* ReadableStreamReader object associated with it.
*
* @param {workbox-streams.StreamSource} source
* @return {ReadableStreamReader}
* @private
*/
function _getReaderFromSource(
source: StreamSource,
): ReadableStreamReader<unknown> {
if (source instanceof Response) {
// See https://github.com/GoogleChrome/workbox/issues/2998
if (source.body) {
return source.body.getReader();
}
throw new WorkboxError('opaque-streams-source', {type: source.type});
}
if (source instanceof ReadableStream) {
return source.getReader();
}
return new Response(source as BodyInit).body!.getReader();
}
/**
* Takes multiple source Promises, each of which could resolve to a Response, a
* ReadableStream, or a [BodyInit](https://fetch.spec.whatwg.org/#bodyinit).
*
* Returns an object exposing a ReadableStream with each individual stream's
* data returned in sequence, along with a Promise which signals when the
* stream is finished (useful for passing to a FetchEvent's waitUntil()).
*
* @param {Array<Promise<workbox-streams.StreamSource>>} sourcePromises
* @return {Object<{done: Promise, stream: ReadableStream}>}
*
* @memberof workbox-streams
*/
function concatenate(sourcePromises: Promise<StreamSource>[]): {
done: Promise<void>;
stream: ReadableStream;
} {
if (process.env.NODE_ENV !== 'production') {
assert!.isArray(sourcePromises, {
moduleName: 'workbox-streams',
funcName: 'concatenate',
paramName: 'sourcePromises',
});
}
const readerPromises = sourcePromises.map((sourcePromise) => {
return Promise.resolve(sourcePromise).then((source) => {
return _getReaderFromSource(source);
});
});
const streamDeferred: Deferred<void> = new Deferred();
let i = 0;
const logMessages: any[] = [];
const stream = new ReadableStream({
pull(controller: ReadableStreamDefaultController<any>) {
return readerPromises[i]
.then((reader) => reader.read())
.then((result) => {
if (result.done) {
if (process.env.NODE_ENV !== 'production') {
logMessages.push([
'Reached the end of source:',
sourcePromises[i],
]);
}
i++;
if (i >= readerPromises.length) {
// Log all the messages in the group at once in a single group.
if (process.env.NODE_ENV !== 'production') {
logger.groupCollapsed(
`Concatenating ${readerPromises.length} sources.`,
);
for (const message of logMessages) {
if (Array.isArray(message)) {
logger.log(...message);
} else {
logger.log(message);
}
}
logger.log('Finished reading all sources.');
logger.groupEnd();
}
controller.close();
streamDeferred.resolve();
return;
}
// The `pull` method is defined because we're inside it.
return this.pull!(controller);
} else {
controller.enqueue(result.value);
}
})
.catch((error) => {
if (process.env.NODE_ENV !== 'production') {
logger.error('An error occurred:', error);
}
streamDeferred.reject(error);
throw error;
});
},
cancel() {
if (process.env.NODE_ENV !== 'production') {
logger.warn('The ReadableStream was cancelled.');
}
streamDeferred.resolve();
},
});
return {done: streamDeferred.promise, stream};
}
export {concatenate};