-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighland.js
3946 lines (3590 loc) · 102 KB
/
highland.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
!function(e){if("object"==typeof exports)module.exports=e();else if("function"==typeof define&&define.amd)define(e);else{var f;"undefined"!=typeof window?f=window:"undefined"!=typeof global?f=global:"undefined"!=typeof self&&(f=self),f.highland=e()}}(function(){var define,module,exports;return (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);throw new Error("Cannot find module '"+o+"'")}var f=n[o]={exports:{}};t[o][0].call(f.exports,function(e){var n=t[o][1][e];return s(n?n:e)},f,f.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
(function (process,global){
/**
* 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 = _dereq_('util').inherits;
var EventEmitter = _dereq_('events').EventEmitter;
/**
* 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. You call `next()`
* to signal you've finished processing the current data. 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.
*
* **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 also pass as an optional third parameter a function, an array of strings
* or a number. In this case the event handler will try to wrap the arguments emitted
* to it and write this object to the new stream.
*
* **Promise -** Accepts an ES6 / jQuery style promise and returns a
* Highland Stream which will emit a single value (or an error).
*
* @id _(source)
* @section Stream Objects
* @name _(source)
* @param {Array | Function | Readable Stream | Promise} source - (optional) source to take values from from
* @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);
*
* // creating a stream from events
* _('click', btn).each(handleEvent);
*
* // creating a stream from events with mapping
* _('request', httpServer, ['req', 'res']).each(handleEvent);
*
* // from a Promise object
* var foo = _($.getJSON('/api/foo'));
*/
exports = module.exports = function (/*optional*/xs, /*optional*/ee, /*optional*/ mappingHint) {
return new Stream(xs, ee, mappingHint);
};
var _ = exports;
// Save bytes in the minified (but not gzipped) version:
var ArrayProto = Array.prototype,
ObjProto = Object.prototype;
// Create quick reference variables for speed access to core prototypes.
var slice = ArrayProto.slice,
toString = ObjProto.toString;
_.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 toString.call(x) === '[object Array]';
};
// setImmediate implementation with browser and older node fallbacks
if (typeof setImmediate === 'undefined') {
if (typeof process === 'undefined' || !(process.nextTick)) {
_.setImmediate = function (fn) {
setTimeout(fn, 0);
};
}
else {
// use nextTick on old node versions
_.setImmediate = process.nextTick;
}
}
// check no process.stdout to detect browserify
else if (typeof process === 'undefined' || !(process.stdout)) {
// modern browser - but not a direct alias for IE10 compatibility
_.setImmediate = function (fn) {
setImmediate(fn);
};
}
else {
_.setImmediate = setImmediate;
}
/**
* 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)
var _global = this;
if (typeof global !== 'undefined') {
_global = global;
}
else if (typeof window !== 'undefined') {
_global = window;
}
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 function () {
var args = largs.concat(slice.call(arguments));
if (args.length < n) {
return _.ncurry.apply(this, [n, fn].concat(args));
}
return fn.apply(this, args.slice(0, n));
};
};
/**
* 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} f - 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. 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;
}
var r = fns[0].apply(this, arguments);
for (var i = 1; i < fns.length; i++) {
r = fns[i].call(this, r);
}
return r;
};
};
/**
* Actual Stream constructor wrapped the the main exported function
*/
function Stream(/*optional*/xs, /*optional*/ee, /*optional*/mappingHint) {
if (xs && _.isStream(xs)) {
// already a Stream
return xs;
}
EventEmitter.call(this);
var self = 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
self.__HighlandStream__ = true;
self.id = ('' + Math.random()).substr(2, 6);
this.paused = true;
this._incoming = [];
this._outgoing = [];
this._consumers = [];
this._observers = [];
this._destructors = [];
this._send_events = false;
this._delegate = null;
this.source = null;
// Old-style node Stream.pipe() checks for this
this.writable = true;
self.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
self.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;
}
}
});
if (xs === undefined) {
// nothing else to do
}
else if (_.isArray(xs)) {
self._incoming = xs.concat([nil]);
}
else if (typeof xs === 'function') {
this._generator = xs;
this._generator_push = function (err, x) {
self.write(err ? new StreamError(err): x);
};
this._generator_next = function (s) {
if (s) {
// we MUST pause to get the redirect object into the _incoming
// buffer otherwise it would be passed directly to _send(),
// which does not handle StreamRedirect objects!
var _paused = self.paused;
if (!_paused) {
self.pause();
}
self.write(new StreamRedirect(s));
if (!_paused) {
self.resume();
}
}
else {
self._generator_running = false;
}
if (!self.paused) {
self.resume();
}
};
}
else if (_.isObject(xs)) {
if (_.isFunction(xs.then)) {
// probably a promise
return _(function (push) {
xs.then(function (value) {
push(null, value);
return push(null, nil);
},
function (err) {
push(err);
return push(null, nil);
});
});
}
else {
// write any errors into the stream
xs.on('error', function (err) {
self.write(new StreamError(err));
});
// assume it's a pipeable stream as a source
xs.pipe(self);
}
}
else if (typeof xs === 'string') {
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; };
}
ee.on(xs, function () {
var ctx = mapper.apply(this, arguments);
self.write(ctx);
});
}
else {
throw new Error(
'Unexpected argument type to Stream(): ' + (typeof xs)
);
}
}
inherits(Stream, EventEmitter);
/**
* adds a top-level _.foo(mystream) style export for Stream methods
*/
function exposeMethod(name) {
var f = Stream.prototype[name];
var n = f.length;
_[name] = _.ncurry(n + 1, function () {
var args = Array.prototype.slice.call(arguments);
var s = _(args.pop());
return f.apply(s, args);
});
}
/**
* Used as an Error marker when writing to a Stream's incoming buffer
*/
function StreamError(err) {
this.__HighlandStreamError__ = true;
this.error = err;
}
/**
* Used as a Redirect marker when writing to a Stream's incoming buffer
*/
function StreamRedirect(to) {
this.__HighlandStreamRedirect__ = true;
this.to = to;
}
/**
* Returns true if `x` is a Highland Stream.
*
* @id isStream
* @section Utils
* @name _.isStream(x)
* @param x - the object to test
* @api public
*
* _.isStream('foo') // => false
* _.isStream(_([1,2,3])) // => true
*/
_.isStream = function (x) {
return _.isObject(x) && x.__HighlandStream__;
};
_._isStreamError = function (x) {
return _.isObject(x) && x.__HighlandStreamError__;
};
_._isStreamRedirect = function (x) {
return _.isObject(x) && x.__HighlandStreamRedirect__;
};
/**
* Sends errors / data to consumers, observers and event handlers
*/
Stream.prototype._send = function (err, x) {
if (x === nil) {
this.ended = true;
}
if (this._consumers.length) {
for (var i = 0, len = this._consumers.length; i < len; i++) {
var c = this._consumers[i];
if (err) {
c.write(new StreamError(err));
}
else {
c.write(x);
}
}
}
if (this._observers.length) {
for (var j = 0, len2 = this._observers.length; j < len2; j++) {
this._observers[j].write(x);
}
}
if (this._send_events) {
if (x === nil) {
this.emit('end');
}
else {
this.emit('data', x);
}
}
};
/**
* Pauses the stream. All Highland Streams start in the paused state.
*
* @id pause
* @section Stream Objects
* @name Stream.pause()
* @api public
*
* var xs = _(generator);
* xs.pause();
*/
Stream.prototype.pause = function () {
//console.log([this.id, 'pause']);
this.paused = true;
if (this.source) {
this.source._checkBackPressure();
}
};
/**
* When there is a change in downstream consumers, it will often ask
* the parent Stream to re-check it's state and pause/resume accordingly.
*/
Stream.prototype._checkBackPressure = function () {
if (!this._consumers.length) {
return this.pause();
}
for (var i = 0, len = this._consumers.length; i < len; i++) {
if (this._consumers[i].paused) {
return this.pause();
}
}
return this.resume();
};
/**
* Starts pull values out of the incoming buffer and sending them downstream,
* this will exit early if this causes a downstream consumer to pause.
*/
Stream.prototype._readFromBuffer = function () {
var len = this._incoming.length;
var i = 0;
while (i < len && !this.paused) {
var x = this._incoming[i];
if (_._isStreamError(x)) {
this._send(x.error);
}
else if (_._isStreamRedirect(x)) {
this._redirect(x.to);
}
else {
this._send(null, x);
}
i++;
}
// remove processed data from _incoming buffer
this._incoming.splice(0, i);
};
/**
* Starts pull values out of the incoming buffer and sending them downstream,
* this will exit early if this causes a downstream consumer to pause.
*/
Stream.prototype._sendOutgoing = function () {
var len = this._outgoing.length;
var i = 0;
while (i < len && !this.paused) {
var x = this._outgoing[i];
if (_._isStreamError(x)) {
Stream.prototype._send.call(this, x.error);
}
else if (_._isStreamRedirect(x)) {
this._redirect(x.to);
}
else {
Stream.prototype._send.call(this, null, x);
}
i++;
}
// remove processed data from _outgoing buffer
this._outgoing.splice(0, i);
};
/**
* Resumes a paused Stream. This will either read from the Stream's incoming
* buffer or request more data from an upstream source.
*
* @id resume
* @section Stream Objects
* @name Stream.resume()
* @api public
*
* var xs = _(generator);
* xs.resume();
*/
Stream.prototype.resume = function () {
//console.log([this.id, 'resume']);
if (this._resume_running) {
// already processing _incoming buffer, ignore resume call
this._repeat_resume = true;
return;
}
this._resume_running = true;
do {
// use a repeat flag to avoid recursing resume() calls
this._repeat_resume = false;
this.paused = false;
// send values from outgoing buffer first
this._sendOutgoing();
// send values from incoming buffer before reading from source
this._readFromBuffer();
// we may have paused while reading from buffer
if (!this.paused) {
// ask parent for more data
if (this.source) {
this.source._checkBackPressure();
}
// run _generator to fill up _incoming buffer
else if (this._generator) {
this._runGenerator();
}
else {
// perhaps a node stream is being piped in
this.emit('drain');
}
}
} while (this._repeat_resume);
this._resume_running = false;
};
/**
* Ends a Stream. This is the same as sending a [nil](#nil) value as data.
* You shouldn't need to call this directly, rather it will be called by
* any [Node Readable Streams](http://nodejs.org/api/stream.html#stream_class_stream_readable)
* you pipe in.
*
* @id end
* @section Stream Objects
* @name Stream.end()
* @api public
*
* mystream.end();
*/
Stream.prototype.end = function () {
this.write(nil);
};
/**
* Pipes a Highland Stream to a [Node Writable Stream](http://nodejs.org/api/stream.html#stream_class_stream_writable)
* (Highland Streams are also Node Writable Streams). This will pull all the
* data from the source Highland Stream and write it to the destination,
* automatically managing flow so that the destination is not overwhelmed
* by a fast source.
*
* This function returns the destination so you can chain together pipe calls.
*
* @id pipe
* @section Consumption
* @name Stream.pipe(dest)
* @param {Writable Stream} dest - the destination to write all data to
* @api public
*
* var source = _(generator);
* var dest = fs.createWriteStream('myfile.txt')
* source.pipe(dest);
*
* // chained call
* source.pipe(through).pipe(dest);
*/
Stream.prototype.pipe = function (dest) {
var self = this;
// stdout and stderr are special case writables that cannot be closed
var canClose = dest !== process.stdout && dest !== process.stderr;
var s = self.consume(function (err, x, push, next) {
if (err) {
self.emit('error', err);
return;
}
if (x === nil) {
if (canClose) {
dest.end();
}
}
else if (dest.write(x) !== false) {
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.
this._destructors.push(function () {
dest.removeListener('drain', onConsumerDrain);
});
s.resume();
return dest;
function onConsumerDrain() {
s.resume();
}
};
/**
* Destroys a stream by unlinking it from any consumers and sources. This will
* stop all consumers from receiving events from this stream and removes this
* stream as a consumer of any source stream.
*
* This function calls end() on the stream and unlinks it from any piped-to streams.
*
* @id destroy
* @section Stream Objects
* @name Stream.destroy()
* @api public
*/
Stream.prototype.destroy = function () {
var self = this;
this.end();
_(this._consumers).each(function (consumer) {
self._removeConsumer(consumer);
});
if (this.source) {
this.source._removeConsumer(this);
}
_(this._destructors).each(function (destructor) {
destructor();
});
};
/**
* Runs the generator function for this Stream. If the generator is already
* running (it has been called and not called next() yet) then this function
* will do nothing.
*/
Stream.prototype._runGenerator = function () {
// if _generator already running, exit
if (this._generator_running) {
return;
}
this._generator_running = true;
this._generator(this._generator_push, this._generator_next);
};
/**
* Performs the redirect from one Stream to another. In order for the
* redirect to happen at the appropriate time, it is put on the incoming
* buffer as a StreamRedirect object, and this function is called
* once it is read from the buffer.
*/
Stream.prototype._redirect = function (to) {
// coerce to Stream
to = _(to);
while (to._delegate) {
to = to._delegate;
}
to._consumers = this._consumers.map(function (c) {
c.source = to;
return c;
});
// TODO: copy _observers
this._consumers = [];
this.consume = function () {
return to.consume.apply(to, arguments);
};
this._removeConsumer = function () {
return to._removeConsumer.apply(to, arguments);
};
if (this.paused) {
to.pause();
}
else {
this.pause();
to._checkBackPressure();
}
this._delegate = to;
};
/**
* Adds a new consumer Stream, which will accept data and provide backpressure
* to this Stream. Adding more than one consumer will cause an exception to be
* thrown as the backpressure strategy must be explicitly chosen by the
* developer (through calling fork or observe).
*/
Stream.prototype._addConsumer = function (s) {
if (this._consumers.length) {
throw new Error(
'Stream already being consumed, you must either fork() or observe()'
);
}
s.source = this;
this._consumers.push(s);
this._checkBackPressure();
};
/**
* Removes a consumer from this Stream.
*/
Stream.prototype._removeConsumer = function (s) {
this._consumers = this._consumers.filter(function (c) {
return c !== s;
});
if (s.source === this) {
s.source = null;
}
this._checkBackPressure();
};
/**
* Consumes values from a Stream (once resumed) and returns a new Stream for
* you to optionally push values onto using the provided push / next functions.
*
* This function forms the basis of many higher-level Stream operations.
* It will not cause a paused stream to immediately resume, but behaves more
* like a 'through' stream, handling values as they are read.
*
* @id consume
* @section Transforms
* @name Stream.consume(f)
* @param {Function} f - the function to handle errors and values
* @api public
*
* var filter = function (f, source) {
* return source.consume(function (err, x, push, next) {
* if (err) {
* // pass errors along the stream and consume next value
* push(err);
* next();
* }
* else if (x === _.nil) {
* // pass nil (end event) along the stream
* push(null, x);
* }
* else {
* // pass on the value only if the value passes the predicate
* if (f(x)) {
* push(null, x);
* }
* next();
* }
* });
* };
*/
Stream.prototype.consume = function (f) {
var self = this;
var s = new Stream();
var _send = s._send;
var push = function (err, x) {
//console.log(['push', err, x, s.paused]);
if (x === nil) {
// ended, remove consumer from source
self._removeConsumer(s);
}
if (s.paused) {
if (err) {
s._outgoing.push(new StreamError(err));
}
else {
s._outgoing.push(x);
}
}
else {
_send.call(s, err, x);
}
};
var async;
var next_called;
var next = function (s2) {
//console.log(['next', async]);
if (s2) {
// we MUST pause to get the redirect object into the _incoming
// buffer otherwise it would be passed directly to _send(),
// which does not handle StreamRedirect objects!
var _paused = s.paused;
if (!_paused) {
s.pause();
}
s.write(new StreamRedirect(s2));
if (!_paused) {
s.resume();
}
}
else if (async) {
s.resume();
}
else {
next_called = true;
}
};
s._send = function (err, x) {
async = false;
next_called = false;