-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
196 lines (179 loc) · 5.55 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
const { Stream, Duplex } = require("stream");
/**
* Options
* @typedef {('off'|'basic'|'verbose')} DebugOptions
*/
/**
* Logging options
* @typedef {{ debug: DebugOptions, stringToBufferThreshold: number }} Options
*/
/**
* @type {Options}
*/
const defaultOptions = {
debug: "off",
stringToBufferThreshold: Infinity // "stringToBufferThreshold": min string.length before converting it into a Buffer
};
/**
* Helper function for logging
*
* @param {DebugOptions} debug - logging configuration
* @param {string} mainItem - title
* @param {any} verboseItems - rest of the details
*/
const log = (debug, mainItem, ...verboseItems) =>
debug !== "off" &&
console.log(
"[marinate] ",
mainItem,
...(debug === "verbose" ? verboseItems : [])
);
/**
* Types for parts
* @typedef {Stream|string|Promise|function} TypeOfSupportedPartTypes
*/
/**
* Support types for parts
* @typedef {('stream'|'string'|'promise'|'function')} SupportedPartTypes
*/
/**
* A helper function to get type of object passed to it
* @param {any} obj
* @returns {SupportedPartTypes} Returns type of the object passed
*/
const typeOf = obj => {
if (obj instanceof Stream) {
return "stream";
}
if (typeof obj === "string") {
return "string";
}
if (obj instanceof Promise) {
return "promise";
}
if (typeof obj === "function") {
return "function";
}
};
/**
* Promisified version of write
* @param {Stream} stream stream to write into
* @returns {function} Function that returns promise
*/
const write = stream => value =>
new Promise(resolve => stream.write(value, resolve) === true && resolve());
/**
* Returns a stream created out of buffered passsed to it
* @param {Buffer} buffer - buffer to push into stream
* @returns {Stream}
*/
const bufferToReadableStream = buffer => {
const stream = new Duplex();
stream.push(buffer);
stream.push(null);
return stream;
};
/**
* Returns a readable stream that streams the string passed to it
* @param {string} string
* @returns {ReadableStream} Readable stream created out of the passed string
*/
const stringToReadableStream = string =>
bufferToReadableStream(Buffer.from(string));
/**
* Returns a promise that resolves after streamToPipe has been successfully ended streaming into stteamToPipeInto
* @param {ReadbleStream} streamToPipe
* @param {WritableStream} streamToPipeInto
* @param {Options} options
*/
const resolveAfterPipeAndEnd = (streamToPipe, streamToPipeInto, options) =>
new Promise((resolve, reject) => {
streamToPipe.pipe(
streamToPipeInto,
options
);
streamToPipe.on("end", resolve);
});
/**
* A function returning promise after streaming given `part` into `streamToWriteInto`.
* @param {object} data
* @param {TypeOfSupportedPartTypes} data.part
* @param {WritableStream} data.streamToWriteInto
* @param {Options} data.options
*/
const handlePart = async ({ part, streamToWriteInto, options }) => {
const { debug, stringToBufferThreshold } = options;
const writeToStream = write(streamToWriteInto);
switch (typeOf(part)) {
case "function": {
await handlePart({ part: part(), streamToWriteInto, options });
break;
}
case "promise": {
await handlePart({ part: await part, streamToWriteInto, options });
break;
}
case "string": {
if (part.length >= stringToBufferThreshold) {
log(debug, `Rendering string part as stream`, part);
await resolveAfterPipeAndEnd(
stringToReadableStream(part),
streamToWriteInto,
{ end: false }
);
log(debug, `Rendered string part as stream`);
} else if (part !== "") {
log(debug, "Rendering string part", part);
await writeToStream(part);
}
break;
}
case "stream": {
const time = Date.now();
log(debug, `Rendering stream part [${time}]`);
await resolveAfterPipeAndEnd(part, streamToWriteInto, { end: false });
log(debug, `Rendered stream part [${time}] in ${Date.now() - time}ms`);
break;
}
default: {
console.log({ part });
throw new Error(`Unknown type [${typeOf(part)}] of above part`);
}
}
};
module.exports = (staticParts, ...dynamicParts) => async (
/** @type {WritableStream} */
streamToWriteInto,
/** @type {Options} */
options = defaultOptions
) => {
const { debug, stringToBufferThreshold } = options;
for (let [index, staticPart] of staticParts.entries()) {
// for..of will iterate only when internal `await`s are resolved.
await handlePart({
part: staticPart, // take this string and
streamToWriteInto, // directly write into the stream or pipe it
options // based on the options
});
if (index === staticParts.length - 1) {
// if staticPart is last element, we just end the stream
log(debug, "Finished Marinating");
streamToWriteInto.end();
} else {
// for intermediate staticParts, we need to plug in the dynamic parts before streaming the next staticPart
const dynamicPart = dynamicParts[index];
const typeOfDynamicPart = typeOf(dynamicPart);
if (["string", "function"].includes(typeOfDynamicPart)) {
await handlePart({
part: dynamicPart, // take this dynamic part (string | function returning (string | promise | stream))
streamToWriteInto, // write it into stream
options // based on options
});
} else {
throw new Error(
`\${dynamicParts} can only be of type (string | function returning (string | promise | stream)). Found type ${typeOfDynamicPart}`
);
}
}
}
};