-
Notifications
You must be signed in to change notification settings - Fork 147
/
index.js
executable file
·4804 lines (4366 loc) · 128 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
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Highland: the high-level streams library
*
* Highland may be freely distributed under the Apache 2.0 license.
* http://github.com/caolan/highland
* Copyright (c) Caolan McMahon
*
*/
var inherits = require('util').inherits;
var EventEmitter = require('events').EventEmitter;
var Decoder = require('string_decoder').StringDecoder;
var Queue = require('./queue');
var IntMap = require('./intMap');
// Create quick slice reference variable for speed
var slice = Array.prototype.slice;
var hasOwn = Object.prototype.hasOwnProperty;
// Set up the global object.
var _global = this;
if (typeof global !== 'undefined') {
_global = global;
}
else if (typeof window !== 'undefined') {
_global = window;
}
/**
* The Stream constructor, accepts an array of values or a generator function
* as an optional argument. This is typically the entry point to the Highland
* APIs, providing a convenient way of chaining calls together.
*
* **Arrays -** Streams created from Arrays will emit each value of the Array
* and then emit a [nil](#nil) value to signal the end of the Stream.
*
* **Generators -** These are functions which provide values for the Stream.
* They are lazy and can be infinite, they can also be asynchronous (for
* example, making a HTTP request). You emit values on the Stream by calling
* `push(err, val)`, much like a standard Node.js callback. Once it has been
* called, the generator function will not be called again unless you call
* `next()`. This call to `next()` will signal you've finished processing the
* current data and allow for the generator function to be called again. If the
* Stream is still being consumed the generator function will then be called
* again.
*
* You can also redirect a generator Stream by passing a new source Stream
* to read from to next. For example: `next(other_stream)` - then any subsequent
* calls will be made to the new source.
*
* **Node Readable Stream -** Pass in a Node Readable Stream object to wrap
* it with the Highland API. Reading from the resulting Highland Stream will
* begin piping the data from the Node Stream to the Highland Stream.
*
* A stream constructed in this way relies on `Readable#pipe` to end the
* Highland Stream once there is no more data. Not all Readable Streams do
* this. For example, `IncomingMessage` will only emit `close` when the client
* aborts communications and will *not* properly call `end`. In this case, you
* can provide an optional `onFinished` function with the signature
* `onFinished(readable, callback)` as the second argument.
*
* This function will be passed the Readable and a callback that should called
* when the Readable ends. If the Readable ended from an error, the error
* should be passed as the first argument to the callback. `onFinished` should
* bind to whatever listener is necessary to detect the Readable's completion.
* If the callback is called multiple times, only the first invocation counts.
* If the callback is called *after* the Readable has already ended (e.g., the
* `pipe` method already called `end`), it will be ignored.
*
* The `onFinished` function may optionally return one of the following:
*
* - A cleanup function that will be called when the stream ends. It should
* unbind any listeners that were added.
* - An object with the following optional properties:
* - `onDestroy` - the cleanup function.
* - `continueOnError` - Whether or not to continue the stream when an
* error is passed to the callback. Set this to `true` if the Readable
* may continue to emit values after errors. Default: `false`.
*
* See [this issue](https://github.com/caolan/highland/issues/490) for a
* discussion on why Highland cannot reliably detect stream completion for
* all implementations and why the `onFinished` function is required.
*
* **EventEmitter / jQuery Elements -** Pass in both an event name and an
* event emitter as the two arguments to the constructor and the first
* argument emitted to the event handler will be written to the new Stream.
*
* You can pass a mapping hint as the third argument, which specifies how
* event arguments are pushed into the stream. If no mapping hint is provided,
* only the first value emitted with the event to the will be pushed onto the
* Stream.
*
* If `mappingHint` is a number, an array of that length will be pushed onto
* the stream, containing exactly that many parameters from the event. If it's
* an array, it's used as keys to map the arguments into an object which is
* pushed to the tream. If it is a function, it's called with the event
* arguments, and the returned value is pushed.
*
* **Promise -** Accepts an ES6 / jQuery style promise and returns a
* Highland Stream which will emit a single value (or an error). In case you use
* [bluebird cancellation](http://bluebirdjs.com/docs/api/cancellation.html) Highland Stream will be empty for a cancelled promise.
*
* **Iterator -** Accepts an ES6 style iterator that implements the [iterator protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_.22iterator.22_protocol):
* yields all the values from the iterator using its `next()` method and terminates when the
* iterator's done value returns true. If the iterator's `next()` method throws, the exception will be emitted as an error,
* and the stream will be ended with no further calls to `next()`.
*
* **Iterable -** Accepts an object that implements the [iterable protocol](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Iteration_protocols#The_.22iterable.22_protocol),
* i.e., contains a method that returns an object that conforms to the iterator protocol. The stream will use the
* iterator defined in the `Symbol.iterator` property of the iterable object to generate emitted values.
*
* @id _(source)
* @section Stream Objects
* @name _(source)
* @param {Array | Function | Iterator | Iterable | Promise | Readable Stream | String} source - (optional) source to take values from from
* @param {Function} onFinished - (optional) a function that detects when the readable completes. Second argument. Only valid if `source` is a Readable.
* @param {EventEmitter | jQuery Element} eventEmitter - (optional) An event emitter. Second argument. Only valid if `source` is a String.
* @param {Array | Function | Number} mappingHint - (optional) how to pass the
* arguments to the callback. Only valid if `source` is a String.
* @api public
*
* // from an Array
* _([1, 2, 3, 4]);
*
* // using a generator function
* _(function (push, next) {
* push(null, 1);
* push(err);
* next();
* });
*
* // a stream with no source, can pipe node streams through it etc.
* var through = _();
*
* // wrapping a Node Readable Stream so you can easily manipulate it
* _(readable).filter(hasSomething).pipe(writeable);
*
* // wrapping a Readable that may signify completion by emitting `close`
* // (e.g., IncomingMessage).
* _(req, function (req, callback) {
* req.on('end', callback)
* .on('close', callback)
* .on('error', callback);
*
* return function () {
* req.removeListener('end', callback);
* req.removeListener('close', callback);
* req.removeListener('error', callback);
* };
* }).pipe(writable);
*
* // wrapping a Readable that may emit values after errors.
* _(req, function (req, callback) {
* req.on('error', callback);
*
* return {
* onDestroy: function () {
* req.removeListener('error', callback);
* },
* continueOnError: true
* };
* }).pipe(writable);
*
* // creating a stream from events
* _('click', btn).each(handleEvent);
*
* // creating a stream from events with a mapping array
* _('request', httpServer, ['req', 'res']).each(handleEvent);
* //=> { req: IncomingMessage, res: ServerResponse }
*
* // creating a stream from events with a mapping function
* _('request', httpServer, function(req, res) {
* return res;
* }).each(handleEvent);
* //=> IncomingMessage
*
* // from a Promise object
* var foo = _($.getJSON('/api/foo'));
*
* //from an iterator
* var map = new Map([['a', 1], ['b', 2]]);
* var bar = _(map.values()).toArray(_.log);
* //=> [1, 2]
*
* //from an iterable
* var set = new Set([1, 2, 2, 3, 4]);
* var bar = _(set).toArray(_.log);
* //=> [ 1, 2, 3, 4]
*/
/*eslint-disable no-multi-spaces */
var _ = exports = module.exports = __(Stream);
function __(StreamCtor) {
return function (/*optional*/xs, /*optional*/secondArg, /*optional*/ mappingHint) {
/*eslint-enable no-multi-spaces */
var s = null;
if (_.isUndefined(xs)) {
// nothing else to do
s = new StreamCtor();
s.writable = true;
}
else if (_.isStream(xs)) {
if (!(xs instanceof StreamCtor)) { // different subclass or version
var ret = new StreamCtor();
xs.on('error', ret.write.bind(ret));
s = xs.pipe(ret);
}
else {
s = xs;
}
}
else if (_.isArray(xs)) {
s = new StreamCtor();
s._outgoing.enqueueAll(xs);
s._outgoing.enqueue(_.nil);
}
else if (_.isFunction(xs)) {
s = new StreamCtor(xs);
}
else if (_.isObject(xs)) {
// check to see if we have a readable stream
if (_.isFunction(xs.on) && _.isFunction(xs.pipe)) {
var onFinish = _.isFunction(secondArg) ? secondArg : defaultReadableOnFinish;
s = new StreamCtor();
s.writable = true;
pipeReadable(xs, onFinish, s);
// s has to be writable so that the pipe works
// return a non-writable stream
return s.map(function (x) { return x; });
}
else if (_.isFunction(xs.then)) {
// probably a promise
s = promiseStream(StreamCtor, xs);
}
// must check iterators and iterables in this order
// because generators are both iterators and iterables:
// their Symbol.iterator method returns the `this` object
// and an infinite loop would result otherwise
else if (_.isFunction(xs.next)) {
//probably an iterator
return iteratorStream(StreamCtor, xs);
}
else if (!_.isUndefined(_global.Symbol) && xs[_global.Symbol.iterator]) {
//probably an iterable
return iteratorStream(StreamCtor, xs[_global.Symbol.iterator]());
}
else {
throw new Error(
'Object was not a stream, promise, iterator or iterable: ' + (typeof xs)
);
}
}
else if (_.isString(xs)) {
var mapper = hintMapper(mappingHint);
s = new StreamCtor();
secondArg.on(xs, function () {
var ctx = mapper.apply(this, arguments);
s.write(ctx);
});
}
else {
throw new Error(
'Unexpected argument type to Stream constructor: ' + (typeof xs)
);
}
return s;
};
}
/*eslint-enable no-use-before-define */
// ES5 detected value, used for switch between ES5 and ES3 code
var isES5 = (function () {
'use strict';
return Function.prototype.bind && !this;
}());
_.isUndefined = function (x) {
return typeof x === 'undefined';
};
_.isFunction = function (x) {
return typeof x === 'function';
};
_.isObject = function (x) {
return typeof x === 'object' && x !== null;
};
_.isString = function (x) {
return typeof x === 'string';
};
_.isArray = Array.isArray || function (x) {
return Object.prototype.toString.call(x) === '[object Array]';
};
// setImmediate browser fallback
if (typeof setImmediate === 'undefined') {
_.setImmediate = function (fn) {
setTimeout(fn, 0);
};
}
else {
// We don't use a direct alias since some tests depend
// on allowing Sinon.Js to override the global
// setImmediate.
_.setImmediate = function (fn) {
setImmediate(fn);
};
}
/**
* The end of stream marker. This is sent along the data channel of a Stream
* to tell consumers that the Stream has ended. See the example map code for
* an example of detecting the end of a Stream.
*
* Note: `nil` is setup as a global where possible. This makes it convenient
* to access, but more importantly lets Streams from different Highland
* instances work together and detect end-of-stream properly. This is mostly
* useful for NPM where you may have many different Highland versions installed.
*
* @id nil
* @section Utils
* @name _.nil
* @api public
*
* var map = function (iter, source) {
* return source.consume(function (err, val, push, next) {
* if (err) {
* push(err);
* next();
* }
* else if (val === _.nil) {
* push(null, val);
* }
* else {
* push(null, iter(val));
* next();
* }
* });
* };
*/
// set up a global nil object in cases where you have multiple Highland
// instances installed (often via npm)
if (!_global.nil) {
_global.nil = {};
}
var nil = _.nil = _global.nil;
/**
* Transforms a function with specific arity (all arguments must be
* defined) in a way that it can be called as a chain of functions until
* the arguments list is saturated.
*
* This function is not itself curryable.
*
* @id curry
* @name _.curry(fn, [*arguments])
* @section Functions
* @param {Function} fn - the function to curry
* @param args.. - any number of arguments to pre-apply to the function
* @returns Function
* @api public
*
* fn = curry(function (a, b, c) {
* return a + b + c;
* });
*
* fn(1)(2)(3) == fn(1, 2, 3)
* fn(1, 2)(3) == fn(1, 2, 3)
* fn(1)(2, 3) == fn(1, 2, 3)
*/
_.curry = function (fn /* args... */) {
var args = slice.call(arguments);
return _.ncurry.apply(this, [fn.length].concat(args));
};
/**
* Same as `curry` but with a specific number of arguments. This can be
* useful when functions do not explicitly define all its parameters.
*
* This function is not itself curryable.
*
* @id ncurry
* @name _.ncurry(n, fn, [args...])
* @section Functions
* @param {Number} n - the number of arguments to wait for before apply fn
* @param {Function} fn - the function to curry
* @param args... - any number of arguments to pre-apply to the function
* @returns Function
* @api public
*
* fn = ncurry(3, function () {
* return Array.prototype.join.call(arguments, '.');
* });
*
* fn(1, 2, 3) == '1.2.3';
* fn(1, 2)(3) == '1.2.3';
* fn(1)(2)(3) == '1.2.3';
*/
_.ncurry = function (n, fn /* args... */) {
var largs = slice.call(arguments, 2);
if (largs.length >= n) {
return fn.apply(this, largs.slice(0, n));
}
return _.partial.apply(this, [_.ncurry, n, fn].concat(largs));
};
/**
* Partially applies the function (regardless of whether it has had curry
* called on it). This will always postpone execution until at least the next
* call of the partially applied function.
*
* @id partial
* @name _.partial(fn, args...)
* @section Functions
* @param {Function} fn - function to partial apply
* @param args... - the arguments to apply to the function
* @api public
*
* var addAll = function () {
* var args = Array.prototype.slice.call(arguments);
* return foldl1(add, args);
* };
* var f = partial(addAll, 1, 2);
* f(3, 4) == 10
*/
_.partial = function (f /* args... */) {
var args = slice.call(arguments, 1);
return function () {
return f.apply(this, args.concat(slice.call(arguments)));
};
};
/**
* Evaluates the function `fn` with the argument positions swapped. Only
* works with functions that accept two arguments.
*
* @id flip
* @name _.flip(fn, [x, y])
* @section Functions
* @param {Function} fn - function to flip argument application for
* @param x - parameter to apply to the right hand side of f
* @param y - parameter to apply to the left hand side of f
* @api public
*
* div(2, 4) == 0.5
* flip(div, 2, 4) == 2
* flip(div)(2, 4) == 2
*/
_.flip = _.curry(function (fn, x, y) { return fn(y, x); });
/**
* Creates a composite function, which is the application of function1 to
* the results of function2. You can pass an arbitrary number of arguments
* and have them composed. This means you can't partially apply the compose
* function itself.
*
* @id compose
* @name _.compose(fn1, fn2, ...)
* @section Functions
* @api public
*
* var add1 = add(1);
* var mul3 = mul(3);
*
* var add1mul3 = compose(mul3, add1);
* add1mul3(2) == 9
*/
_.compose = function (/*functions...*/) {
var fns = slice.call(arguments).reverse();
return _.seq.apply(null, fns);
};
/**
* The reversed version of [compose](#compose). Where arguments are in the
* order of application.
*
* @id seq
* @name _.seq(fn1, fn2, ...)
* @section Functions
* @api public
*
* var add1 = add(1);
* var mul3 = mul(3);
*
* var add1mul3 = seq(add1, mul3);
* add1mul3(2) == 9
*/
_.seq = function () {
var fns = slice.call(arguments);
return function () {
if (!fns.length) {
return null;
}
var r = fns[0].apply(this, arguments);
for (var i = 1; i < fns.length; i++) {
r = fns[i].call(this, r);
}
return r;
};
};
function nop() {
// Do nothing.
}
function defaultReadableOnFinish(readable, callback) {
// It's possible that `close` is emitted *before* `end`, so we simply
// cannot handle that case. See
// https://github.com/caolan/highland/issues/490 for details.
// pipe already pushes on end, so no need to bind to `end`.
// write any errors into the stream
readable.once('error', callback);
return function () {
readable.removeListener('error', callback);
};
}
function pipeReadable(xs, onFinish, stream) {
var response = onFinish(xs, streamEndCb);
var unbound = false;
var cleanup = null;
var endOnError = true;
if (_.isFunction(response)) {
cleanup = response;
}
else if (response != null) {
cleanup = response.onDestroy;
endOnError = !response.continueOnError;
}
xs.pipe(stream);
stream.onDestroy(unbind);
function streamEndCb(error) {
if (stream._nil_pushed) {
return;
}
if (error) {
stream.write(new StreamError(error));
}
if (error == null || endOnError) {
unbind();
stream.end();
}
}
function unbind() {
if (unbound) {
return;
}
unbound = true;
if (cleanup) {
cleanup();
}
if (xs.unpipe) {
xs.unpipe(stream);
}
}
}
function newPullFunction(xs) {
return function pull(cb) {
xs.pull(cb);
};
}
function newDelegateGenerator(pull) {
return function delegateGenerator(push, next) {
var self = this;
pull(function (err, x) {
// Minor optimization to immediately call the
// generator if requested.
var old = self._defer_run_generator;
self._defer_run_generator = true;
push(err, x);
if (x !== nil) {
next();
}
self._defer_run_generator = old;
if (!old && self._run_generator_deferred) {
self._runGenerator();
}
});
};
}
function promiseStream(StreamCtor, promise) {
if (_.isFunction(promise['finally'])) { // eslint-disable-line dot-notation
// Using finally handles also bluebird promise cancellation
return new StreamCtor(function (push) {
promise.then(function (value) {
return push(null, value);
},
function (err) {
return push(err);
})['finally'](function () { // eslint-disable-line dot-notation
return push(null, nil);
});
});
}
else {
// Sticking to promise standard only
return new StreamCtor(function (push) {
promise.then(function (value) {
push(null, value);
return push(null, nil);
},
function (err) {
push(err);
return push(null, nil);
});
});
}
}
function iteratorStream(StreamCtor, it) {
return new StreamCtor(function (push, next) {
var iterElem, iterErr;
try {
iterElem = it.next();
}
catch (err) {
iterErr = err;
}
if (iterErr) {
push(iterErr);
push(null, _.nil);
}
else if (iterElem.done) {
if (!_.isUndefined(iterElem.value)) {
// generators can return a final
// value on completion using return
// keyword otherwise value will be
// undefined
push(null, iterElem.value);
}
push(null, _.nil);
}
else {
push(null, iterElem.value);
next();
}
});
}
function hintMapper(mappingHint) {
var mappingHintType = (typeof mappingHint);
var mapper;
if (mappingHintType === 'function') {
mapper = mappingHint;
}
else if (mappingHintType === 'number') {
mapper = function () {
return slice.call(arguments, 0, mappingHint);
};
}
else if (_.isArray(mappingHint)) {
mapper = function () {
var args = arguments;
return mappingHint.reduce(function (ctx, hint, idx) {
ctx[hint] = args[idx];
return ctx;
}, {});
};
}
else {
mapper = function (x) { return x; };
}
return mapper;
}
function pipeStream(src, dest, write, end, passAlongErrors) {
var resume = null;
var s = src.consume(function (err, x, push, next) {
var canContinue;
if (err) {
if (passAlongErrors) {
canContinue = write.call(dest, new StreamError(err));
}
else {
src.emit('error', err);
canContinue = true;
}
}
else if (x === nil) {
end.call(dest);
return;
}
else {
canContinue = write.call(dest, x);
}
if (canContinue !== false) {
next();
}
else {
resume = next;
}
});
dest.on('drain', onConsumerDrain);
// Since we don't keep a reference to piped-to streams,
// save a callback that will unbind the event handler.
src.onDestroy(function () {
dest.removeListener('drain', onConsumerDrain);
});
dest.emit('pipe', src);
s.resume();
return dest;
function onConsumerDrain() {
if (resume) {
resume();
resume = null;
}
}
}
/**
* Actual Stream constructor wrapped the the main exported function
*/
function Stream(generator) {
EventEmitter.call(this);
// used to detect Highland Streams using isStream(x), this
// will work even in cases where npm has installed multiple
// versions, unlike an instanceof check
this.__HighlandStream__ = true;
this.id = ('' + Math.random()).substr(2, 6);
this.paused = true;
this.ended = false;
// Old-style node Stream.pipe() checks for writable, and gulp checks for
// readable. Discussion at https://github.com/caolan/highland/pull/438.
this.readable = true;
this.writable = false;
this._outgoing = new Queue();
this._observers = [];
this._destructors = [];
this._send_events = false;
this._nil_pushed = false; // Sets to true when a nil has been queued.
this._explicitly_destroyed = false; // Sets to true when destroy() is called.
this._request = null;
this._multiplexer = null;
this._consumer = null;
this._generator = generator;
this._generator_requested = true;
this._defer_run_generator = false;
this._run_generator_deferred = false;
var self = this;
// These are defined here instead of on the prototype
// because bind is super slow.
this._push_fn = function (err, x) {
if (x === nil) {
// It's possible that next was called before the
// nil, causing the generator to be deferred. This
// is allowed since push can be called at any time.
// We have to cancel the deferred call to preserve the
// generator contract.
self._run_generator_deferred = false;
}
// This will set _nil_pushed if necessary.
self._writeOutgoing(err ? new StreamError(err) : x);
};
this._next_fn = function (xs) {
if (self._explicitly_destroyed) {
return;
}
// It's possible to get into a situation where a call to next() is
// scheduled asynchonously, but before it is run, destroy() is called,
// usually by a downstream consumer like take(1). The call to next()
// still completes, and there is nothing the original caller can do can
// do. We do not want to throw in that situation.
if (self._nil_pushed) {
throw new Error('Cannot call next after nil');
}
self._generator_requested = true;
if (xs) {
xs = self.create(xs);
var pull = newPullFunction(xs);
self._generator = newDelegateGenerator(pull);
}
if (!self.paused) {
if (self._defer_run_generator) {
self._run_generator_deferred = true;
}
else {
_.setImmediate(function () {
self._runGenerator();
});
}
}
};
this.on('newListener', function (ev) {
if (ev === 'data') {
self._send_events = true;
_.setImmediate(self.resume.bind(self));
}
else if (ev === 'end') {
// this property avoids us checking the length of the
// listners subscribed to each event on each _send() call
self._send_events = true;
}
});
// TODO: write test to cover this removeListener code
this.on('removeListener', function (ev) {
if (ev === 'end' || ev === 'data') {
var end_listeners = self.listeners('end').length;
var data_listeners = self.listeners('data').length;
if (end_listeners + data_listeners === 0) {
// stop emitting events
self._send_events = false;
}
}
});
}
inherits(Stream, EventEmitter);
function _addMethod(proto, topLevel) {
return function(name, f) {
proto[name] = f;
var n = f.length;
function relevel(coerce) {
return _.ncurry(n + 1, function () {
var args = slice.call(arguments);
var s = coerce(args.pop());
return f.apply(s, args);
});
}
topLevel[name] = relevel(topLevel);
topLevel[name]._relevel = relevel;
};
}
var addMethod = _addMethod(Stream.prototype, _);
function _addMethods(proto, topLevel, methods) {
for (var p in methods) {
if (hasOwn.call(methods, p)) {
_addMethod(proto, topLevel)(p, methods[p]);
}
}
}
function _addToplevelMethod(topLevel) {
return function (name, fn) {
function relevel(_topLevel) {
var bound = fn.bind(_topLevel);
bound._relevel = relevel;
return bound;
}
topLevel[name] = relevel(topLevel);
};
}
var addToplevelMethod = _addToplevelMethod(_);
function _addToplevelMethods(topLevel, methods) {
for (var p in methods) {
if (hasOwn.call(methods, p)) {
_addToplevelMethod(topLevel)(p, methods[p]);
}
}
}
function use(Super, originalTopLevel) {
return function(methods, toplevelMethods) {
function Sub() {
Stream.apply(this, arguments);
}
inherits(Sub, Super);
function topLevel() {
return __(Sub).apply(null, arguments);
}
for (var p in originalTopLevel) {
if (hasOwn.call(originalTopLevel, p)) {
var fn = originalTopLevel[p];
topLevel[p] = (typeof fn._relevel === 'function') ? fn._relevel(topLevel) : fn;
}
}
_addMethods(Sub.prototype, topLevel, methods || {});
_addToplevelMethods(topLevel, toplevelMethods || {});
topLevel.use = use(Sub, topLevel);
return topLevel;
};
}
_.use = use(Stream, _);
/**
* Creates a stream that sends a single value then ends.
*
* @id of
* @name _.of(x)
* @param x - the value to send
* @section Utils
*
* _.of(1).toArray(_.log); // => [1]
*/
addToplevelMethod('of', function (x) {
return _([x]);
});
/**
* Creates a stream that sends a single error then ends.
*
* @id fromError
* @name _.fromError(err)
* @param error - the error to send
* @section Utils
*
* _.fromError(new Error('Single Error')).toCallback(function (err, result) {
* // err contains Error('Single Error') object
* }
*/
addToplevelMethod('fromError', function (error) {
return _(function (push) {
push(error);
push(null, _.nil);
});
});
Stream.prototype.create = function () {
return __(this.constructor).apply(null, arguments);
};
Stream.prototype.createChild = function createChild(/*varargs*/) {
var child = this.create.apply(this, arguments);
child.onDestroy(this.destroy.bind(this));
return child;
};
/**
* Used as an Error marker when writing to a Stream's incoming buffer
*/
function StreamError(err) {
this.__HighlandStreamError__ = true;
this.error = err;
}
/**
* Returns true if `x` is a Highland Stream.
*
* @id isStream