2 Commits

Author SHA1 Message Date
Lewis Diamond
e168e8b9da remove useless test things 2019-12-06 16:48:37 -05:00
Lewis Diamond
7c5fe5c9f7 Remove our specific stuff from package.json 2019-12-06 16:46:48 -05:00
52 changed files with 414 additions and 720 deletions

View File

@@ -1,13 +1,15 @@
# Strom
# Mhysa
**Dependency-free stream utils for Node.js**
<sub>Released under the [MIT](https://git.lewis.id/strom/blob/master/LICENSE) license.</sub>
<sub>Released under the [MIT](https://github.com/Wenzil/Mhysa/blob/master/LICENSE) license.</sub>
```sh
yarn add strom // Name TBD
yarn add mhysa
```
<sub>Tested with Node.js versions 8+</sub>
## fromArray(array)
Convert an array into a `Readable` stream of its elements
@@ -16,7 +18,7 @@ Convert an array into a `Readable` stream of its elements
| `array` | `T[]` | Array of elements to stream |
```js
strom.fromArray(["a", "b"])
Mhysa.fromArray(["a", "b"])
.pipe(process.stdout);
// ab is printed out
```
@@ -33,8 +35,8 @@ Return a `ReadWrite` stream that maps streamed chunks
| `options.writableObjectMode` | `boolean` | Whether this stream should behave as a writable stream of objects |
```js
strom.fromArray(["a", "b"])
.pipe(strom.map(s => s.toUpperCase()))
Mhysa.fromArray(["a", "b"])
.pipe(Mhysa.map(s => s.toUpperCase()))
.pipe(process.stdout);
// AB is printed out
```
@@ -51,8 +53,8 @@ Return a `ReadWrite` stream that flat maps streamed chunks
| `options.writableObjectMode` | `boolean` | Whether this stream should behave as a writable stream of objects |
```js
strom.fromArray(["a", "AA"])
.pipe(strom.flatMap(s => new Array(s.length).fill(s)))
Mhysa.fromArray(["a", "AA"])
.pipe(Mhysa.flatMap(s => new Array(s.length).fill(s)))
.pipe(process.stdout);
// aAAAA is printed out
```
@@ -68,8 +70,8 @@ Return a `ReadWrite` stream that filters out streamed chunks for which the predi
| `options.objectMode` | `boolean` | `boolean` | Whether this stream should behave as a stream of objects |
```js
strom.fromArray(["a", "b", "c"])
.pipe(strom.filter(s => s !== "b"))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.filter(s => s !== "b"))
.pipe(process.stdout);
// ac is printed out
```
@@ -88,9 +90,9 @@ value
| `options.writableObjectMode` | `boolean` | Whether this stream should behave as a writable stream of objects |
```js
strom.fromArray(["a", "b", "cc"])
.pipe(strom.reduce((acc, s) => ({ ...acc, [s]: s.length }), {}))
.pipe(strom.stringify())
Mhysa.fromArray(["a", "b", "cc"])
.pipe(Mhysa.reduce((acc, s) => ({ ...acc, [s]: s.length }), {}))
.pipe(Mhysa.stringify())
.pipe(process.stdout);
// {"a":1,"b":1","c":2} is printed out
```
@@ -106,9 +108,9 @@ Return a `ReadWrite` stream that splits streamed chunks using the given separato
| `options.encoding` | `string` | Character encoding to use for decoding chunks. Defaults to utf8
```js
strom.fromArray(["a,b", "c,d"])
.pipe(strom.split(","))
.pipe(strom.join("|"))
Mhysa.fromArray(["a,b", "c,d"])
.pipe(Mhysa.split(","))
.pipe(Mhysa.join("|"))
.pipe(process.stdout);
// a|bc|d is printed out
```
@@ -124,8 +126,8 @@ Return a `ReadWrite` stream that joins streamed chunks using the given separator
| `options.encoding` | `string` | Character encoding to use for decoding chunks. Defaults to utf8
```js
strom.fromArray(["a", "b", "c"])
.pipe(strom.join(","))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.join(","))
.pipe(process.stdout);
// a,b,c is printed out
```
@@ -143,8 +145,8 @@ the streamed chunks with the specified replacement string
| `options.encoding` | `string` | Character encoding to use for decoding chunks. Defaults to utf8
```js
strom.fromArray(["a1", "b22", "c333"])
.pipe(strom.replace(/b\d+/, "B"))
Mhysa.fromArray(["a1", "b22", "c333"])
.pipe(Mhysa.replace(/b\d+/, "B"))
.pipe(process.stdout);
// a1Bc333 is printed out
```
@@ -154,8 +156,8 @@ strom.fromArray(["a1", "b22", "c333"])
Return a `ReadWrite` stream that parses the streamed chunks as JSON
```js
strom.fromArray(['{ "a": "b" }'])
.pipe(strom.parse())
Mhysa.fromArray(['{ "a": "b" }'])
.pipe(Mhysa.parse())
.once("data", object => console.log(object));
// { a: 'b' } is printed out
```
@@ -165,8 +167,8 @@ strom.fromArray(['{ "a": "b" }'])
Return a `ReadWrite` stream that stringifies the streamed chunks to JSON
```js
strom.fromArray([{ a: "b" }])
.pipe(strom.stringify())
Mhysa.fromArray([{ a: "b" }])
.pipe(Mhysa.stringify())
.pipe(process.stdout);
// {"a":"b"} is printed out
```
@@ -181,8 +183,8 @@ Return a `ReadWrite` stream that collects streamed chunks into an array or buffe
| `options.objectMode` | `boolean` | Whether this stream should behave as a stream of objects |
```js
strom.fromArray(["a", "b", "c"])
.pipe(strom.collect({ objectMode: true }))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.collect({ objectMode: true }))
.once("data", object => console.log(object));
// [ 'a', 'b', 'c' ] is printed out
```
@@ -198,7 +200,7 @@ Return a `Readable` stream of readable streams concatenated together
```js
const source1 = new Readable();
const source2 = new Readable();
strom.concat(source1, source2).pipe(process.stdout)
Mhysa.concat(source1, source2).pipe(process.stdout)
source1.push("a1 ");
source2.push("c3 ");
source1.push("b2 ");
@@ -219,7 +221,7 @@ Return a `Readable` stream of readable streams merged together in chunk arrival
```js
const source1 = new Readable({ read() {} });
const source2 = new Readable({ read() {} });
strom.merge(source1, source2).pipe(process.stdout);
Mhysa.merge(source1, source2).pipe(process.stdout);
source1.push("a1 ");
setTimeout(() => source2.push("c3 "), 10);
setTimeout(() => source1.push("b2 "), 20);
@@ -241,8 +243,8 @@ cause the given readable stream to yield chunks
```js
const catProcess = require("child_process").exec("grep -o ab");
strom.fromArray(["a", "b", "c"])
.pipe(strom.duplex(catProcess.stdin, catProcess.stdout))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.duplex(catProcess.stdin, catProcess.stdout))
.pipe(process.stdout);
// ab is printed out
```
@@ -257,8 +259,8 @@ Return a `Duplex` stream from a child process' stdin and stdout
```js
const catProcess = require("child_process").exec("grep -o ab");
strom.fromArray(["a", "b", "c"])
.pipe(strom.child(catProcess))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.child(catProcess))
.pipe(process.stdout);
// ab is printed out
```
@@ -274,8 +276,8 @@ ended
```js
let f = async () => {
const source = strom.fromArray(["a", "b", "c"]);
console.log(await strom.last(source));
const source = Mhysa.fromArray(["a", "b", "c"]);
console.log(await Mhysa.last(source));
};
f();
// c is printed out

View File

@@ -1,16 +1,17 @@
{
"name": "strom",
"version": "2.0.0",
"description": "Streams utils for Node.js",
"name": "mhysa",
"version": "2.0.0-alpha.1",
"description": "Streams and event emitter utils for Node.js",
"keywords": [
"promise",
"stream",
"event emitter",
"utils"
],
"contributors": [
{
"author": {
"name": "Wenzil"
},
"contributors": [
{
"name": "jerry",
"email": "jerry@jogogo.co"
@@ -27,20 +28,19 @@
"dist"
],
"repository": {
"url": "git@git.lewis.id:ldiamond/strom.git",
"url": "git@github.com:Wenzil/Mhysa.git",
"type": "git"
},
"scripts": {
"test": "ava",
"lint": "tslint -p tsconfig.json",
"validate:tslint": "tslint-config-prettier-check ./tslint.json",
"prepublishOnly": "yarn lint && yarn test && yarn tsc -d",
"prepare": "tsc"
"prepublishOnly": "yarn lint && yarn test && yarn tsc -d"
},
"dependencies": {},
"devDependencies": {
"@types/chai": "^4.1.7",
"@types/node": "^12.12.15",
"@types/node": "^12.7.2",
"@types/sinon": "^7.0.13",
"ava": "^2.4.0",
"chai": "^4.2.0",
@@ -55,8 +55,7 @@
},
"ava": {
"files": [
"tests/*.spec.ts",
"tests/utils/*.spec.ts"
"tests/*.spec.ts"
],
"sources": [
"src/**/*.ts"

View File

@@ -1,8 +1,8 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(["a", "b", "c"])
.pipe(strom.map(s => Promise.resolve(s + s)))
.pipe(strom.flatMap(s => Promise.resolve([s, s.toUpperCase()])))
.pipe(strom.filter(s => Promise.resolve(s !== "bb")))
.pipe(strom.join(","))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.map(s => Promise.resolve(s + s)))
.pipe(Mhysa.flatMap(s => Promise.resolve([s, s.toUpperCase()])))
.pipe(Mhysa.filter(s => Promise.resolve(s !== "bb")))
.pipe(Mhysa.join(","))
.pipe(process.stdout);

View File

@@ -1,6 +1,6 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
const catProcess = require("child_process").exec("grep -o ab");
strom.fromArray(["a", "b", "c"])
.pipe(strom.child(catProcess))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.child(catProcess))
.pipe(process.stdout);

View File

@@ -1,5 +1,5 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(["a", "b", "c"])
.pipe(strom.collect({ objectMode: true }))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.collect({ objectMode: true }))
.on("data", object => console.log(object));

View File

@@ -1,9 +1,9 @@
const { Readable } = require("stream");
const strom = require("strom").strom();
const Mhysa = require("mhysa");
const source1 = new Readable();
const source2 = new Readable();
strom.concat(source1, source2).pipe(process.stdout);
Mhysa.concat(source1, source2).pipe(process.stdout);
source1.push("a1 ");
source2.push("c3 ");
source1.push("b2 ");

View File

@@ -1,6 +1,6 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
const catProcess = require("child_process").exec("grep -o ab");
strom.fromArray(["a", "b", "c"])
.pipe(strom.duplex(catProcess.stdin, catProcess.stdout))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.duplex(catProcess.stdin, catProcess.stdout))
.pipe(process.stdout);

View File

@@ -1,6 +1,6 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(["a", "b", "c"])
.pipe(strom.filter(s => s !== "b"))
.pipe(strom.join(","))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.filter(s => s !== "b"))
.pipe(Mhysa.join(","))
.pipe(process.stdout);

View File

@@ -1,6 +1,6 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(["a", "AA"])
.pipe(strom.flatMap(s => new Array(s.length).fill(s)))
.pipe(strom.join(","))
Mhysa.fromArray(["a", "AA"])
.pipe(Mhysa.flatMap(s => new Array(s.length).fill(s)))
.pipe(Mhysa.join(","))
.pipe(process.stdout);

View File

@@ -1,5 +1,5 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(["a", "b", "c"])
.pipe(strom.join(","))
Mhysa.fromArray(["a", "b", "c"])
.pipe(Mhysa.join(","))
.pipe(process.stdout);

View File

@@ -1,7 +1,7 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
let f = async () => {
const source = strom.fromArray(["a", "b", "c"]);
console.log(await strom.last(source));
const source = Mhysa.fromArray(["a", "b", "c"]);
console.log(await Mhysa.last(source));
};
f();

View File

@@ -1,6 +1,6 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(["a", "b"])
.pipe(strom.map(s => s.toUpperCase()))
.pipe(strom.join(","))
Mhysa.fromArray(["a", "b"])
.pipe(Mhysa.map(s => s.toUpperCase()))
.pipe(Mhysa.join(","))
.pipe(process.stdout);

View File

@@ -1,9 +1,9 @@
const { Readable } = require("stream");
const strom = require("strom").strom();
const Mhysa = require("mhysa");
const source1 = new Readable({ read() {} });
const source2 = new Readable({ read() {} });
strom.merge(source1, source2).pipe(process.stdout);
Mhysa.merge(source1, source2).pipe(process.stdout);
source1.push("a1 ");
setTimeout(() => source2.push("c3 "), 10);
setTimeout(() => source1.push("b2 "), 20);

View File

@@ -1,5 +1,5 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(['{ "a": "b" }'])
.pipe(strom.parse())
Mhysa.fromArray(['{ "a": "b" }'])
.pipe(Mhysa.parse())
.on("data", object => console.log(object));

View File

@@ -1,6 +1,6 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(["a", "b", "cc"])
.pipe(strom.reduce((acc, s) => ({ ...acc, [s]: s.length }), {}))
.pipe(strom.stringify())
Mhysa.fromArray(["a", "b", "cc"])
.pipe(Mhysa.reduce((acc, s) => ({ ...acc, [s]: s.length }), {}))
.pipe(Mhysa.stringify())
.pipe(process.stdout);

View File

@@ -1,5 +1,5 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(["a1", "b22", "c333"])
.pipe(strom.replace(/b\d+/, "B"))
Mhysa.fromArray(["a1", "b22", "c333"])
.pipe(Mhysa.replace(/b\d+/, "B"))
.pipe(process.stdout);

View File

@@ -1,6 +1,6 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray(["a,b", "c,d"])
.pipe(strom.split(","))
.pipe(strom.join("|"))
Mhysa.fromArray(["a,b", "c,d"])
.pipe(Mhysa.split(","))
.pipe(Mhysa.join("|"))
.pipe(process.stdout);

View File

@@ -1,5 +1,5 @@
const strom = require("strom").strom();
const Mhysa = require("mhysa");
strom.fromArray([{ a: "b" }])
.pipe(strom.stringify())
Mhysa.fromArray([{ a: "b" }])
.pipe(Mhysa.stringify())
.pipe(process.stdout);

View File

@@ -12,9 +12,7 @@ export function batch(
clearTimeout(timer);
}
timer = null;
if (buffer.length > 0) {
self.push(buffer);
}
buffer = [];
};
return new Transform({

View File

@@ -1,5 +1,4 @@
import { AllStreams, isReadable } from "../helpers";
import { PassThrough, pipeline, TransformOptions, Transform } from "stream";
import { pipeline, TransformOptions, Transform } from "stream";
export function compose(
streams: Array<
@@ -22,6 +21,18 @@ enum EventSubscription {
Self,
}
type AllStreams =
| NodeJS.ReadableStream
| NodeJS.ReadWriteStream
| NodeJS.WritableStream;
function isReadable(stream: AllStreams): stream is NodeJS.WritableStream {
return (
(stream as NodeJS.ReadableStream).pipe !== undefined &&
(stream as any).readable === true
);
}
export class Compose extends Transform {
private first: AllStreams;
private last: AllStreams;
@@ -34,11 +45,11 @@ export class Compose extends Transform {
options?: TransformOptions,
) {
super(options);
this.first = new PassThrough(options);
this.first = streams[0];
this.last = streams[streams.length - 1];
this.streams = streams;
pipeline(
[this.first, ...streams],
streams,
errorCallback ||
((error: any) => {
if (error) {

View File

@@ -1,131 +1,99 @@
import { DuplexOptions, Duplex, Transform } from "stream";
import { WritableOptions, Writable } from "stream";
import { isReadable } from "../helpers";
enum EventSubscription {
Last = 0,
First,
All,
Self,
Unhandled,
}
const eventsTarget = {
close: EventSubscription.Self,
data: EventSubscription.All,
drain: EventSubscription.Self,
end: EventSubscription.Self,
error: EventSubscription.Self,
finish: EventSubscription.Self,
pause: EventSubscription.Self,
pipe: EventSubscription.Self,
readable: EventSubscription.Self,
resume: EventSubscription.Self,
unpipe: EventSubscription.Self,
};
type DemuxStreams = NodeJS.WritableStream | NodeJS.ReadWriteStream;
export interface DemuxOptions extends DuplexOptions {
remultiplex?: boolean;
}
export function demux(
pipelineConstructor: (
destKey?: string,
chunk?: any,
) => DemuxStreams | DemuxStreams[],
construct: (destKey?: string) => DemuxStreams,
demuxBy: string | ((chunk: any) => string),
options?: DemuxOptions,
): Duplex {
return new Demux(pipelineConstructor, demuxBy, options);
options?: WritableOptions,
): Writable {
return new Demux(construct, demuxBy, options);
}
class Demux extends Duplex {
// @TODO handle pipe event ie) Multiplex
class Demux extends Writable {
private streamsByKey: {
[key: string]: DemuxStreams[];
[key: string]: DemuxStreams;
};
private demuxer: (chunk: any) => string;
private pipelineConstructor: (
destKey?: string,
chunk?: any,
) => DemuxStreams[];
private remultiplex: boolean;
private transform: Transform;
private construct: (destKey?: string) => DemuxStreams;
constructor(
pipelineConstructor: (
destKey?: string,
chunk?: any,
) => DemuxStreams | DemuxStreams[],
construct: (destKey?: string) => DemuxStreams,
demuxBy: string | ((chunk: any) => string),
options: DemuxOptions = {},
options: WritableOptions = {},
) {
super(options);
this.demuxer =
typeof demuxBy === "string" ? chunk => chunk[demuxBy] : demuxBy;
this.pipelineConstructor = (destKey: string, chunk?: any) => {
const pipeline = pipelineConstructor(destKey, chunk);
return Array.isArray(pipeline) ? pipeline : [pipeline];
};
this.remultiplex =
options.remultiplex === undefined ? true : options.remultiplex;
this.construct = construct;
this.streamsByKey = {};
this.transform = new Transform({
...options,
transform: (d, _, cb) => {
this.push(d);
cb(null);
},
});
this.on("unpipe", () => this._flush());
}
// tslint:disable-next-line
public _read(size: number) {}
public async _write(chunk: any, encoding: any, cb: any) {
const destKey = this.demuxer(chunk);
if (this.streamsByKey[destKey] === undefined) {
const newPipelines = this.pipelineConstructor(destKey, chunk);
this.streamsByKey[destKey] = newPipelines;
newPipelines.forEach(newPipeline => {
if (this.remultiplex && isReadable(newPipeline)) {
(newPipeline as NodeJS.ReadWriteStream).pipe(
this.transform,
);
} else if (this.remultiplex) {
console.error(
`Pipeline construct for ${destKey} does not implement readable interface`,
);
this.streamsByKey[destKey] = await this.construct(destKey);
}
if (!this.streamsByKey[destKey].write(chunk, encoding)) {
this.streamsByKey[destKey].once("drain", () => {
cb();
});
}
const pipelines = this.streamsByKey[destKey];
const pendingDrains: Array<Promise<any>> = [];
pipelines.forEach(pipeline => {
if (!pipeline.write(chunk, encoding)) {
pendingDrains.push(
new Promise(resolve => {
pipeline.once("drain", () => {
resolve();
});
}),
);
}
});
await Promise.all(pendingDrains);
} else {
cb();
}
public _flush() {
const pipelines: DemuxStreams[] = Array.prototype.concat.apply(
[],
Object.values(this.streamsByKey),
);
const flushPromises: Array<Promise<void>> = [];
pipelines.forEach(pipeline => {
flushPromises.push(
new Promise(resolve => {
pipeline.once("end", () => {
resolve();
});
}),
);
});
pipelines.forEach(pipeline => pipeline.end());
Promise.all(flushPromises).then(() => {
this.push(null);
this.emit("end");
});
}
public _destroy(error: any, cb: (error?: any) => void) {
const pipelines: DemuxStreams[] = [].concat.apply(
[],
Object.values(this.streamsByKey),
public on(event: string, cb: any) {
switch (eventsTarget[event]) {
case EventSubscription.Self:
super.on(event, cb);
break;
case EventSubscription.All:
Object.keys(this.streamsByKey).forEach(key =>
this.streamsByKey[key].on(event, cb),
);
pipelines.forEach(p => (p as any).destroy());
cb(error);
break;
default:
super.on(event, cb);
}
return this;
}
public once(event: string, cb: any) {
switch (eventsTarget[event]) {
case EventSubscription.Self:
super.once(event, cb);
break;
case EventSubscription.All:
Object.keys(this.streamsByKey).forEach(key =>
this.streamsByKey[key].once(event, cb),
);
break;
default:
super.once(event, cb);
}
return this;
}
}

View File

@@ -28,7 +28,7 @@ import { unbatch } from "./unbatch";
import { compose } from "./compose";
import { demux } from "./demux";
export function strom(defaultOptions: TransformOptions = { objectMode: true }) {
export default function mhysa(defaultOptions?: TransformOptions) {
function withDefaultOptions<T extends any[], R>(
n: number,
fn: (...args: T) => R,

View File

@@ -1,17 +1,3 @@
export async function sleep(time: number): Promise<{} | null> {
return time > 0 ? new Promise(resolve => setTimeout(resolve, time)) : null;
}
export type AllStreams =
| NodeJS.ReadableStream
| NodeJS.ReadWriteStream
| NodeJS.WritableStream;
export function isReadable(
stream: AllStreams,
): stream is NodeJS.WritableStream {
return (
(stream as NodeJS.ReadableStream).pipe !== undefined &&
(stream as any).readable === true
);
}

View File

@@ -1,2 +1,2 @@
export { strom } from "./functions";
export * from "./utils";
import mhysa from "./functions";
export default mhysa;

View File

@@ -1,12 +0,0 @@
import { Transform } from "stream";
export function collected(stream: Transform): any {
return new Promise((resolve, reject) => {
stream.once("data", d => {
resolve(d);
});
stream.once("error", e => {
reject(e);
});
});
}

View File

@@ -1 +0,0 @@
export { collected } from "./collected";

View File

@@ -1,10 +1,10 @@
import test from "ava";
import { expect } from "chai";
import { Readable } from "stream";
import { strom } from "../src";
import mhysa from "../src";
import { FlushStrategy } from "../src/functions/accumulator";
import { performance } from "perf_hooks";
const { accumulator, accumulatorBy } = strom({ objectMode: true });
const { accumulator, accumulatorBy } = mhysa({ objectMode: true });
test.cb("accumulator() rolling", t => {
t.plan(3);
@@ -14,14 +14,8 @@ test.cb("accumulator() rolling", t => {
key: string;
}
const source = new Readable({ objectMode: true });
const firstFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const secondFlush = [
{ ts: 2, key: "d" },
{ ts: 3, key: "e" },
];
const firstFlush = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const secondFlush = [{ ts: 2, key: "d" }, { ts: 3, key: "e" }];
const thirdFlush = [{ ts: 4, key: "f" }];
const flushes = [firstFlush, secondFlush, thirdFlush];
@@ -94,10 +88,7 @@ test.cb(
"nonExistingKey",
{ objectMode: true },
);
const input = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const input = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
source
.pipe(accumulatorStream)
@@ -191,10 +182,7 @@ test.cb("accumulator() sliding", t => {
{ ts: 4, key: "d" },
];
const firstFlush = [{ ts: 0, key: "a" }];
const secondFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const secondFlush = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const thirdFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
@@ -244,10 +232,7 @@ test.cb("accumulator() sliding with key", t => {
{ ts: 6, key: "g" },
];
const firstFlush = [{ ts: 0, key: "a" }];
const secondFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const secondFlush = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const thirdFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
@@ -258,14 +243,8 @@ test.cb("accumulator() sliding with key", t => {
{ ts: 2, key: "c" },
{ ts: 3, key: "d" },
];
const fifthFlush = [
{ ts: 3, key: "d" },
{ ts: 5, key: "f" },
];
const sixthFlush = [
{ ts: 5, key: "f" },
{ ts: 6, key: "g" },
];
const fifthFlush = [{ ts: 3, key: "d" }, { ts: 5, key: "f" }];
const sixthFlush = [{ ts: 5, key: "f" }, { ts: 6, key: "g" }];
const flushes = [
firstFlush,
@@ -307,10 +286,7 @@ test.cb(
"nonExistingKey",
{ objectMode: true },
);
const input = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const input = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
source
.pipe(accumulatorStream)
@@ -358,22 +334,10 @@ test.cb(
{ ts: 6, key: "g" },
];
const firstFlush = [{ ts: 0, key: "a" }];
const secondFlush = [
{ ts: 0, key: "a" },
{ ts: 2, key: "c" },
];
const thirdFlush = [
{ ts: 2, key: "c" },
{ ts: 3, key: "d" },
];
const fourthFlush = [
{ ts: 3, key: "d" },
{ ts: 5, key: "f" },
];
const fifthFlush = [
{ ts: 5, key: "f" },
{ ts: 6, key: "g" },
];
const secondFlush = [{ ts: 0, key: "a" }, { ts: 2, key: "c" }];
const thirdFlush = [{ ts: 2, key: "c" }, { ts: 3, key: "d" }];
const fourthFlush = [{ ts: 3, key: "d" }, { ts: 5, key: "f" }];
const fifthFlush = [{ ts: 5, key: "f" }, { ts: 6, key: "g" }];
const flushes = [
firstFlush,
@@ -505,10 +469,7 @@ test.cb("accumulatorBy() sliding", t => {
{ ts: 6, key: "g" },
];
const firstFlush = [{ ts: 0, key: "a" }];
const secondFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
];
const secondFlush = [{ ts: 0, key: "a" }, { ts: 1, key: "b" }];
const thirdFlush = [
{ ts: 0, key: "a" },
{ ts: 1, key: "b" },
@@ -519,14 +480,8 @@ test.cb("accumulatorBy() sliding", t => {
{ ts: 2, key: "c" },
{ ts: 3, key: "d" },
];
const fifthFlush = [
{ ts: 3, key: "d" },
{ ts: 5, key: "f" },
];
const sixthFlush = [
{ ts: 5, key: "f" },
{ ts: 6, key: "g" },
];
const fifthFlush = [{ ts: 3, key: "d" }, { ts: 5, key: "f" }];
const sixthFlush = [{ ts: 5, key: "f" }, { ts: 6, key: "g" }];
const flushes = [
firstFlush,

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { batch, map, fromArray } = strom({ objectMode: true });
import mhysa from "../src";
const { batch } = mhysa({ objectMode: true });
test.cb("batch() batches chunks together", t => {
t.plan(3);
@@ -57,28 +57,3 @@ test.cb("batch() yields a batch after the timeout", t => {
source.push(null);
}, 600 * 2);
});
test.cb(
"batch() yields all input data even when the last element(s) dont make a full batch",
t => {
const data = [1, 2, 3, 4, 5, 6, 7];
fromArray([...data])
.pipe(batch(3))
.pipe(
map(d => {
t.deepEqual(
d,
[data.shift(), data.shift(), data.shift()].filter(
x => !!x,
),
);
}),
)
.on("error", t.fail)
.on("finish", () => {
t.is(data.length, 0);
t.end();
});
},
);

View File

@@ -2,8 +2,8 @@ import * as cp from "child_process";
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { child } = strom();
import mhysa from "../src";
const { child } = mhysa();
test.cb(
"child() allows easily writing to child process stdin and reading from its stdout",

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { collect } = strom();
import mhysa from "../src";
const { collect } = mhysa();
test.cb(
"collect() collects streamed elements into an array (object, flowing mode)",
@@ -59,7 +59,7 @@ test.cb(
const source = new Readable({ objectMode: false });
source
.pipe(collect({ objectMode: false }))
.pipe(collect())
.on("data", collected => {
expect(collected).to.deep.equal(Buffer.from("abc"));
t.pass();

View File

@@ -2,9 +2,9 @@ import * as test from "ava";
import { expect } from "chai";
import { sleep } from "../src/helpers";
import { Readable, Writable } from "stream";
import { strom } from "../src";
import mhysa from "../src";
import { performance } from "perf_hooks";
const { compose, map, fromArray } = strom({ objectMode: true });
const { compose, map } = mhysa({ objectMode: true });
test.cb("compose() chains two streams together in the correct order", t => {
t.plan(3);
@@ -98,7 +98,7 @@ test.cb("piping compose() maintains correct order", t => {
});
test("compose() writable length should be less than highWaterMark when handing writes", async t => {
t.plan(2);
t.plan(7);
return new Promise(async (resolve, reject) => {
interface Chunk {
key: string;
@@ -140,12 +140,19 @@ test("compose() writable length should be less than highWaterMark when handing w
{ key: "e", mapped: [] },
];
fromArray(input).pipe(composed);
for (const item of input) {
const res = composed.write(item);
expect(composed._writableState.length).to.be.at.most(2);
t.pass();
if (!res) {
await sleep(10);
}
}
});
});
test("compose() should emit drain event ~rate * highWaterMark ms for every write that causes backpressure", async t => {
t.plan(2);
t.plan(7);
const _rate = 100;
const highWaterMark = 2;
return new Promise(async (resolve, reject) => {
@@ -174,14 +181,19 @@ test("compose() should emit drain event ~rate * highWaterMark ms for every write
composed.on("drain", () => {
t.pass();
expect(composed._writableState.length).to.be.equal(0);
expect(performance.now() - start).to.be.closeTo(
_rate * highWaterMark,
40,
);
});
composed.on("data", (chunk: Chunk) => {
t.deepEqual(chunk.mapped, [1, 2]);
pendingReads--;
if (pendingReads === 0) {
resolve();
}
});
composed.on("finish", () => resolve());
const input = [
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
@@ -189,7 +201,19 @@ test("compose() should emit drain event ~rate * highWaterMark ms for every write
{ key: "d", mapped: [] },
{ key: "e", mapped: [] },
];
fromArray(input).pipe(composed);
let start = performance.now();
let pendingReads = input.length;
start = performance.now();
for (const item of input) {
const res = composed.write(item);
expect(composed._writableState.length).to.be.at.most(highWaterMark);
t.pass();
if (!res) {
await sleep(_rate * highWaterMark * 2);
start = performance.now();
}
}
});
});
@@ -223,6 +247,10 @@ test.cb(
composed.on("drain", () => {
expect(composed._writableState.length).to.be.equal(0);
expect(performance.now() - start).to.be.closeTo(
_rate * input.length,
50,
);
t.pass();
});
@@ -243,6 +271,7 @@ test.cb(
input.forEach(item => {
composed.write(item);
});
const start = performance.now();
},
);

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { concat, collect } = strom();
import mhysa from "../src";
const { concat, collect } = mhysa();
test.cb(
"concat() concatenates multiple readable streams (object, flowing mode)",
@@ -172,7 +172,7 @@ test.cb(
test.cb("concat() concatenates empty list of readable streams", t => {
t.plan(0);
concat()
.pipe(collect({ objectMode: false }))
.pipe(collect())
.on("data", _ => {
t.fail();
})

View File

@@ -1,11 +1,11 @@
import { Readable } from "stream";
import test from "ava";
import { strom } from "../src";
import mhysa from "../src";
const withDefaultOptions = strom({ objectMode: true });
const withoutOptions = strom();
const withDefaultOptions = mhysa({ objectMode: true });
const withoutOptions = mhysa();
test("strom instances can have default options", t => {
test("Mhysa instances can have default options", t => {
let batch = withDefaultOptions.batch();
t.true(batch._readableState.objectMode);
t.true(batch._writableState.objectMode);

View File

@@ -1,11 +1,11 @@
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
import { Writable, Readable } from "stream";
import * as sinon from "sinon";
import { sleep } from "../src/helpers";
import mhysa from "../src";
import { Writable } from "stream";
const sinon = require("sinon");
const { sleep } = require("../src/helpers");
import { performance } from "perf_hooks";
const { demux, map, fromArray } = strom({ objectMode: true });
const { demux, map } = mhysa();
interface Test {
key: string;
@@ -31,7 +31,7 @@ test.cb("demux() constructor should be called once per key", t => {
return dest;
});
const demuxed = demux(construct, "key", {});
const demuxed = demux(construct, "key", { objectMode: true });
demuxed.on("finish", () => {
expect(construct.withArgs("a").callCount).to.equal(1);
@@ -41,35 +41,8 @@ test.cb("demux() constructor should be called once per key", t => {
t.end();
});
fromArray(input).pipe(demuxed);
});
test.cb("demux() item written passed in constructor", t => {
t.plan(4);
const input = [
{ key: "a", visited: [] },
{ key: "b", visited: [] },
{ key: "c", visited: [] },
];
const construct = sinon.spy((destKey: string, item: any) => {
expect(item).to.deep.equal({ key: destKey, visited: [] });
t.pass();
const dest = map((chunk: Test) => {
chunk.visited.push(1);
return chunk;
});
return dest;
});
const demuxed = demux(construct, "key", {});
demuxed.on("finish", () => {
t.pass();
t.end();
});
fromArray(input).pipe(demuxed);
input.forEach(event => demuxed.write(event));
demuxed.end();
});
test.cb("demux() should send input through correct pipeline", t => {
@@ -93,7 +66,7 @@ test.cb("demux() should send input through correct pipeline", t => {
return dest;
};
const demuxed = demux(construct, "key", {});
const demuxed = demux(construct, "key", { objectMode: true });
demuxed.on("finish", () => {
pipelineSpies["a"].getCalls().forEach(call => {
@@ -111,7 +84,8 @@ test.cb("demux() should send input through correct pipeline", t => {
t.end();
});
fromArray(input).pipe(demuxed);
input.forEach(event => demuxed.write(event));
demuxed.end();
});
test.cb("demux() constructor should be called once per key using keyBy", t => {
@@ -134,7 +108,7 @@ test.cb("demux() constructor should be called once per key using keyBy", t => {
return dest;
});
const demuxed = demux(construct, item => item.key, {});
const demuxed = demux(construct, item => item.key, { objectMode: true });
demuxed.on("finish", () => {
expect(construct.withArgs("a").callCount).to.equal(1);
@@ -144,7 +118,8 @@ test.cb("demux() constructor should be called once per key using keyBy", t => {
t.end();
});
fromArray(input).pipe(demuxed);
input.forEach(event => demuxed.write(event));
demuxed.end();
});
test.cb("demux() should send input through correct pipeline using keyBy", t => {
@@ -168,7 +143,7 @@ test.cb("demux() should send input through correct pipeline using keyBy", t => {
return dest;
};
const demuxed = demux(construct, item => item.key, {});
const demuxed = demux(construct, item => item.key, { objectMode: true });
demuxed.on("finish", () => {
pipelineSpies["a"].getCalls().forEach(call => {
@@ -186,10 +161,11 @@ test.cb("demux() should send input through correct pipeline using keyBy", t => {
t.end();
});
fromArray(input).pipe(demuxed);
input.forEach(event => demuxed.write(event));
demuxed.end();
});
test("demux() write should return false and emit drain if more than highWaterMark items are buffered", t => {
test("demux() write should return false after if it has >= highWaterMark items buffered and drain should be emitted", t => {
return new Promise(async (resolve, reject) => {
t.plan(7);
interface Chunk {
@@ -213,7 +189,7 @@ test("demux() write should return false and emit drain if more than highWaterMar
await sleep(slowProcessorSpeed);
return { ...chunk, mapped: [1] };
},
{ highWaterMark: 1 },
{ highWaterMark: 1, objectMode: true },
);
first.on("data", chunk => {
@@ -229,6 +205,7 @@ test("demux() write should return false and emit drain if more than highWaterMar
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark,
});
@@ -252,7 +229,7 @@ test("demux() write should return false and emit drain if more than highWaterMar
});
});
test("demux() should emit one drain event after slowProcessorSpeed * highWaterMark ms when first stream is bottleneck", t => {
test("demux() should emit one drain event after slowProcessorSpeed * highWaterMark ms", t => {
return new Promise(async (resolve, reject) => {
t.plan(7);
interface Chunk {
@@ -278,7 +255,7 @@ test("demux() should emit one drain event after slowProcessorSpeed * highWaterMa
chunk.mapped.push(1);
return chunk;
},
{ highWaterMark: 1 },
{ highWaterMark: 1, objectMode: true },
);
first.on("data", () => {
@@ -291,6 +268,7 @@ test("demux() should emit one drain event after slowProcessorSpeed * highWaterMa
return first;
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark,
});
_demux.on("error", err => {
@@ -318,7 +296,7 @@ test("demux() should emit one drain event after slowProcessorSpeed * highWaterMa
test("demux() should emit one drain event when writing 6 items with highWaterMark of 5", t => {
return new Promise(async (resolve, reject) => {
t.plan(1);
t.plan(7);
interface Chunk {
key: string;
mapped: number[];
@@ -340,11 +318,12 @@ test("demux() should emit one drain event when writing 6 items with highWaterMar
chunk.mapped.push(2);
return chunk;
},
{ highWaterMark: 1 },
{ highWaterMark: 1, objectMode: true },
);
first.on("data", () => {
pendingReads--;
t.pass();
if (pendingReads === 0) {
resolve();
}
@@ -352,6 +331,7 @@ test("demux() should emit one drain event when writing 6 items with highWaterMar
return first;
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark: 5,
});
@@ -375,10 +355,9 @@ test("demux() should emit one drain event when writing 6 items with highWaterMar
});
});
test.cb(
"demux() should emit drain event when second stream is bottleneck after (highWaterMark - 2) * slowProcessorSpeed ms",
test.cb.only(
"demux() should emit drain event when third stream is bottleneck",
t => {
// ie) first two items are pushed directly into first and second streams (highWaterMark - 2 remain in demux)
t.plan(8);
const slowProcessorSpeed = 100;
const highWaterMark = 5;
@@ -404,7 +383,7 @@ test.cb(
chunk.mapped.push(1);
return chunk;
},
{ highWaterMark: 1 },
{ objectMode: true, highWaterMark: 1 },
);
const second = map(
@@ -413,23 +392,25 @@ test.cb(
chunk.mapped.push(2);
return chunk;
},
{ highWaterMark: 1 },
{ objectMode: true, highWaterMark: 1 },
);
first.pipe(second).pipe(sink);
return first;
};
const _demux = demux(construct, () => "a", {
objectMode: true,
highWaterMark,
});
_demux.on("error", err => {
t.end(err);
});
// This event should be received after at least 5 * slowProcessorSpeed (two are read immediately by first and second, 5 remaining in demux before drain event)
_demux.on("drain", () => {
expect(_demux._writableState.length).to.be.equal(0);
expect(performance.now() - start).to.be.greaterThan(
slowProcessorSpeed * 3,
slowProcessorSpeed * (input.length - 2),
);
t.pass();
});
@@ -446,14 +427,15 @@ test.cb(
let pendingReads = input.length;
const start = performance.now();
fromArray(input).pipe(_demux);
input.forEach(item => {
_demux.write(item);
});
},
);
test.cb(
"demux() should emit drain event when third stream is bottleneck",
"demux() should emit drain event when second stream is bottleneck",
t => {
// @TODO investigate why drain is emitted after slowProcessorSpeed
t.plan(8);
const slowProcessorSpeed = 100;
const highWaterMark = 5;
@@ -464,7 +446,7 @@ test.cb(
const sink = new Writable({
objectMode: true,
write(chunk, encoding, cb) {
expect(chunk.mapped).to.deep.equal([1, 2, 3]);
expect(chunk.mapped).to.deep.equal([1, 2]);
t.pass();
pendingReads--;
if (pendingReads === 0) {
@@ -479,14 +461,14 @@ test.cb(
chunk.mapped.push(1);
return chunk;
},
{ highWaterMark: 1 },
{ objectMode: true, highWaterMark: 1 },
);
const second = map(
(chunk: Chunk) => {
chunk.mapped.push(2);
return chunk;
},
{ highWaterMark: 1 },
{ objectMode: true, highWaterMark: 1 },
);
const third = map(
@@ -495,7 +477,7 @@ test.cb(
chunk.mapped.push(3);
return chunk;
},
{ highWaterMark: 1 },
{ objectMode: true, highWaterMark: 1 },
);
first
@@ -505,16 +487,18 @@ test.cb(
return first;
};
const _demux = demux(construct, () => "a", {
objectMode: true,
highWaterMark,
});
_demux.on("error", err => {
t.end(err);
});
// This event should be received after at least 3 * slowProcessorSpeed (two are read immediately by first and second, 3 remaining in demux before drain event)
_demux.on("drain", () => {
expect(_demux._writableState.length).to.be.equal(0);
expect(performance.now() - start).to.be.greaterThan(
slowProcessorSpeed,
slowProcessorSpeed * (input.length - 4),
);
t.pass();
});
@@ -531,7 +515,9 @@ test.cb(
let pendingReads = input.length;
const start = performance.now();
fromArray(input).pipe(_demux);
input.forEach(item => {
_demux.write(item);
});
},
);
@@ -550,21 +536,10 @@ test("demux() should be blocked by slowest pipeline", t => {
chunk.mapped.push(1);
return chunk;
},
{ highWaterMark: 1 },
{ objectMode: true, highWaterMark: 1 },
);
return first;
};
const _demux = demux(construct, "key", {
highWaterMark: 1,
});
_demux.on("error", err => {
reject(err);
});
_demux.on("data", async chunk => {
first.on("data", chunk => {
pendingReads--;
if (chunk.key === "b") {
expect(performance.now() - start).to.be.greaterThan(
@@ -575,12 +550,22 @@ test("demux() should be blocked by slowest pipeline", t => {
resolve();
}
});
return first;
};
const _demux = demux(construct, "key", {
objectMode: true,
highWaterMark: 1,
});
_demux.on("error", err => {
reject(err);
});
const input = [
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "c", mapped: [] },
{ key: "c", mapped: [] },
{ key: "c", mapped: [] },
{ key: "b", mapped: [] },
];
@@ -599,266 +584,74 @@ test("demux() should be blocked by slowest pipeline", t => {
});
});
test.cb("Demux should remux to sink", t => {
t.plan(6);
let i = 0;
const input = [
{ key: "a", visited: [] },
{ key: "b", visited: [] },
{ key: "a", visited: [] },
{ key: "c", visited: [] },
{ key: "a", visited: [] },
{ key: "b", visited: [] },
];
const result = [
{ key: "a", visited: ["a"] },
{ key: "b", visited: ["b"] },
{ key: "a", visited: ["a"] },
{ key: "c", visited: ["c"] },
{ key: "a", visited: ["a"] },
{ key: "b", visited: ["b"] },
];
const construct = (destKey: string) => {
const dest = map((chunk: any) => {
chunk.visited.push(destKey);
return chunk;
});
return dest;
};
const sink = map(d => {
t.deepEqual(d, result[i]);
i++;
if (i === input.length) {
t.end();
}
});
const demuxed = demux(construct, "key", {});
fromArray(input)
.pipe(demuxed)
.pipe(sink);
});
test.cb("Demux should send data events", t => {
t.plan(6);
let i = 0;
const input = [
{ key: "a", visited: [] },
{ key: "b", visited: [] },
{ key: "a", visited: [] },
{ key: "c", visited: [] },
{ key: "a", visited: [] },
{ key: "b", visited: [] },
];
const result = [
{ key: "a", visited: ["a"] },
{ key: "b", visited: ["b"] },
{ key: "a", visited: ["a"] },
{ key: "c", visited: ["c"] },
{ key: "a", visited: ["a"] },
{ key: "b", visited: ["b"] },
];
const construct = (destKey: string) => {
const dest = map((chunk: any) => {
chunk.visited.push(destKey);
return chunk;
});
return dest;
};
const demuxed = demux(construct, "key", {});
fromArray(input).pipe(demuxed);
demuxed.on("data", d => {
t.deepEqual(d, result[i]);
i++;
if (i === input.length) {
t.end();
}
});
});
test.cb("demux() `finish` and `end` propagates", t => {
test("demux() should emit drain event when second stream in pipeline is bottleneck", t => {
t.plan(5);
const highWaterMark = 3;
return new Promise(async (resolve, reject) => {
interface Chunk {
key: string;
mapped: number[];
}
t.plan(9);
const construct = (destKey: string) => {
const dest = map((chunk: any) => {
chunk.mapped.push(destKey);
return chunk;
});
return dest;
};
const _demux = demux(construct, "key", {
highWaterMark: 3,
});
const fakeSource = new Readable({
const sink = new Writable({
objectMode: true,
read() {
return;
write(chunk, encoding, cb) {
expect(chunk.mapped).to.deep.equal([1, 2]);
t.pass();
cb();
if (pendingReads === 0) {
resolve();
}
},
});
const sink = map((d: any) => {
const curr = input.shift();
t.is(curr.key, d.key);
t.deepEqual(d.mapped, [d.key]);
});
fakeSource.pipe(_demux).pipe(sink);
fakeSource.on("end", () => {
t.pass();
});
_demux.on("finish", () => {
t.pass();
});
_demux.on("unpipe", () => {
t.pass();
});
_demux.on("end", () => {
t.pass();
t.end();
});
sink.on("finish", () => {
t.pass();
});
const input = [
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
];
fakeSource.push(input[0]);
fakeSource.push(input[1]);
fakeSource.push(null);
});
test.cb("demux() `unpipe` propagates", t => {
interface Chunk {
key: string;
mapped: number[];
}
t.plan(7);
const construct = (destKey: string) => {
const dest = map((chunk: any) => {
chunk.mapped.push(destKey);
const first = map(
(chunk: Chunk) => {
expect(first._readableState.length).to.be.at.most(2);
chunk.mapped.push(1);
return chunk;
});
return dest;
};
const _demux = demux(construct, "key", {
highWaterMark: 3,
});
const fakeSource = new Readable({
objectMode: true,
read() {
return;
},
});
{ objectMode: true, highWaterMark: 2 },
);
const sink = map((d: any) => {
const curr = input.shift();
t.is(curr.key, d.key);
t.deepEqual(d.mapped, [d.key]);
});
fakeSource.pipe(_demux).pipe(sink);
_demux.on("unpipe", () => {
t.pass();
});
sink.on("unpipe", () => {
t.pass();
});
sink.on("finish", () => {
t.pass();
t.end();
});
const input = [
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
];
fakeSource.push(input[0]);
fakeSource.push(input[1]);
fakeSource.push(null);
});
test.cb("demux() should be 'destroyable'", t => {
t.plan(2);
const _sleep = 100;
interface Chunk {
key: string;
mapped: string[];
}
const construct = (destKey: string) => {
const first = map(async (chunk: Chunk) => {
await sleep(_sleep);
chunk.mapped.push(destKey);
const second = map(
async (chunk: Chunk) => {
await sleep(100);
chunk.mapped.push(2);
expect(second._writableState.length).to.be.equal(1);
pendingReads--;
return chunk;
});
},
{ objectMode: true, highWaterMark: 1 },
);
first.pipe(second).pipe(sink);
return first;
};
const _demux = demux(construct, "key");
const fakeSource = new Readable({
const _demux = demux(construct, "key", {
objectMode: true,
read() {
return;
},
highWaterMark,
});
_demux.on("error", err => {
reject();
});
const fakeSink = new Writable({
objectMode: true,
write(data, enc, cb) {
const cur = input.shift();
t.is(cur.key, data.key);
t.deepEqual(cur.mapped, ["a"]);
if (cur.key === "a") {
_demux.destroy();
}
cb();
},
_demux.on("drain", () => {
expect(_demux._writableState.length).to.be.equal(0);
t.pass();
});
_demux.on("close", t.end);
fakeSource.pipe(_demux).pipe(fakeSink);
const input = [
{ key: "a", mapped: [] },
{ key: "b", mapped: [] },
{ key: "c", mapped: [] },
{ key: "d", mapped: [] },
{ key: "e", mapped: [] },
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
{ key: "a", mapped: [] },
];
fakeSource.push(input[0]);
fakeSource.push(input[1]);
fakeSource.push(input[2]);
fakeSource.push(input[3]);
fakeSource.push(input[4]);
let pendingReads = input.length;
input.forEach(item => {
_demux.write(item);
});
});
});

View File

@@ -2,8 +2,8 @@ import * as cp from "child_process";
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { duplex } = strom();
import mhysa from "../src";
const { duplex } = mhysa();
test.cb(
"duplex() combines a writable and readable stream into a ReadWrite stream",

View File

@@ -1,8 +1,8 @@
import test from "ava";
import { expect } from "chai";
import { Readable } from "stream";
import { strom } from "../src";
const { filter } = strom();
import mhysa from "../src";
const { filter } = mhysa();
test.cb("filter() filters elements synchronously", t => {
t.plan(2);

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { flatMap } = strom({ objectMode: true });
import mhysa from "../src";
const { flatMap } = mhysa({ objectMode: true });
test.cb("flatMap() maps elements synchronously", t => {
t.plan(6);

View File

@@ -1,7 +1,7 @@
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { fromArray } = strom();
import mhysa from "../src";
const { fromArray } = mhysa();
test.cb("fromArray() streams array elements in flowing mode", t => {
t.plan(3);

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { join } = strom();
import mhysa from "../src";
const { join } = mhysa();
test.cb("join() joins chunks using the specified separator", t => {
t.plan(9);

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { last } = strom();
import mhysa from "../src";
const { last } = mhysa();
test("last() resolves to the last chunk streamed by the given readable stream", async t => {
const source = new Readable({ objectMode: true });

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { map } = strom();
import mhysa from "../src";
const { map } = mhysa();
test.cb("map() maps elements synchronously", t => {
t.plan(3);

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { merge } = strom();
import mhysa from "../src";
const { merge } = mhysa();
test.cb(
"merge() merges multiple readable streams in chunk arrival order",

View File

@@ -2,9 +2,9 @@ import { Readable } from "stream";
import { performance } from "perf_hooks";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
import mhysa from "../src";
import { sleep } from "../src/helpers";
const { parallelMap } = strom({ objectMode: true });
const { parallelMap } = mhysa({ objectMode: true });
test.cb("parallelMap() parallel mapping", t => {
t.plan(6);

View File

@@ -1,8 +1,8 @@
import { Readable, finished } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { parse } = strom();
import mhysa from "../src";
const { parse } = mhysa();
test.cb("parse() parses the streamed elements as JSON", t => {
t.plan(3);

View File

@@ -2,8 +2,8 @@ import { Readable } from "stream";
import { performance } from "perf_hooks";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { rate } = strom({ objectMode: true });
import mhysa from "../src";
const { rate } = mhysa({ objectMode: true });
test.cb("rate() sends data at a rate of 150", t => {
t.plan(5);

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { reduce } = strom({ objectMode: true });
import mhysa from "../src";
const { reduce } = mhysa({ objectMode: true });
test.cb("reduce() reduces elements synchronously", t => {
t.plan(1);

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { replace } = strom();
import mhysa from "../src";
const { replace } = mhysa();
test.cb(
"replace() replaces occurrences of the given string in the streamed elements with the specified " +

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { split } = strom();
import mhysa from "../src";
const { split } = mhysa();
test.cb("split() splits chunks using the default separator (\\n)", t => {
t.plan(5);

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { stringify } = strom();
import mhysa from "../src";
const { stringify } = mhysa();
test.cb("stringify() stringifies the streamed elements as JSON", t => {
t.plan(4);

View File

@@ -1,8 +1,8 @@
import { Readable } from "stream";
import test from "ava";
import { expect } from "chai";
import { strom } from "../src";
const { unbatch, batch } = strom({ objectMode: true });
import mhysa from "../src";
const { unbatch, batch } = mhysa({ objectMode: true });
test.cb("unbatch() unbatches", t => {
t.plan(3);

View File

@@ -1,9 +0,0 @@
import test from "ava";
import { collected } from "../../src/utils";
import { strom } from "../../src";
const { fromArray, collect } = strom({ objectMode: true });
test("collected returns a promise for the first data point", async t => {
const data = collected(fromArray([1, 2, 3, 4]).pipe(collect()));
t.deepEqual(await data, [1, 2, 3, 4]);
});

View File

@@ -409,10 +409,10 @@
resolved "https://registry.yarnpkg.com/@types/node/-/node-12.7.2.tgz#c4e63af5e8823ce9cc3f0b34f7b998c2171f0c44"
integrity sha512-dyYO+f6ihZEtNPDcWNR1fkoTDf3zAK3lAABDze3mz6POyIercH0lEUawUFXlG8xaQZmm1yEBON/4TsYv/laDYg==
"@types/node@^12.12.15":
version "12.12.15"
resolved "https://npm.dev.jogogo.co/@types%2fnode/-/node-12.12.15.tgz#8dfb6ce22fedd469128137640a3aa8f17415422f"
integrity sha512-Pv+vWicyFd07Hw/SmNnTUguqrHgDfMtjabvD9sQyxeqbpCEg8CmViLBaVPHtNsoBgZECrRf5/pgV6FJIBrGSjw==
"@types/node@^12.7.2":
version "12.12.14"
resolved "https://npm.dev.jogogo.co/@types%2fnode/-/node-12.12.14.tgz#1c1d6e3c75dba466e0326948d56e8bd72a1903d2"
integrity sha512-u/SJDyXwuihpwjXy7hOOghagLEV1KdAST6syfnOk6QZAMzZuWZqXy5aYYZbh8Jdpd4escVFP0MvftHNDb9pruA==
"@types/sinon@^7.0.13":
version "7.5.1"
@@ -1935,7 +1935,7 @@ merge2@^1.2.3, merge2@^1.3.0:
integrity sha512-2j4DAdlBOkiSZIsaXk4mTE3sRS02yBHAtfy127xRV3bQUFqXkjHCHLW6Scv7DwNRbIWNHH8zpnz9zMaKXIdvYw==
mhysa@./:
version "2.0.0-alpha.1"
version "0.0.1-beta.4"
micromatch@^4.0.2:
version "4.0.2"