Best JavaScript code snippet using playwright-internal
kefir.js
Source:kefir.js
...343 mixin = extend({344 _init: function(args) {},345 _free: function() {},346 _handleValue: function(x, isCurrent) {347 this._send(VALUE, x, isCurrent);348 },349 _handleError: function(x, isCurrent) {350 this._send(ERROR, x, isCurrent);351 },352 _handleEnd: function(__, isCurrent) {353 this._send(END, null, isCurrent);354 },355 _handleAny: function(event) {356 switch (event.type) {357 case VALUE: this._handleValue(event.value, event.current); break;358 case ERROR: this._handleError(event.value, event.current); break;359 case END: this._handleEnd(event.value, event.current); break;360 }361 },362 _onActivation: function() {363 this._source.onAny(this._$handleAny);364 },365 _onDeactivation: function() {366 this._source.offAny(this._$handleAny);367 }368 }, mixin || {});369 function buildClass(BaseClass) {370 function AnonymousObservable(source, args) {371 BaseClass.call(this);372 this._source = source;373 this._name = source._name + '.' + name;374 this._init(args);375 var $ = this;376 this._$handleAny = function(event) {377 $._handleAny(event);378 };379 }380 inherit(AnonymousObservable, BaseClass, {381 _clear: function() {382 BaseClass.prototype._clear.call(this);383 this._source = null;384 this._$handleAny = null;385 this._free();386 }387 }, mixin);388 return AnonymousObservable;389 }390 var AnonymousStream = buildClass(Stream);391 var AnonymousProperty = buildClass(Property);392 if (options.streamMethod) {393 Stream.prototype[name] = options.streamMethod(AnonymousStream, AnonymousProperty);394 }395 if (options.propertyMethod) {396 Property.prototype[name] = options.propertyMethod(AnonymousStream, AnonymousProperty);397 }398}399function withTwoSources(name, mixin /*, options*/) {400 mixin = extend({401 _init: function(args) {},402 _free: function() {},403 _handlePrimaryValue: function(x, isCurrent) {404 this._send(VALUE, x, isCurrent);405 },406 _handlePrimaryError: function(x, isCurrent) {407 this._send(ERROR, x, isCurrent);408 },409 _handlePrimaryEnd: function(__, isCurrent) {410 this._send(END, null, isCurrent);411 },412 _handleSecondaryValue: function(x, isCurrent) {413 this._lastSecondary = x;414 },415 _handleSecondaryError: function(x, isCurrent) {416 this._send(ERROR, x, isCurrent);417 },418 _handleSecondaryEnd: function(__, isCurrent) {},419 _handlePrimaryAny: function(event) {420 switch (event.type) {421 case VALUE:422 this._handlePrimaryValue(event.value, event.current);423 break;424 case ERROR:425 this._handlePrimaryError(event.value, event.current);426 break;427 case END:428 this._handlePrimaryEnd(event.value, event.current);429 break;430 }431 },432 _handleSecondaryAny: function(event) {433 switch (event.type) {434 case VALUE:435 this._handleSecondaryValue(event.value, event.current);436 break;437 case ERROR:438 this._handleSecondaryError(event.value, event.current);439 break;440 case END:441 this._handleSecondaryEnd(event.value, event.current);442 this._removeSecondary();443 break;444 }445 },446 _removeSecondary: function() {447 if (this._secondary !== null) {448 this._secondary.offAny(this._$handleSecondaryAny);449 this._$handleSecondaryAny = null;450 this._secondary = null;451 }452 },453 _onActivation: function() {454 if (this._secondary !== null) {455 this._secondary.onAny(this._$handleSecondaryAny);456 }457 if (this._alive) {458 this._primary.onAny(this._$handlePrimaryAny);459 }460 },461 _onDeactivation: function() {462 if (this._secondary !== null) {463 this._secondary.offAny(this._$handleSecondaryAny);464 }465 this._primary.offAny(this._$handlePrimaryAny);466 }467 }, mixin || {});468 function buildClass(BaseClass) {469 function AnonymousObservable(primary, secondary, args) {470 BaseClass.call(this);471 this._primary = primary;472 this._secondary = secondary;473 this._name = primary._name + '.' + name;474 this._lastSecondary = NOTHING;475 var $ = this;476 this._$handleSecondaryAny = function(event) {477 $._handleSecondaryAny(event);478 };479 this._$handlePrimaryAny = function(event) {480 $._handlePrimaryAny(event);481 };482 this._init(args);483 }484 inherit(AnonymousObservable, BaseClass, {485 _clear: function() {486 BaseClass.prototype._clear.call(this);487 this._primary = null;488 this._secondary = null;489 this._lastSecondary = null;490 this._$handleSecondaryAny = null;491 this._$handlePrimaryAny = null;492 this._free();493 }494 }, mixin);495 return AnonymousObservable;496 }497 var AnonymousStream = buildClass(Stream);498 var AnonymousProperty = buildClass(Property);499 Stream.prototype[name] = function(secondary) {500 return new AnonymousStream(this, secondary, rest(arguments, 1, []));501 };502 Property.prototype[name] = function(secondary) {503 return new AnonymousProperty(this, secondary, rest(arguments, 1, []));504 };505}506// Dispatcher507function callSubscriber(sType, sFn, event) {508 if (sType === ANY) {509 sFn(event);510 } else if (sType === event.type) {511 if (sType === VALUE || sType === ERROR) {512 sFn(event.value);513 } else {514 sFn();515 }516 }517}518function Dispatcher() {519 this._items = [];520}521extend(Dispatcher.prototype, {522 add: function(type, fn) {523 this._items = concat(this._items, [{524 type: type,525 fn: fn526 }]);527 return this._items.length;528 },529 remove: function(type, fn) {530 this._items = removeByPred(this._items, function(fnData) {531 return fnData.type === type && fnData.fn === fn;532 });533 return this._items.length;534 },535 dispatch: function(event) {536 var items = this._items;537 for (var i = 0; i < items.length; i++) {538 callSubscriber(items[i].type, items[i].fn, event);539 }540 }541});542// Events543function Event(type, value, current) {544 return {type: type, value: value, current: !!current};545}546var CURRENT_END = Event(END, undefined, true);547// Observable548function Observable() {549 this._dispatcher = new Dispatcher();550 this._active = false;551 this._alive = true;552}553Kefir.Observable = Observable;554extend(Observable.prototype, {555 _name: 'observable',556 _onActivation: function() {},557 _onDeactivation: function() {},558 _setActive: function(active) {559 if (this._active !== active) {560 this._active = active;561 if (active) {562 this._onActivation();563 } else {564 this._onDeactivation();565 }566 }567 },568 _clear: function() {569 this._setActive(false);570 this._alive = false;571 this._dispatcher = null;572 },573 _send: function(type, x, isCurrent) {574 if (this._alive) {575 this._dispatcher.dispatch(Event(type, x, isCurrent));576 if (type === END) {577 this._clear();578 }579 }580 },581 _on: function(type, fn) {582 if (this._alive) {583 this._dispatcher.add(type, fn);584 this._setActive(true);585 } else {586 callSubscriber(type, fn, CURRENT_END);587 }588 return this;589 },590 _off: function(type, fn) {591 if (this._alive) {592 var count = this._dispatcher.remove(type, fn);593 if (count === 0) {594 this._setActive(false);595 }596 }597 return this;598 },599 onValue: function(fn) {600 return this._on(VALUE, fn);601 },602 onError: function(fn) {603 return this._on(ERROR, fn);604 },605 onEnd: function(fn) {606 return this._on(END, fn);607 },608 onAny: function(fn) {609 return this._on(ANY, fn);610 },611 offValue: function(fn) {612 return this._off(VALUE, fn);613 },614 offError: function(fn) {615 return this._off(ERROR, fn);616 },617 offEnd: function(fn) {618 return this._off(END, fn);619 },620 offAny: function(fn) {621 return this._off(ANY, fn);622 }623});624// extend() can't handle `toString` in IE8625Observable.prototype.toString = function() {626 return '[' + this._name + ']';627};628// Stream629function Stream() {630 Observable.call(this);631}632Kefir.Stream = Stream;633inherit(Stream, Observable, {634 _name: 'stream'635});636// Property637function Property() {638 Observable.call(this);639 this._current = NOTHING;640 this._currentError = NOTHING;641}642Kefir.Property = Property;643inherit(Property, Observable, {644 _name: 'property',645 _send: function(type, x, isCurrent) {646 if (this._alive) {647 if (!isCurrent) {648 this._dispatcher.dispatch(Event(type, x));649 }650 if (type === VALUE) {651 this._current = x;652 }653 if (type === ERROR) {654 this._currentError = x;655 }656 if (type === END) {657 this._clear();658 }659 }660 },661 _on: function(type, fn) {662 if (this._alive) {663 this._dispatcher.add(type, fn);664 this._setActive(true);665 }666 if (this._current !== NOTHING) {667 callSubscriber(type, fn, Event(VALUE, this._current, true));668 }669 if (this._currentError !== NOTHING) {670 callSubscriber(type, fn, Event(ERROR, this._currentError, true));671 }672 if (!this._alive) {673 callSubscriber(type, fn, CURRENT_END);674 }675 return this;676 }677});678// Log679Observable.prototype.log = function(name) {680 name = name || this.toString();681 var handler = function(event) {682 var typeStr = '<' + event.type + (event.current ? ':current' : '') + '>';683 if (event.type === VALUE || event.type === ERROR) {684 console.log(name, typeStr, event.value);685 } else {686 console.log(name, typeStr);687 }688 };689 if (!this.__logHandlers) {690 this.__logHandlers = [];691 }692 this.__logHandlers.push({name: name, handler: handler});693 this.onAny(handler);694 return this;695};696Observable.prototype.offLog = function(name) {697 name = name || this.toString();698 if (this.__logHandlers) {699 var handlerIndex = findByPred(this.__logHandlers, function(obj) {700 return obj.name === name;701 });702 if (handlerIndex !== -1) {703 var handler = this.__logHandlers[handlerIndex].handler;704 this.__logHandlers.splice(handlerIndex, 1);705 this.offAny(handler);706 }707 }708 return this;709};710// Kefir.withInterval()711withInterval('withInterval', {712 _init: function(args) {713 this._fn = args[0];714 var $ = this;715 this._emitter = {716 emit: function(x) {717 $._send(VALUE, x);718 },719 error: function(x) {720 $._send(ERROR, x);721 },722 end: function() {723 $._send(END);724 },725 emitEvent: function(e) {726 $._send(e.type, e.value);727 }728 };729 },730 _free: function() {731 this._fn = null;732 this._emitter = null;733 },734 _onTick: function() {735 this._fn(this._emitter);736 }737});738// Kefir.fromPoll()739withInterval('fromPoll', {740 _init: function(args) {741 this._fn = args[0];742 },743 _free: function() {744 this._fn = null;745 },746 _onTick: function() {747 this._send(VALUE, this._fn());748 }749});750// Kefir.interval()751withInterval('interval', {752 _init: function(args) {753 this._x = args[0];754 },755 _free: function() {756 this._x = null;757 },758 _onTick: function() {759 this._send(VALUE, this._x);760 }761});762// Kefir.sequentially()763withInterval('sequentially', {764 _init: function(args) {765 this._xs = cloneArray(args[0]);766 if (this._xs.length === 0) {767 this._send(END);768 }769 },770 _free: function() {771 this._xs = null;772 },773 _onTick: function() {774 switch (this._xs.length) {775 case 1:776 this._send(VALUE, this._xs[0]);777 this._send(END);778 break;779 default:780 this._send(VALUE, this._xs.shift());781 }782 }783});784// Kefir.repeatedly()785withInterval('repeatedly', {786 _init: function(args) {787 this._xs = cloneArray(args[0]);788 this._i = -1;789 },790 _onTick: function() {791 if (this._xs.length > 0) {792 this._i = (this._i + 1) % this._xs.length;793 this._send(VALUE, this._xs[this._i]);794 }795 }796});797Kefir.repeatedly = deprecated(798 'Kefir.repeatedly()',799 'Kefir.repeat(() => Kefir.sequentially(...)})',800 Kefir.repeatedly801);802// Kefir.later()803withInterval('later', {804 _init: function(args) {805 this._x = args[0];806 },807 _free: function() {808 this._x = null;809 },810 _onTick: function() {811 this._send(VALUE, this._x);812 this._send(END);813 }814});815function _AbstractPool(options) {816 Stream.call(this);817 this._queueLim = get(options, 'queueLim', 0);818 this._concurLim = get(options, 'concurLim', -1);819 this._drop = get(options, 'drop', 'new');820 if (this._concurLim === 0) {821 throw new Error('options.concurLim can\'t be 0');822 }823 var $ = this;824 this._$handleSubAny = function(event) {825 $._handleSubAny(event);826 };827 this._queue = [];828 this._curSources = [];829 this._activating = false;830 this._bindedEndHandlers = [];831}832inherit(_AbstractPool, Stream, {833 _name: 'abstractPool',834 _add: function(obj, toObs) {835 toObs = toObs || id;836 if (this._concurLim === -1 || this._curSources.length < this._concurLim) {837 this._addToCur(toObs(obj));838 } else {839 if (this._queueLim === -1 || this._queue.length < this._queueLim) {840 this._addToQueue(toObs(obj));841 } else if (this._drop === 'old') {842 this._removeOldest();843 this._add(toObs(obj));844 }845 }846 },847 _addAll: function(obss) {848 var $ = this;849 forEach(obss, function(obs) {850 $._add(obs);851 });852 },853 _remove: function(obs) {854 if (this._removeCur(obs) === -1) {855 this._removeQueue(obs);856 }857 },858 _addToQueue: function(obs) {859 this._queue = concat(this._queue, [obs]);860 },861 _addToCur: function(obs) {862 this._curSources = concat(this._curSources, [obs]);863 if (this._active) {864 this._subscribe(obs);865 }866 },867 _subscribe: function(obs) {868 var $ = this;869 var onEnd = function() {870 $._removeCur(obs);871 };872 this._bindedEndHandlers.push({obs: obs, handler: onEnd});873 obs.onAny(this._$handleSubAny);874 obs.onEnd(onEnd);875 },876 _unsubscribe: function(obs) {877 obs.offAny(this._$handleSubAny);878 var onEndI = findByPred(this._bindedEndHandlers, function(obj) {879 return obj.obs === obs;880 });881 if (onEndI !== -1) {882 var onEnd = this._bindedEndHandlers[onEndI].handler;883 this._bindedEndHandlers.splice(onEndI, 1);884 obs.offEnd(onEnd);885 }886 },887 _handleSubAny: function(event) {888 if (event.type === VALUE || event.type === ERROR) {889 this._send(event.type, event.value, event.current && this._activating);890 }891 },892 _removeQueue: function(obs) {893 var index = find(this._queue, obs);894 this._queue = remove(this._queue, index);895 return index;896 },897 _removeCur: function(obs) {898 if (this._active) {899 this._unsubscribe(obs);900 }901 var index = find(this._curSources, obs);902 this._curSources = remove(this._curSources, index);903 if (index !== -1) {904 if (this._queue.length !== 0) {905 this._pullQueue();906 } else if (this._curSources.length === 0) {907 this._onEmpty();908 }909 }910 return index;911 },912 _removeOldest: function() {913 this._removeCur(this._curSources[0]);914 },915 _pullQueue: function() {916 if (this._queue.length !== 0) {917 this._queue = cloneArray(this._queue);918 this._addToCur(this._queue.shift());919 }920 },921 _onActivation: function() {922 var sources = this._curSources923 , i;924 this._activating = true;925 for (i = 0; i < sources.length; i++) {926 if (this._active) {927 this._subscribe(sources[i]);928 }929 }930 this._activating = false;931 },932 _onDeactivation: function() {933 var sources = this._curSources934 , i;935 for (i = 0; i < sources.length; i++) {936 this._unsubscribe(sources[i]);937 }938 },939 _isEmpty: function() {940 return this._curSources.length === 0;941 },942 _onEmpty: function() {},943 _clear: function() {944 Stream.prototype._clear.call(this);945 this._queue = null;946 this._curSources = null;947 this._$handleSubAny = null;948 this._bindedEndHandlers = null;949 }950});951// .merge()952var MergeLike = {953 _onEmpty: function() {954 if (this._initialised) {955 this._send(END, null, this._activating);956 }957 }958};959function Merge(sources) {960 _AbstractPool.call(this);961 if (sources.length === 0) {962 this._send(END);963 } else {964 this._addAll(sources);965 }966 this._initialised = true;967}968inherit(Merge, _AbstractPool, extend({_name: 'merge'}, MergeLike));969Kefir.merge = function(obss) {970 return new Merge(obss);971};972Observable.prototype.merge = function(other) {973 return Kefir.merge([this, other]);974};975// .concat()976function Concat(sources) {977 _AbstractPool.call(this, {concurLim: 1, queueLim: -1});978 if (sources.length === 0) {979 this._send(END);980 } else {981 this._addAll(sources);982 }983 this._initialised = true;984}985inherit(Concat, _AbstractPool, extend({_name: 'concat'}, MergeLike));986Kefir.concat = function(obss) {987 return new Concat(obss);988};989Observable.prototype.concat = function(other) {990 return Kefir.concat([this, other]);991};992// .pool()993function Pool() {994 _AbstractPool.call(this);995}996Kefir.Pool = Pool;997inherit(Pool, _AbstractPool, {998 _name: 'pool',999 plug: function(obs) {1000 this._add(obs);1001 return this;1002 },1003 unplug: function(obs) {1004 this._remove(obs);1005 return this;1006 }1007});1008Kefir.pool = function() {1009 return new Pool();1010};1011// .bus()1012function Bus() {1013 _AbstractPool.call(this);1014}1015Kefir.Bus = Bus;1016inherit(Bus, _AbstractPool, {1017 _name: 'bus',1018 plug: function(obs) {1019 this._add(obs);1020 return this;1021 },1022 unplug: function(obs) {1023 this._remove(obs);1024 return this;1025 },1026 emit: function(x) {1027 this._send(VALUE, x);1028 return this;1029 },1030 error: function(x) {1031 this._send(ERROR, x);1032 return this;1033 },1034 end: function() {1035 this._send(END);1036 return this;1037 },1038 emitEvent: function(event) {1039 this._send(event.type, event.value);1040 }1041});1042Kefir.bus = function() {1043 return new Bus();1044};1045// .flatMap()1046function FlatMap(source, fn, options) {1047 _AbstractPool.call(this, options);1048 this._source = source;1049 this._fn = fn || id;1050 this._mainEnded = false;1051 this._lastCurrent = null;1052 var $ = this;1053 this._$handleMainSource = function(event) {1054 $._handleMainSource(event);1055 };1056}1057inherit(FlatMap, _AbstractPool, {1058 _onActivation: function() {1059 _AbstractPool.prototype._onActivation.call(this);1060 if (this._active) {1061 this._activating = true;1062 this._source.onAny(this._$handleMainSource);1063 this._activating = false;1064 }1065 },1066 _onDeactivation: function() {1067 _AbstractPool.prototype._onDeactivation.call(this);1068 this._source.offAny(this._$handleMainSource);1069 },1070 _handleMainSource: function(event) {1071 if (event.type === VALUE) {1072 if (!event.current || this._lastCurrent !== event.value) {1073 this._add(event.value, this._fn);1074 }1075 this._lastCurrent = event.value;1076 }1077 if (event.type === ERROR) {1078 this._send(ERROR, event.value, event.current);1079 }1080 if (event.type === END) {1081 if (this._isEmpty()) {1082 this._send(END, null, event.current);1083 } else {1084 this._mainEnded = true;1085 }1086 }1087 },1088 _onEmpty: function() {1089 if (this._mainEnded) {1090 this._send(END);1091 }1092 },1093 _clear: function() {1094 _AbstractPool.prototype._clear.call(this);1095 this._source = null;1096 this._lastCurrent = null;1097 this._$handleMainSource = null;1098 }1099});1100Observable.prototype.flatMap = function(fn) {1101 return new FlatMap(this, fn)1102 .setName(this, 'flatMap');1103};1104Observable.prototype.flatMapLatest = function(fn) {1105 return new FlatMap(this, fn, {concurLim: 1, drop: 'old'})1106 .setName(this, 'flatMapLatest');1107};1108Observable.prototype.flatMapFirst = function(fn) {1109 return new FlatMap(this, fn, {concurLim: 1})1110 .setName(this, 'flatMapFirst');1111};1112Observable.prototype.flatMapConcat = function(fn) {1113 return new FlatMap(this, fn, {queueLim: -1, concurLim: 1})1114 .setName(this, 'flatMapConcat');1115};1116Observable.prototype.flatMapConcurLimit = function(fn, limit) {1117 var result;1118 if (limit === 0) {1119 result = Kefir.never();1120 } else {1121 if (limit < 0) {1122 limit = -1;1123 }1124 result = new FlatMap(this, fn, {queueLim: -1, concurLim: limit});1125 }1126 return result.setName(this, 'flatMapConcurLimit');1127};1128// .zip()1129function Zip(sources, combinator) {1130 Stream.call(this);1131 if (sources.length === 0) {1132 this._send(END);1133 } else {1134 this._buffers = map(sources, function(source) {1135 return isArray(source) ? cloneArray(source) : [];1136 });1137 this._sources = map(sources, function(source) {1138 return isArray(source) ? Kefir.never() : source;1139 });1140 this._combinator = combinator ? spread(combinator, this._sources.length) : id;1141 this._aliveCount = 0;1142 this._bindedHandlers = Array(this._sources.length);1143 for (var i = 0; i < this._sources.length; i++) {1144 this._bindedHandlers[i] = this._bindHandleAny(i);1145 }1146 }1147}1148inherit(Zip, Stream, {1149 _name: 'zip',1150 _onActivation: function() {1151 var i, length = this._sources.length;1152 this._drainArrays();1153 this._aliveCount = length;1154 for (i = 0; i < length; i++) {1155 if (this._active) {1156 this._sources[i].onAny(this._bindedHandlers[i]);1157 }1158 }1159 },1160 _onDeactivation: function() {1161 for (var i = 0; i < this._sources.length; i++) {1162 this._sources[i].offAny(this._bindedHandlers[i]);1163 }1164 },1165 _emit: function(isCurrent) {1166 var values = new Array(this._buffers.length);1167 for (var i = 0; i < this._buffers.length; i++) {1168 values[i] = this._buffers[i].shift();1169 }1170 this._send(VALUE, this._combinator(values), isCurrent);1171 },1172 _isFull: function() {1173 for (var i = 0; i < this._buffers.length; i++) {1174 if (this._buffers[i].length === 0) {1175 return false;1176 }1177 }1178 return true;1179 },1180 _emitIfFull: function(isCurrent) {1181 if (this._isFull()) {1182 this._emit(isCurrent);1183 }1184 },1185 _drainArrays: function() {1186 while (this._isFull()) {1187 this._emit(true);1188 }1189 },1190 _bindHandleAny: function(i) {1191 var $ = this;1192 return function(event) {1193 $._handleAny(i, event);1194 };1195 },1196 _handleAny: function(i, event) {1197 if (event.type === VALUE) {1198 this._buffers[i].push(event.value);1199 this._emitIfFull(event.current);1200 }1201 if (event.type === ERROR) {1202 this._send(ERROR, event.value, event.current);1203 }1204 if (event.type === END) {1205 this._aliveCount--;1206 if (this._aliveCount === 0) {1207 this._send(END, null, event.current);1208 }1209 }1210 },1211 _clear: function() {1212 Stream.prototype._clear.call(this);1213 this._sources = null;1214 this._buffers = null;1215 this._combinator = null;1216 this._bindedHandlers = null;1217 }1218});1219Kefir.zip = function(sources, combinator) {1220 return new Zip(sources, combinator);1221};1222Observable.prototype.zip = function(other, combinator) {1223 return new Zip([this, other], combinator);1224};1225// .combine()1226function Combine(active, passive, combinator) {1227 Stream.call(this);1228 if (active.length === 0) {1229 this._send(END);1230 } else {1231 this._activeCount = active.length;1232 this._sources = concat(active, passive);1233 this._combinator = combinator ? spread(combinator, this._sources.length) : id;1234 this._aliveCount = 0;1235 this._currents = new Array(this._sources.length);1236 fillArray(this._currents, NOTHING);1237 this._activating = false;1238 this._emitAfterActivation = false;1239 this._endAfterActivation = false;1240 this._bindedHandlers = Array(this._sources.length);1241 for (var i = 0; i < this._sources.length; i++) {1242 this._bindedHandlers[i] = this._bindHandleAny(i);1243 }1244 }1245}1246inherit(Combine, Stream, {1247 _name: 'combine',1248 _onActivation: function() {1249 var length = this._sources.length,1250 i;1251 this._aliveCount = this._activeCount;1252 this._activating = true;1253 for (i = 0; i < length; i++) {1254 this._sources[i].onAny(this._bindedHandlers[i]);1255 }1256 this._activating = false;1257 if (this._emitAfterActivation) {1258 this._emitAfterActivation = false;1259 this._emitIfFull(true);1260 }1261 if (this._endAfterActivation) {1262 this._send(END, null, true);1263 }1264 },1265 _onDeactivation: function() {1266 var length = this._sources.length,1267 i;1268 for (i = 0; i < length; i++) {1269 this._sources[i].offAny(this._bindedHandlers[i]);1270 }1271 },1272 _emitIfFull: function(isCurrent) {1273 if (!contains(this._currents, NOTHING)) {1274 var combined = cloneArray(this._currents);1275 combined = this._combinator(combined);1276 this._send(VALUE, combined, isCurrent);1277 }1278 },1279 _bindHandleAny: function(i) {1280 var $ = this;1281 return function(event) {1282 $._handleAny(i, event);1283 };1284 },1285 _handleAny: function(i, event) {1286 if (event.type === VALUE) {1287 this._currents[i] = event.value;1288 if (i < this._activeCount) {1289 if (this._activating) {1290 this._emitAfterActivation = true;1291 } else {1292 this._emitIfFull(event.current);1293 }1294 }1295 }1296 if (event.type === ERROR) {1297 this._send(ERROR, event.value, event.current);1298 }1299 if (event.type === END) {1300 if (i < this._activeCount) {1301 this._aliveCount--;1302 if (this._aliveCount === 0) {1303 if (this._activating) {1304 this._endAfterActivation = true;1305 } else {1306 this._send(END, null, event.current);1307 }1308 }1309 }1310 }1311 },1312 _clear: function() {1313 Stream.prototype._clear.call(this);1314 this._sources = null;1315 this._currents = null;1316 this._combinator = null;1317 this._bindedHandlers = null;1318 }1319});1320Kefir.combine = function(active, passive, combinator) {1321 if (isFn(passive)) {1322 combinator = passive;1323 passive = null;1324 }1325 return new Combine(active, passive || [], combinator);1326};1327Observable.prototype.combine = function(other, combinator) {1328 return Kefir.combine([this, other], combinator);1329};1330// .sampledBy()1331Kefir.sampledBy = deprecated(1332 'Kefir.sampledBy()',1333 'Kefir.combine(active, passive, combinator)',1334 function(passive, active, combinator) {1335 // we need to flip `passive` and `active` in combinator function1336 var _combinator = combinator;1337 if (passive.length > 0) {1338 var passiveLength = passive.length;1339 _combinator = function() {1340 var args = circleShift(arguments, passiveLength);1341 return combinator ? apply(combinator, null, args) : args;1342 };1343 }1344 return new Combine(active, passive, _combinator).setName('sampledBy');1345 }1346);1347Observable.prototype.sampledBy = function(other, combinator) {1348 var _combinator;1349 if (combinator) {1350 _combinator = function(active, passive) {1351 return combinator(passive, active);1352 };1353 }1354 return new Combine([other], [this], _combinator || id2).setName(this, 'sampledBy');1355};1356function produceStream(StreamClass, PropertyClass) {1357 return function() {1358 return new StreamClass(this, arguments);1359 };1360}1361function produceProperty(StreamClass, PropertyClass) {1362 return function() {1363 return new PropertyClass(this, arguments);1364 };1365}1366// .toProperty()1367withOneSource('toProperty', {1368 _init: function(args) {1369 if (args.length > 0) {1370 this._send(VALUE, args[0]);1371 }1372 }1373}, {propertyMethod: produceProperty, streamMethod: produceProperty});1374// .changes()1375withOneSource('changes', {1376 _handleValue: function(x, isCurrent) {1377 if (!isCurrent) {1378 this._send(VALUE, x);1379 }1380 },1381 _handleError: function(x, isCurrent) {1382 if (!isCurrent) {1383 this._send(ERROR, x);1384 }1385 }1386}, {1387 streamMethod: function() {1388 return function() {1389 return this;1390 };1391 },1392 propertyMethod: produceStream1393});1394// .withHandler()1395withOneSource('withHandler', {1396 _init: function(args) {1397 this._handler = args[0];1398 this._forcedCurrent = false;1399 var $ = this;1400 this._emitter = {1401 emit: function(x) {1402 $._send(VALUE, x, $._forcedCurrent);1403 },1404 error: function(x) {1405 $._send(ERROR, x, $._forcedCurrent);1406 },1407 end: function() {1408 $._send(END, null, $._forcedCurrent);1409 },1410 emitEvent: function(e) {1411 $._send(e.type, e.value, $._forcedCurrent);1412 }1413 };1414 },1415 _free: function() {1416 this._handler = null;1417 this._emitter = null;1418 },1419 _handleAny: function(event) {1420 this._forcedCurrent = event.current;1421 this._handler(this._emitter, event);1422 this._forcedCurrent = false;1423 }1424});1425// .flatten(fn)1426withOneSource('flatten', {1427 _init: function(args) {1428 this._fn = args[0] ? args[0] : id;1429 },1430 _free: function() {1431 this._fn = null;1432 },1433 _handleValue: function(x, isCurrent) {1434 var xs = this._fn(x);1435 for (var i = 0; i < xs.length; i++) {1436 this._send(VALUE, xs[i], isCurrent);1437 }1438 }1439});1440// .transduce(transducer)1441var TRANSFORM_METHODS_OLD = {1442 step: 'step',1443 result: 'result'1444};1445var TRANSFORM_METHODS_NEW = {1446 step: '@@transducer/step',1447 result: '@@transducer/result'1448};1449function xformForObs(obs) {1450 function step(res, input) {1451 obs._send(VALUE, input, obs._forcedCurrent);1452 return null;1453 }1454 function result(res) {1455 obs._send(END, null, obs._forcedCurrent);1456 return null;1457 }1458 return {1459 step: step,1460 result: result,1461 '@@transducer/step': step,1462 '@@transducer/result': result1463 };1464}1465withOneSource('transduce', {1466 _init: function(args) {1467 var xf = args[0](xformForObs(this));1468 if (isFn(xf[TRANSFORM_METHODS_NEW.step]) && isFn(xf[TRANSFORM_METHODS_NEW.result])) {1469 this._transformMethods = TRANSFORM_METHODS_NEW;1470 } else if (isFn(xf[TRANSFORM_METHODS_OLD.step]) && isFn(xf[TRANSFORM_METHODS_OLD.result])) {1471 this._transformMethods = TRANSFORM_METHODS_OLD;1472 } else {1473 throw new Error('Unsuported transducers protocol');1474 }1475 this._xform = xf;1476 },1477 _free: function() {1478 this._xform = null;1479 this._transformMethods = null;1480 },1481 _handleValue: function(x, isCurrent) {1482 this._forcedCurrent = isCurrent;1483 if (this._xform[this._transformMethods.step](null, x) !== null) {1484 this._xform[this._transformMethods.result](null);1485 }1486 this._forcedCurrent = false;1487 },1488 _handleEnd: function(__, isCurrent) {1489 this._forcedCurrent = isCurrent;1490 this._xform[this._transformMethods.result](null);1491 this._forcedCurrent = false;1492 }1493});1494// .map(fn)1495withOneSource('map', {1496 _init: function(args) {1497 this._fn = args[0] || id;1498 },1499 _free: function() {1500 this._fn = null;1501 },1502 _handleValue: function(x, isCurrent) {1503 this._send(VALUE, this._fn(x), isCurrent);1504 }1505});1506// .mapErrors(fn)1507withOneSource('mapErrors', {1508 _init: function(args) {1509 this._fn = args[0] || id;1510 },1511 _free: function() {1512 this._fn = null;1513 },1514 _handleError: function(x, isCurrent) {1515 this._send(ERROR, this._fn(x), isCurrent);1516 }1517});1518// .errorsToValues(fn)1519function defaultErrorsToValuesHandler(x) {1520 return {1521 convert: true,1522 value: x1523 };1524}1525withOneSource('errorsToValues', {1526 _init: function(args) {1527 this._fn = args[0] || defaultErrorsToValuesHandler;1528 },1529 _free: function() {1530 this._fn = null;1531 },1532 _handleError: function(x, isCurrent) {1533 var result = this._fn(x);1534 var type = result.convert ? VALUE : ERROR;1535 var newX = result.convert ? result.value : x;1536 this._send(type, newX, isCurrent);1537 }1538});1539// .valuesToErrors(fn)1540function defaultValuesToErrorsHandler(x) {1541 return {1542 convert: true,1543 error: x1544 };1545}1546withOneSource('valuesToErrors', {1547 _init: function(args) {1548 this._fn = args[0] || defaultValuesToErrorsHandler;1549 },1550 _free: function() {1551 this._fn = null;1552 },1553 _handleValue: function(x, isCurrent) {1554 var result = this._fn(x);1555 var type = result.convert ? ERROR : VALUE;1556 var newX = result.convert ? result.error : x;1557 this._send(type, newX, isCurrent);1558 }1559});1560// .filter(fn)1561withOneSource('filter', {1562 _init: function(args) {1563 this._fn = args[0] || id;1564 },1565 _free: function() {1566 this._fn = null;1567 },1568 _handleValue: function(x, isCurrent) {1569 if (this._fn(x)) {1570 this._send(VALUE, x, isCurrent);1571 }1572 }1573});1574// .filterErrors(fn)1575withOneSource('filterErrors', {1576 _init: function(args) {1577 this._fn = args[0] || id;1578 },1579 _free: function() {1580 this._fn = null;1581 },1582 _handleError: function(x, isCurrent) {1583 if (this._fn(x)) {1584 this._send(ERROR, x, isCurrent);1585 }1586 }1587});1588// .takeWhile(fn)1589withOneSource('takeWhile', {1590 _init: function(args) {1591 this._fn = args[0] || id;1592 },1593 _free: function() {1594 this._fn = null;1595 },1596 _handleValue: function(x, isCurrent) {1597 if (this._fn(x)) {1598 this._send(VALUE, x, isCurrent);1599 } else {1600 this._send(END, null, isCurrent);1601 }1602 }1603});1604// .take(n)1605withOneSource('take', {1606 _init: function(args) {1607 this._n = args[0];1608 if (this._n <= 0) {1609 this._send(END);1610 }1611 },1612 _handleValue: function(x, isCurrent) {1613 this._n--;1614 this._send(VALUE, x, isCurrent);1615 if (this._n === 0) {1616 this._send(END, null, isCurrent);1617 }1618 }1619});1620// .skip(n)1621withOneSource('skip', {1622 _init: function(args) {1623 this._n = Math.max(0, args[0]);1624 },1625 _handleValue: function(x, isCurrent) {1626 if (this._n === 0) {1627 this._send(VALUE, x, isCurrent);1628 } else {1629 this._n--;1630 }1631 }1632});1633// .skipDuplicates([fn])1634withOneSource('skipDuplicates', {1635 _init: function(args) {1636 this._fn = args[0] || strictEqual;1637 this._prev = NOTHING;1638 },1639 _free: function() {1640 this._fn = null;1641 this._prev = null;1642 },1643 _handleValue: function(x, isCurrent) {1644 if (this._prev === NOTHING || !this._fn(this._prev, x)) {1645 this._prev = x;1646 this._send(VALUE, x, isCurrent);1647 }1648 }1649});1650// .skipWhile(fn)1651withOneSource('skipWhile', {1652 _init: function(args) {1653 this._fn = args[0] || id;1654 this._skip = true;1655 },1656 _free: function() {1657 this._fn = null;1658 },1659 _handleValue: function(x, isCurrent) {1660 if (!this._skip) {1661 this._send(VALUE, x, isCurrent);1662 return;1663 }1664 if (!this._fn(x)) {1665 this._skip = false;1666 this._fn = null;1667 this._send(VALUE, x, isCurrent);1668 }1669 }1670});1671// .diff(fn, seed)1672withOneSource('diff', {1673 _init: function(args) {1674 this._fn = args[0] || defaultDiff;1675 this._prev = args.length > 1 ? args[1] : NOTHING;1676 },1677 _free: function() {1678 this._prev = null;1679 this._fn = null;1680 },1681 _handleValue: function(x, isCurrent) {1682 if (this._prev !== NOTHING) {1683 this._send(VALUE, this._fn(this._prev, x), isCurrent);1684 }1685 this._prev = x;1686 }1687});1688// .scan(fn, seed)1689withOneSource('scan', {1690 _init: function(args) {1691 this._fn = args[0];1692 if (args.length > 1) {1693 this._send(VALUE, args[1], true);1694 }1695 },1696 _free: function() {1697 this._fn = null;1698 },1699 _handleValue: function(x, isCurrent) {1700 if (this._current !== NOTHING) {1701 x = this._fn(this._current, x);1702 }1703 this._send(VALUE, x, isCurrent);1704 }1705}, {streamMethod: produceProperty});1706// .reduce(fn, seed)1707withOneSource('reduce', {1708 _init: function(args) {1709 this._fn = args[0];1710 this._result = args.length > 1 ? args[1] : NOTHING;1711 },1712 _free: function() {1713 this._fn = null;1714 this._result = null;1715 },1716 _handleValue: function(x) {1717 this._result = (this._result === NOTHING) ? x : this._fn(this._result, x);1718 },1719 _handleEnd: function(__, isCurrent) {1720 if (this._result !== NOTHING) {1721 this._send(VALUE, this._result, isCurrent);1722 }1723 this._send(END, null, isCurrent);1724 }1725});1726// .mapEnd(fn)1727withOneSource('mapEnd', {1728 _init: function(args) {1729 this._fn = args[0];1730 },1731 _free: function() {1732 this._fn = null;1733 },1734 _handleEnd: function(__, isCurrent) {1735 this._send(VALUE, this._fn(), isCurrent);1736 this._send(END, null, isCurrent);1737 }1738});1739// .skipValue()1740withOneSource('skipValues', {1741 _handleValue: function() {}1742});1743// .skipError()1744withOneSource('skipErrors', {1745 _handleError: function() {}1746});1747// .skipEnd()1748withOneSource('skipEnd', {1749 _handleEnd: function() {}1750});1751// .endOnError()1752withOneSource('endOnError', {1753 _handleError: function(x, isCurrent) {1754 this._send(ERROR, x, isCurrent);1755 this._send(END, null, isCurrent);1756 }1757});1758// .slidingWindow(max[, min])1759withOneSource('slidingWindow', {1760 _init: function(args) {1761 this._max = args[0];1762 this._min = args[1] || 0;1763 this._buff = [];1764 },1765 _free: function() {1766 this._buff = null;1767 },1768 _handleValue: function(x, isCurrent) {1769 this._buff = slide(this._buff, x, this._max);1770 if (this._buff.length >= this._min) {1771 this._send(VALUE, this._buff, isCurrent);1772 }1773 }1774});1775// .bufferWhile([predicate], [options])1776withOneSource('bufferWhile', {1777 _init: function(args) {1778 this._fn = args[0] || id;1779 this._flushOnEnd = get(args[1], 'flushOnEnd', true);1780 this._buff = [];1781 },1782 _free: function() {1783 this._buff = null;1784 },1785 _flush: function(isCurrent) {1786 if (this._buff !== null && this._buff.length !== 0) {1787 this._send(VALUE, this._buff, isCurrent);1788 this._buff = [];1789 }1790 },1791 _handleValue: function(x, isCurrent) {1792 this._buff.push(x);1793 if (!this._fn(x)) {1794 this._flush(isCurrent);1795 }1796 },1797 _handleEnd: function(x, isCurrent) {1798 if (this._flushOnEnd) {1799 this._flush(isCurrent);1800 }1801 this._send(END, null, isCurrent);1802 }1803});1804// .debounce(wait, {immediate})1805withOneSource('debounce', {1806 _init: function(args) {1807 this._wait = Math.max(0, args[0]);1808 this._immediate = get(args[1], 'immediate', false);1809 this._lastAttempt = 0;1810 this._timeoutId = null;1811 this._laterValue = null;1812 this._endLater = false;1813 var $ = this;1814 this._$later = function() {1815 $._later();1816 };1817 },1818 _free: function() {1819 this._laterValue = null;1820 this._$later = null;1821 },1822 _handleValue: function(x, isCurrent) {1823 if (isCurrent) {1824 this._send(VALUE, x, isCurrent);1825 } else {1826 this._lastAttempt = now();1827 if (this._immediate && !this._timeoutId) {1828 this._send(VALUE, x);1829 }1830 if (!this._timeoutId) {1831 this._timeoutId = setTimeout(this._$later, this._wait);1832 }1833 if (!this._immediate) {1834 this._laterValue = x;1835 }1836 }1837 },1838 _handleEnd: function(__, isCurrent) {1839 if (isCurrent) {1840 this._send(END, null, isCurrent);1841 } else {1842 if (this._timeoutId && !this._immediate) {1843 this._endLater = true;1844 } else {1845 this._send(END);1846 }1847 }1848 },1849 _later: function() {1850 var last = now() - this._lastAttempt;1851 if (last < this._wait && last >= 0) {1852 this._timeoutId = setTimeout(this._$later, this._wait - last);1853 } else {1854 this._timeoutId = null;1855 if (!this._immediate) {1856 this._send(VALUE, this._laterValue);1857 this._laterValue = null;1858 }1859 if (this._endLater) {1860 this._send(END);1861 }1862 }1863 }1864});1865// .throttle(wait, {leading, trailing})1866withOneSource('throttle', {1867 _init: function(args) {1868 this._wait = Math.max(0, args[0]);1869 this._leading = get(args[1], 'leading', true);1870 this._trailing = get(args[1], 'trailing', true);1871 this._trailingValue = null;1872 this._timeoutId = null;1873 this._endLater = false;1874 this._lastCallTime = 0;1875 var $ = this;1876 this._$trailingCall = function() {1877 $._trailingCall();1878 };1879 },1880 _free: function() {1881 this._trailingValue = null;1882 this._$trailingCall = null;1883 },1884 _handleValue: function(x, isCurrent) {1885 if (isCurrent) {1886 this._send(VALUE, x, isCurrent);1887 } else {1888 var curTime = now();1889 if (this._lastCallTime === 0 && !this._leading) {1890 this._lastCallTime = curTime;1891 }1892 var remaining = this._wait - (curTime - this._lastCallTime);1893 if (remaining <= 0) {1894 this._cancelTraling();1895 this._lastCallTime = curTime;1896 this._send(VALUE, x);1897 } else if (this._trailing) {1898 this._cancelTraling();1899 this._trailingValue = x;1900 this._timeoutId = setTimeout(this._$trailingCall, remaining);1901 }1902 }1903 },1904 _handleEnd: function(__, isCurrent) {1905 if (isCurrent) {1906 this._send(END, null, isCurrent);1907 } else {1908 if (this._timeoutId) {1909 this._endLater = true;1910 } else {1911 this._send(END);1912 }1913 }1914 },1915 _cancelTraling: function() {1916 if (this._timeoutId !== null) {1917 clearTimeout(this._timeoutId);1918 this._timeoutId = null;1919 }1920 },1921 _trailingCall: function() {1922 this._send(VALUE, this._trailingValue);1923 this._timeoutId = null;1924 this._trailingValue = null;1925 this._lastCallTime = !this._leading ? 0 : now();1926 if (this._endLater) {1927 this._send(END);1928 }1929 }1930});1931// .delay()1932withOneSource('delay', {1933 _init: function(args) {1934 this._wait = Math.max(0, args[0]);1935 this._buff = [];1936 var $ = this;1937 this._$shiftBuff = function() {1938 $._send(VALUE, $._buff.shift());1939 };1940 },1941 _free: function() {1942 this._buff = null;1943 this._$shiftBuff = null;1944 },1945 _handleValue: function(x, isCurrent) {1946 if (isCurrent) {1947 this._send(VALUE, x, isCurrent);1948 } else {1949 this._buff.push(x);1950 setTimeout(this._$shiftBuff, this._wait);1951 }1952 },1953 _handleEnd: function(__, isCurrent) {1954 if (isCurrent) {1955 this._send(END, null, isCurrent);1956 } else {1957 var $ = this;1958 setTimeout(function() {1959 $._send(END);1960 }, this._wait);1961 }1962 }1963});1964// Kefir.fromBinder(fn)1965function FromBinder(fn) {1966 Stream.call(this);1967 this._fn = fn;1968 this._unsubscribe = null;1969}1970inherit(FromBinder, Stream, {1971 _name: 'fromBinder',1972 _onActivation: function() {1973 var $ = this1974 , isCurrent = true1975 , emitter = {1976 emit: function(x) {1977 $._send(VALUE, x, isCurrent);1978 },1979 error: function(x) {1980 $._send(ERROR, x, isCurrent);1981 },1982 end: function() {1983 $._send(END, null, isCurrent);1984 },1985 emitEvent: function(e) {1986 $._send(e.type, e.value, isCurrent);1987 }1988 };1989 this._unsubscribe = this._fn(emitter) || null;1990 // fix https://github.com/pozadi/kefir/issues/351991 if (!this._active && this._unsubscribe !== null) {1992 this._unsubscribe();1993 this._unsubscribe = null;1994 }1995 isCurrent = false;1996 },1997 _onDeactivation: function() {1998 if (this._unsubscribe !== null) {1999 this._unsubscribe();2000 this._unsubscribe = null;2001 }2002 },2003 _clear: function() {2004 Stream.prototype._clear.call(this);2005 this._fn = null;2006 }2007});2008Kefir.fromBinder = function(fn) {2009 return new FromBinder(fn);2010};2011// Kefir.emitter()2012function Emitter() {2013 Stream.call(this);2014}2015inherit(Emitter, Stream, {2016 _name: 'emitter',2017 emit: function(x) {2018 this._send(VALUE, x);2019 return this;2020 },2021 error: function(x) {2022 this._send(ERROR, x);2023 return this;2024 },2025 end: function() {2026 this._send(END);2027 return this;2028 },2029 emitEvent: function(event) {2030 this._send(event.type, event.value);2031 }2032});2033Kefir.emitter = function() {2034 return new Emitter();2035};2036Kefir.Emitter = Emitter;2037// Kefir.never()2038var neverObj = new Stream();2039neverObj._send(END);2040neverObj._name = 'never';2041Kefir.never = function() {2042 return neverObj;2043};2044// Kefir.constant(x)2045function Constant(x) {2046 Property.call(this);2047 this._send(VALUE, x);2048 this._send(END);2049}2050inherit(Constant, Property, {2051 _name: 'constant'2052});2053Kefir.constant = function(x) {2054 return new Constant(x);2055};2056// Kefir.constantError(x)2057function ConstantError(x) {2058 Property.call(this);2059 this._send(ERROR, x);2060 this._send(END);2061}2062inherit(ConstantError, Property, {2063 _name: 'constantError'2064});2065Kefir.constantError = function(x) {2066 return new ConstantError(x);2067};2068// Kefir.repeat(generator)2069function Repeat(generator) {2070 Stream.call(this);2071 this._generator = generator;2072 this._source = null;2073 this._inLoop = false;2074 this._activating = false;2075 this._iteration = 0;2076 var $ = this;2077 this._$handleAny = function(event) {2078 $._handleAny(event);2079 };2080}2081inherit(Repeat, Stream, {2082 _name: 'repeat',2083 _handleAny: function(event) {2084 if (event.type === END) {2085 this._source = null;2086 this._startLoop();2087 } else {2088 this._send(event.type, event.value, this._activating);2089 }2090 },2091 _startLoop: function() {2092 if (!this._inLoop) {2093 this._inLoop = true;2094 while (this._source === null && this._alive && this._active) {2095 this._source = this._generator(this._iteration++);2096 if (this._source) {2097 this._source.onAny(this._$handleAny);2098 } else {2099 this._send(END);2100 }2101 }2102 this._inLoop = false;2103 }2104 },2105 _onActivation: function() {2106 this._activating = true;2107 if (this._source) {2108 this._source.onAny(this._$handleAny);2109 } else {2110 this._startLoop();2111 }2112 this._activating = false;2113 },2114 _onDeactivation: function() {2115 if (this._source) {2116 this._source.offAny(this._$handleAny);2117 }2118 },2119 _clear: function() {2120 Stream.prototype._clear.call(this);2121 this._generator = null;2122 this._source = null;2123 this._$handleAny = null;2124 }2125});2126Kefir.repeat = function(generator) {2127 return new Repeat(generator);2128};2129// .setName2130Observable.prototype.setName = function(sourceObs, selfName /* or just selfName */) {2131 this._name = selfName ? sourceObs._name + '.' + selfName : sourceObs;2132 return this;2133};2134// .mapTo2135Observable.prototype.mapTo = deprecated(2136 '.mapTo()',2137 '.map(() => value)',2138 function(value) {2139 return this.map(function() {2140 return value;2141 }).setName(this, 'mapTo');2142 }2143);2144// .pluck2145Observable.prototype.pluck = deprecated(2146 '.pluck()',2147 '.map((v) => v.prop)',2148 function(propertyName) {2149 return this.map(function(x) {2150 return x[propertyName];2151 }).setName(this, 'pluck');2152 }2153);2154// .invoke2155Observable.prototype.invoke = deprecated(2156 '.invoke()',2157 '.map((v) => v.method())',2158 function(methodName /*, arg1, arg2... */) {2159 var args = rest(arguments, 1);2160 return this.map(args ?2161 function(x) {2162 return apply(x[methodName], x, args);2163 } :2164 function(x) {2165 return x[methodName]();2166 }2167 ).setName(this, 'invoke');2168 }2169);2170// .timestamp2171Observable.prototype.timestamp = deprecated(2172 '.timestamp()',2173 '.map((v) => {value: v, time: (new Date).getTime()})',2174 function() {2175 return this.map(function(x) {2176 return {value: x, time: now()};2177 }).setName(this, 'timestamp');2178 }2179);2180// .tap2181Observable.prototype.tap = deprecated(2182 '.tap()',2183 '.map((v) => {fn(v); return v})',2184 function(fn) {2185 return this.map(function(x) {2186 fn(x);2187 return x;2188 }).setName(this, 'tap');2189 }2190);2191// .and2192Kefir.and = deprecated(2193 'Kefir.and()',2194 'Kefir.combine([a, b], (a, b) => a && b)',2195 function(observables) {2196 return Kefir.combine(observables, and).setName('and');2197 }2198);2199Observable.prototype.and = deprecated(2200 '.and()',2201 '.combine(other, (a, b) => a && b)',2202 function(other) {2203 return this.combine(other, and).setName('and');2204 }2205);2206// .or2207Kefir.or = deprecated(2208 'Kefir.or()',2209 'Kefir.combine([a, b], (a, b) => a || b)',2210 function(observables) {2211 return Kefir.combine(observables, or).setName('or');2212 }2213);2214Observable.prototype.or = deprecated(2215 '.or()',2216 '.combine(other, (a, b) => a || b)',2217 function(other) {2218 return this.combine(other, or).setName('or');2219 }2220);2221// .not2222Observable.prototype.not = deprecated(2223 '.not()',2224 '.map(v => !v)',2225 function() {2226 return this.map(not).setName(this, 'not');2227 }2228);2229// .awaiting2230Observable.prototype.awaiting = function(other) {2231 return Kefir.merge([2232 this.mapTo(true),2233 other.mapTo(false)2234 ]).skipDuplicates().toProperty(false).setName(this, 'awaiting');2235};2236// .fromCallback2237Kefir.fromCallback = function(callbackConsumer) {2238 var called = false;2239 return Kefir.fromBinder(function(emitter) {2240 if (!called) {2241 callbackConsumer(function(x) {2242 emitter.emit(x);2243 emitter.end();2244 });2245 called = true;2246 }2247 }).setName('fromCallback');2248};2249// .fromNodeCallback2250Kefir.fromNodeCallback = function(callbackConsumer) {2251 var called = false;2252 return Kefir.fromBinder(function(emitter) {2253 if (!called) {2254 callbackConsumer(function(error, x) {2255 if (error) {2256 emitter.error(error);2257 } else {2258 emitter.emit(x);2259 }2260 emitter.end();2261 });2262 called = true;2263 }2264 }).setName('fromNodeCallback');2265};2266// .fromPromise2267Kefir.fromPromise = function(promise) {2268 var called = false;2269 return Kefir.fromBinder(function(emitter) {2270 if (!called) {2271 var onValue = function(x) {2272 emitter.emit(x);2273 emitter.end();2274 };2275 var onError = function(x) {2276 emitter.error(x);2277 emitter.end();2278 };2279 var _promise = promise.then(onValue, onError);2280 // prevent promise/A+ libraries like Q to swallow exceptions2281 if (_promise && isFn(_promise.done)) {2282 _promise.done();2283 }2284 called = true;2285 }2286 }).toProperty().setName('fromPromise');2287};2288// .fromSubUnsub2289Kefir.fromSubUnsub = function(sub, unsub, transformer) {2290 return Kefir.fromBinder(function(emitter) {2291 var handler = transformer ? function() {2292 emitter.emit(apply(transformer, this, arguments));2293 } : emitter.emit;2294 sub(handler);2295 return function() {2296 unsub(handler);2297 };2298 });2299};2300// .fromEvent2301var subUnsubPairs = [2302 ['addEventListener', 'removeEventListener'],2303 ['addListener', 'removeListener'],2304 ['on', 'off']2305];2306Kefir.fromEvent = function(target, eventName, transformer) {2307 var pair, sub, unsub;2308 for (var i = 0; i < subUnsubPairs.length; i++) {2309 pair = subUnsubPairs[i];2310 if (isFn(target[pair[0]]) && isFn(target[pair[1]])) {2311 sub = pair[0];2312 unsub = pair[1];2313 break;2314 }2315 }2316 if (sub === undefined) {2317 throw new Error('target don\'t support any of ' +2318 'addEventListener/removeEventListener, addListener/removeListener, on/off method pair');2319 }2320 return Kefir.fromSubUnsub(2321 function(handler) {2322 target[sub](eventName, handler);2323 },2324 function(handler) {2325 target[unsub](eventName, handler);2326 },2327 transformer2328 ).setName('fromEvent');2329};2330var withTwoSourcesAndBufferMixin = {2331 _init: function(args) {2332 this._buff = [];2333 this._flushOnEnd = get(args[0], 'flushOnEnd', true);2334 },2335 _free: function() {2336 this._buff = null;2337 },2338 _flush: function(isCurrent) {2339 if (this._buff !== null && this._buff.length !== 0) {2340 this._send(VALUE, this._buff, isCurrent);2341 this._buff = [];2342 }2343 },2344 _handlePrimaryEnd: function(__, isCurrent) {2345 if (this._flushOnEnd) {2346 this._flush(isCurrent);2347 }2348 this._send(END, null, isCurrent);2349 }2350};2351withTwoSources('bufferBy', extend({2352 _onActivation: function() {2353 this._primary.onAny(this._$handlePrimaryAny);2354 if (this._alive && this._secondary !== null) {2355 this._secondary.onAny(this._$handleSecondaryAny);2356 }2357 },2358 _handlePrimaryValue: function(x, isCurrent) {2359 this._buff.push(x);2360 },2361 _handleSecondaryValue: function(x, isCurrent) {2362 this._flush(isCurrent);2363 },2364 _handleSecondaryEnd: function(x, isCurrent) {2365 if (!this._flushOnEnd) {2366 this._send(END, null, isCurrent);2367 }2368 }2369}, withTwoSourcesAndBufferMixin));2370withTwoSources('bufferWhileBy', extend({2371 _handlePrimaryValue: function(x, isCurrent) {2372 this._buff.push(x);2373 if (this._lastSecondary !== NOTHING && !this._lastSecondary) {2374 this._flush(isCurrent);2375 }2376 },2377 _handleSecondaryEnd: function(x, isCurrent) {2378 if (!this._flushOnEnd && (this._lastSecondary === NOTHING || this._lastSecondary)) {2379 this._send(END, null, isCurrent);2380 }2381 }2382}, withTwoSourcesAndBufferMixin));2383withTwoSources('filterBy', {2384 _handlePrimaryValue: function(x, isCurrent) {2385 if (this._lastSecondary !== NOTHING && this._lastSecondary) {2386 this._send(VALUE, x, isCurrent);2387 }2388 },2389 _handleSecondaryEnd: function(__, isCurrent) {2390 if (this._lastSecondary === NOTHING || !this._lastSecondary) {2391 this._send(END, null, isCurrent);2392 }2393 }2394});2395withTwoSources('skipUntilBy', {2396 _handlePrimaryValue: function(x, isCurrent) {2397 if (this._lastSecondary !== NOTHING) {2398 this._send(VALUE, x, isCurrent);2399 }2400 },2401 _handleSecondaryEnd: function(__, isCurrent) {2402 if (this._lastSecondary === NOTHING) {2403 this._send(END, null, isCurrent);2404 }2405 }2406});2407withTwoSources('takeUntilBy', {2408 _handleSecondaryValue: function(x, isCurrent) {2409 this._send(END, null, isCurrent);2410 }2411});2412withTwoSources('takeWhileBy', {2413 _handlePrimaryValue: function(x, isCurrent) {2414 if (this._lastSecondary !== NOTHING) {2415 this._send(VALUE, x, isCurrent);2416 }2417 },2418 _handleSecondaryValue: function(x, isCurrent) {2419 this._lastSecondary = x;2420 if (!this._lastSecondary) {2421 this._send(END, null, isCurrent);2422 }2423 },2424 _handleSecondaryEnd: function(__, isCurrent) {2425 if (this._lastSecondary === NOTHING) {2426 this._send(END, null, isCurrent);2427 }2428 }2429});2430withTwoSources('skipWhileBy', {2431 _init: function() {2432 this._hasFalseyFromSecondary = false;2433 },2434 _handlePrimaryValue: function(x, isCurrent) {2435 if (this._hasFalseyFromSecondary) {2436 this._send(VALUE, x, isCurrent);2437 }2438 },2439 _handleSecondaryValue: function(x, isCurrent) {2440 this._hasFalseyFromSecondary = this._hasFalseyFromSecondary || !x;2441 },2442 _handleSecondaryEnd: function(__, isCurrent) {2443 if (!this._hasFalseyFromSecondary) {2444 this._send(END, null, isCurrent);2445 }2446 }2447});2448 if (typeof define === 'function' && define.amd) {2449 define([], function() {2450 return Kefir;2451 });2452 global.Kefir = Kefir;2453 } else if (typeof module === "object" && typeof exports === "object") {2454 module.exports = Kefir;2455 Kefir.Kefir = Kefir;2456 } else {2457 global.Kefir = Kefir;2458 }...
client.unit.js
Source:client.unit.js
...37 sandbox.stub(client, '_deserializeResponseArguments').returns(38 [null, ['contact']]39 );40 var args = {};41 client._send('getConnectedContacts', args, function(err, result) {42 if (err) {43 return done(err);44 }45 expect(request.post.args[0][0]).to.equal('http://localhost:8080');46 expect(request.post.args[0][1]).to.deep.equal({47 auth: {48 username: 'user',49 password: 'pass'50 },51 json: {52 id: '445c33c0-527a-4bcc-af73-d58758d6eaa7',53 method: 'getConnectedContacts',54 params: {}55 },56 timeout: 9000057 });58 expect(result).to.deep.equal(['contact']);59 done();60 });61 });62 it('will handle error from request', function(done) {63 sandbox.stub(request, 'post').callsArgWith(2, new Error('test'));64 var client = complex.createClient();65 var args = {};66 client._send('getConnectedContacts', args, function(err) {67 expect(err).to.be.instanceOf(Error);68 done();69 });70 });71 it('will give error if status code != 200', function(done) {72 var res = { statusCode: 500 };73 var body = { error: { message: 'rabbits are afk'} };74 sandbox.stub(request, 'post').callsArgWith(2, null, res, body);75 var client = complex.createClient();76 var args = {};77 client._send('getConnectedContacts', args, function(err) {78 expect(err).to.be.instanceOf(Error);79 expect(err.message).to.equal('rabbits are afk');80 done();81 });82 });83 it('status code != 200 (with error as body)', function(done) {84 var res = { statusCode: 500 };85 var body = { message: 'rabbits are afk'};86 sandbox.stub(request, 'post').callsArgWith(2, null, res, body);87 var client = complex.createClient();88 var args = {};89 client._send('getConnectedContacts', args, function(err) {90 expect(err).to.be.instanceOf(Error);91 expect(err.message).to.equal('rabbits are afk');92 done();93 });94 });95 it('status code != 200 (missing body)', function(done) {96 var res = { statusCode: 500 };97 var body = {};98 sandbox.stub(request, 'post').callsArgWith(2, null, res, body);99 var client = complex.createClient();100 var args = {};101 client._send('getConnectedContacts', args, function(err) {102 expect(err).to.be.instanceOf(Error);103 expect(err.message).to.equal('Failed to complete work, reason unknown');104 done();105 });106 });107 });108 describe('#_deserializeResponseArguments', function() {109 it('getStorageOffer', function() {110 var client = complex.createClient();111 var method = 'getStorageOffer';112 var args = [113 null,114 {115 address: '127.0.0.1',...
backend.js
Source:backend.js
...24 }25 });26 };27 var _register = function(email, password, event_id, callback){28 _send(29 '/login/register',30 {31 email: email,32 password: password,33 lang: Pard.Options.language(),34 event_id: event_id35 },36 callback37 );38 };39 var _login = function(email, password, callback){40 _send(41 '/login/login',42 {43 email: email,44 password: password45 },46 callback47 );48 };49 var _passwordRecovery = function(email, callback){50 _send(51 '/login/forgotten_password',52 {53 email: email54 },55 callback56 );57 };58 var _logout = function(callback){59 _send(60 '/login/logout',61 {},62 callback63 );64 };65 var _modifyPassword = function(password, callback){66 _send(67 '/users/modify_password',68 {69 password: password70 },71 callback72 );73 };74 var _modifyLang = function(lang, callback){75 _send(76 '/modify_lang',77 {78 lang: lang79 },80 callback81 );82 };83 var _createProfile = function(form, callback){84 console.log(form)85 _send(86 '/users/create_profile',87 form,88 callback89 );90 };91 var _modifyProfile = function(form, callback){92 _send(93 '/users/modify_profile',94 form,95 callback96 );97 };98 var _sendArtistProposal = function(form, callback){99 _send(100 '/users/send_artist_proposal',101 form,102 callback103 );104 };105 var _sendSpaceProposal = function(form, callback){106 _send(107 '/users/send_space_proposal',108 form,109 callback110 );111 };112 var _sendArtistOwnProposal = function(form, callback){113 _send(114 '/users/send_artist_own_proposal',115 form,116 callback117 );118 };119 var _sendSpaceOwnProposal = function(form, callback){120 _send(121 '/users/send_space_own_proposal',122 form,123 callback124 );125 };126 var _createProduction = function(form, callback){127 _send(128 '/users/create_production',129 form,130 callback131 );132 };133 var _modifyProduction = function(form, callback){134 _send(135 '/users/modify_production',136 form,137 callback138 );139 };140 var _createPerformances = function(form, callback){141 _send(142 '/users/create_performances',143 form,144 callback145 );146 };147 var _modifyPerformances = function(form, callback){148 _send(149 '/users/modify_performances',150 form,151 callback152 );153 };154 var _deletePerformances = function(form, callback){155 _send(156 '/users/delete_performances',157 form,158 callback159 );160 };161 var _searchProfiles = function(tags, shown, event_id, callback){162 _send(163 '/search/results',164 {165 query: tags,166 shown: shown,167 event_id: event_id,168 lang: Pard.Options.language()169 },170 callback171 );172 };173 var _searchProgram = function(event_id, tags, filters, date, time, callback){174 _send(175 '/search/results_program',176 {177 event_id: event_id,178 query: tags,179 filters: filters,180 date: date,181 time: time,182 lang: Pard.Options.language()183 },184 callback185 );186 };187 var _searchProgramNow = function(event_id, callback){188 _send(189 '/search/program_now',190 {191 event_id: event_id192 },193 callback194 );195 };196 var _deleteArtistProposal = function(proposal_id, event_id, callback){197 _send(198 '/users/delete_artist_proposal',199 {200 proposal_id: proposal_id,201 event_id: event_id202 },203 callback204 );205 };206 var _deleteSpaceProposal = function(proposal_id, event_id, callback){207 _send(208 '/users/delete_space_proposal',209 {210 proposal_id: proposal_id,211 event_id: event_id212 },213 callback214 );215 };216 var _deleteProduction = function(production_id, callback){217 _send(218 '/users/delete_production',219 {220 production_id: production_id221 },222 callback223 );224 };225 var _deleteProfile = function(profile_id, callback){226 _send(227 '/users/delete_profile',228 {229 profile_id: profile_id230 },231 callback232 );233 };234 var _deleteUser = function(callback){235 _send(236 '/users/delete_user',237 {},238 callback239 );240 };241 var _amendArtistProposal = function(proposal_id, event_id, call_id, amend, callback){242 _send(243 '/users/amend_artist_proposal',244 {245 proposal_id: proposal_id,246 event_id: event_id,247 call_id: call_id,248 amend: amend249 },250 callback251 );252 };253 var _amendSpaceProposal = function(proposal_id, event_id, call_id, amend, callback){254 _send(255 '/users/amend_space_proposal',256 {257 proposal_id: proposal_id,258 event_id: event_id,259 call_id: call_id,260 amend: amend261 },262 callback263 );264 };265 var _modifyArtistProposal = function(form, callback){266 _send(267 '/users/modify_artist_proposal',268 form,269 callback270 );271 };272 var _modifySpaceProposal = function(form, callback){273 _send(274 '/users/modify_space_proposal',275 form,276 callback277 );278 };279 var _addWhitelist = function(event_id, name_email, email, callback){280 _send(281 '/users/add_whitelist',282 {283 event_id: event_id,284 name_email: name_email,285 email: email286 },287 callback288 );289 };290 var _deleteWhitelist = function(event_id, email, callback){291 _send(292 '/users/delete_whitelist',293 {294 event_id: event_id,295 email: email296 },297 callback298 );299 };300 var _saveProgram = function(event_id, program, order, callback){301 _send(302 '/users/save_program',303 {304 event_id: event_id,305 program: program,306 order: order307 },308 callback309 );310 };311 var _getCallForms = function(call_id, callback){312 _send(313 '/forms',314 {315 call_id: call_id,316 lang: Pard.Options.language()317 },318 callback319 );320 };321 var _listProfiles = function(callback){322 _send(323 '/users/list_profiles',324 {},325 callback326 );327 }328 var _events = function(callback){329 _send(330 '/events',331 {},332 callback333 );334 }335 var _feedback = function(name, email, message, callback){336 _send(337 '/feedback',338 {339 name: name,340 email: email,341 message: message342 },343 callback344 ); 345 }346 var _techSupport = function(name, email, subject, profile, browser, message, callback){347 _send(348 '/techSupport',349 {350 name: name,351 email: email,352 subject: subject,353 profile: profile,354 browser: browser,355 message: message356 },357 callback358 ); 359 }360 var _business = function(form, callback){361 _send(362 '/business',363 form,364 callback365 ); 366 }367 var _header = function(callback){368 _send(369 '/users/header',370 {},371 callback372 ); 373 }374 var _saveOrder = function(event_id, order, callback){375 _send(376 '/users/space_order',377 {378 event_id: event_id,379 order: order380 },381 callback382 ); 383 }384 var _publish = function(event_id, callback){385 _send(386 '/users/publish',387 {388 event_id: event_id389 },390 callback391 ); 392 }393 var _eventManager = function(event_id, callback){394 _send(395 '/users/event_manager',396 {397 event_id: event_id,398 lang: Pard.Options.language()399 },400 callback401 ); 402 }403 var _checkName = function(name, callback){404 _send(405 '/users/check_name',406 {407 name: name408 },409 callback410 ); 411 }412 var _checkSlug = function(slug, callback){413 _send(414 '/users/check_slug',415 {416 slug: slug417 },418 callback419 ); 420 }421 var _createSlug = function(slug, event_id, callback){422 _send(423 '/users/create_slug',424 {425 slug: slug,426 event_id: event_id427 },428 callback429 ); 430 }431 return {432 register: _register,433 login: _login,434 passwordRecovery: _passwordRecovery,435 logout: _logout,436 modifyPassword: _modifyPassword,...
authentication.service.js
Source:authentication.service.js
...27 service.askResetTpass = askResetTpass;28 service.SERVER = SERVER;29 return service;30 function Askcode(params) {31 return _send("askWithdrawalAddressVerify",params);32 }33 // calls a function to validate JSON token34 function Ask(request_type,number) {35 if(number){36 return _send("ask", {37 request_type: request_type,38 bank_id:number39 });40 }else{41 return _send("ask", {request_type: request_type});42 }43 }44 //æ¾åå¯ç è·åéªè¯ç 45 function askVerification(params) {46 return _send("ask",params);47 }48 function AskWithdrawal() {49 return service.Ask('WITHD');50 }51 function AskLock() {52 return service.Ask('LOCK');53 }54 function AskEmail(email) {55 return _send("ask", {56 request_type: 'ADMAI',57 email: email58 });59 }60 function AskTPass(tpass) {61 return _send("askSetTpass", {});62 }63 function ASKLOGINPass(params) {64 return _send("askLoginVerification", params);65 }66 function askLoginPhoneVer(params) {67 return _send("askLoginPhoneVerification", params);68 }69 function answerLoginVerification(emailList) {70 return _send("answerLoginVerification", emailList);71 }72 function askResetTpass() {73 return _send("askResetTpass", {});74 }75 function AskChangeEmail() {76 return _send("ask", {77 request_type: 'CHMAI'78 });79 }80 function AskPhone(phone) {81 return _send("ask", {82 request_type: 'ADPHO',83 phone: phone84 });85 }86 function AskChangePhone() {87 return _send("ask", {88 request_type: 'CHPHO'89 });90 }91 function AskResetPasswordEmail(email){92 return _send("ask", {93 request_type: 'FORGO',94 email: email95 });96 }97 function AskResetPasswordPhone(phone){98 return _send("ask", {99 request_type: 'FORGO',100 phone: phone101 });102 }103 function Answer(params) {104 return _send("answer", params);105 }106 function answerVerification(params) {107 return _send("answerVerification", params);108 }109 // function get/returns token, and test if successful110 // method: get111 // params: username, password, etc112 function _send(method, params) {113 var headers={};114 if(typeof params !== 'undefined') {115 if($translate.use() == 'zh_TW') {116 params.language='zh'117 }else {118 params.language='en'119 }120 // params.language=121 } else{122 params='';123 }124 if($rootScope.globals && $rootScope.globals.token){125 headers={ 'x-access-token': $rootScope.globals.token};126 }...
connection.js
Source:connection.js
...104 startup(config) {105 this.stream.write(serialize.startup(config))106 }107 cancel(processID, secretKey) {108 this._send(serialize.cancel(processID, secretKey))109 }110 password(password) {111 this._send(serialize.password(password))112 }113 sendSASLInitialResponseMessage(mechanism, initialResponse) {114 this._send(serialize.sendSASLInitialResponseMessage(mechanism, initialResponse))115 }116 sendSCRAMClientFinalMessage(additionalData) {117 this._send(serialize.sendSCRAMClientFinalMessage(additionalData))118 }119 _send(buffer) {120 if (!this.stream.writable) {121 return false122 }123 return this.stream.write(buffer)124 }125 query(text) {126 this._send(serialize.query(text))127 }128 // send parse message129 parse(query) {130 this._send(serialize.parse(query))131 }132 // send bind message133 bind(config) {134 this._send(serialize.bind(config))135 }136 // send execute message137 execute(config) {138 this._send(serialize.execute(config))139 }140 flush() {141 if (this.stream.writable) {142 this.stream.write(flushBuffer)143 }144 }145 sync() {146 this._ending = true147 this._send(flushBuffer)148 this._send(syncBuffer)149 }150 ref() {151 this.stream.ref()152 }153 unref() {154 this.stream.unref()155 }156 end() {157 // 0x58 = 'X'158 this._ending = true159 if (!this._connecting || !this.stream.writable) {160 this.stream.end()161 return162 }163 return this.stream.write(endBuffer, () => {164 this.stream.end()165 })166 }167 close(msg) {168 this._send(serialize.close(msg))169 }170 describe(msg) {171 this._send(serialize.describe(msg))172 }173 sendCopyFromChunk(chunk) {174 this._send(serialize.copyData(chunk))175 }176 endCopyFrom() {177 this._send(serialize.copyDone())178 }179 sendCopyFail(msg) {180 this._send(serialize.copyFail(msg))181 }182}...
index.js
Source:index.js
...66 return this._peerSubscribing[id] || this._peerSubscribing['*']67}68Protocol.prototype.handshake = function (opts, cb) {69 opts.protocol = Protocol.version70 this._send(0, '', JSON.stringify(opts), parse(cb))71}72Protocol.prototype.add = function (id, service, cb) {73 this._send(1, id, JSON.stringify(service), cb)74}75Protocol.prototype.update = function (id, service, cb) {76 this._send(2, id, JSON.stringify(service), cb)77}78Protocol.prototype.remove = function (id, cb) {79 this._send(3, id, null, cb)80}81Protocol.prototype.list = function (cb) {82 this._send(4, '', null, parse(cb))83}84Protocol.prototype.ps = function (cb) {85 this._send(5, '', null, parse(cb))86}87Protocol.prototype.start = function (id, cb) {88 this._send(6, id, null, cb)89}90Protocol.prototype.stop = function (id, cb) {91 this._send(7, id, null, cb)92}93Protocol.prototype.restart = function (id, cb) {94 this._send(8, id, null, cb)95}96Protocol.prototype.sync = function (id, service, cb) {97 this._send(9, id, JSON.stringify(service), cb)98}99Protocol.prototype.subscribe = function (id, cb) {100 if (typeof id === 'function') return this.subscribe(null, id)101 if (!id) id = '*'102 this._amSubscribing[id] = true103 this._send(10, id, null, cb)104}105Protocol.prototype.unsubscribe = function (id, cb) {106 if (typeof id === 'function') return this.unsubscribe(null, id)107 if (!id) id = '*'108 delete this._amSubscribing[id]109 this._send(11, id, null, cb)110}111Protocol.prototype.stdout = function (id, origin, data) {112 this._send(12, id + '@' + origin, data)113}114Protocol.prototype.stderr = function (id, origin, data) {115 this._send(13, id + '@' + origin, data)116}117Protocol.prototype.spawn = function (id, origin, pid) {118 this._send(14, id + '@' + origin, JSON.stringify(pid))119}120Protocol.prototype.exit = function (id, origin, code) {121 this._send(15, id + '@' + origin, JSON.stringify(code))122}123Protocol.prototype.get = function (id, cb) {124 this._send(16, id, null, parse(cb))125}126Protocol.prototype._send = function (opcode, id, payload, cb) {127 if (!payload) payload = empty128 if (!Buffer.isBuffer(payload)) payload = new Buffer(payload)129 var idLen = Buffer.byteLength(id)130 var message = new Buffer(3 + idLen + payload.length)131 message[0] = opcode132 message.writeUInt16LE(idLen, 1)133 message.write(id, 3)134 if (payload.length) payload.copy(message, 3 + idLen)135 this.send(message, cb)136}...
WebWorker.js
Source:WebWorker.js
...50 testConstructor: function() {51 this.assertInstance(this._worker, qx.bom.WebWorker);52 },53 testMessageEvent: function() {54 this._send("message", function(mess, e) {55 this.assertIdentical(mess, e.getData());56 });57 },58 testErrorEvent: function() {59 var message = "error";60 this._worker.addListener("error", function(e) {61 this.resume(function() {62 this.assertTrue(/error/.test(e.getData()));63 }, this);64 }, this);65 this._worker.postMessage(message);66 this.wait();67 },68 testPostMessageWithNumber: function() {69 this._send(1, function(mess, e) {70 this.assertIdentical(mess, e.getData());71 });72 },73 testPostMessageWithBoolean: function() {74 this._send(true, function(mess, e) {75 this.assertIdentical(mess, e.getData());76 });77 },78 testPostMessageWithNull: function() {79 this._send(null, function(mess, e) {80 this.assertIdentical(mess, e.getData());81 });82 },83 testPostMessageWithObject: function() {84 //this._send({a:"1", b:2, c:3});85 this._send({a:"1", b:2, c:true}, function(mess, e) {86 this.assertIdentical(mess.a, e.getData().a);87 this.assertIdentical(mess.b, e.getData().b);88 this.assertIdentical(mess.c, e.getData().c);89 });90 },91 testPostMessageWithArray: function() {92 //this._send(["1", 2, true]);93 this._send(["1", 2, true], function(mess, e) {94 this.assertIdentical(mess[0], e.getData()[0]);95 this.assertIdentical(mess[1], e.getData()[1]);96 this.assertIdentical(mess[2], e.getData()[2]);97 });98 }99 }...
myworker.js
Source:myworker.js
2var _myeval = eval;3var _flag = 0;4var workshop = (typeof workshop === "undefined")?{}:workshop;5workshop.plot = function(p,o,s) {6 _send(JSON.stringify({k:workshop.current.k,n:workshop.current.n,p:p,o:o,s:s}));7}8workshop.html = function(o) {9 _send(JSON.stringify({k:workshop.current.k,n:workshop.current.n,o:o}));10}11var console;12if(!console) console = {};13console.log = function() {14 var k,n=arguments.length;15 var _x = workshop.current;16 if(_x) {17 for(k=0;k<n;k++) {18 if(k>0) _send(JSON.stringify({k:_x.k,n:_x.n,o:' '}));19 _send(JSON.stringify({k:_x.k,n:_x.n,o:numeric.prettyPrint(arguments[k])}));20 }21 }22 _send(JSON.stringify({k:_x.k,n:_x.n,o:'\n'}));23}24_onmessage = function(event) {25 var _ans, _foo, _x = JSON.parse(event.data);26 if(typeof _x.imports !== "undefined") {27 for(_foo=0;_foo<_x.imports.length;_foo++) { importScripts(_x.imports[_foo]); }28 return;29 }30 try {31 workshop.current = {k:_x.k, n:_x.n};32 _ans = _myeval(_x.e);33 if(typeof(_ans) !== "undefined") { _foo = numeric.prettyPrint(_ans,true); }34 else { _foo = ""; }35 workshop.current = undefined;36 } catch(e) {37 _ans = undefined;38 _foo = e.name+': '+e.message;39 if(typeof e.stack !== "undefined" && typeof e.stack.toString !== "undefined")40 { _foo += "\n\n"+e.stack.toString(); }41 }42 _foo = _foo.replace(/&/g,'&').replace(/>/g,'>').replace(/</g,'<').replace(/"/g,'"');43 _send(JSON.stringify({k:_x.k,n:_x.n,o:_foo}));44}...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({path: 'google.png'});7 await browser.close();8})();
Using AI Code Generation
1const { _send } = require('playwright/lib/client/connection');2const { chromium } = require('playwright');3(async () => {4 const browser = await chromium.launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 const { value } = await _send(page, 'Page.captureScreenshot', {8 });9 console.log(value);10 await browser.close();11})();12const { _send } = require('playwright');13const { chromium } = require('playwright');14(async () => {15 const browser = await chromium.launch();16 const context = await browser.newContext();17 const page = await context.newPage();18 const { value } = await _send(page, 'Page.captureScreenshot', {19 });20 console.log(value);21 await browser.close();22})();
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright.firefox.launch();4 const page = await browser.newPage();5 await browser.close();6})();7const playwright = require('playwright');8(async () => {9 const browser = await playwright.firefox.launch();10 const page = await browser.newPage();11 await browser.close();12})();13const playwright = require('playwright');14(async () => {15 const browser = await playwright.firefox.launch();16 const page = await browser.newPage();17 await browser.close();18})();19const playwright = require('playwright');20(async () => {21 const browser = await playwright.firefox.launch();22 const page = await browser.newPage();23 await browser.close();24})();25const playwright = require('playwright');26(async () => {27 const browser = await playwright.firefox.launch();28 const page = await browser.newPage();29 await browser.close();30})();31const playwright = require('playwright');32(async () => {33 const browser = await playwright.firefox.launch();34 const page = await browser.newPage();35 await page._send('Page.navigate', { url: 'https
Using AI Code Generation
1const { _send } = require('playwright/lib/server/chromium/crConnection.js');2const { chromium } = require('playwright');3const fs = require('fs');4(async () => {5 const browser = await chromium.launch();6 const context = await browser.newContext();7 const page = await context.newPage();8 const target = await page.target();9 const client = await target.createCDPSession();10 const { data } = await _send(client, 'Page.captureScreenshot', { format: 'png', fromSurface: true });11 fs.writeFileSync('screenshot.png', Buffer.from(data, 'base64'));12 await browser.close();13})();
Using AI Code Generation
1const { _send } = require('playwright/lib/server/chromium/crConnection.js');2const { chromium } = require('playwright');3const browser = await chromium.launch();4const page = await browser.newPage();5await page.fill('input[type="search"]', 'playwright');6await page.click('input[type="submit"]');7await _send(page, 'Emulation.setDeviceMetricsOverride', {8});9await page.screenshot({ path: 'github.png' });10await browser.close();11const { _send } = require('playwright/lib/server/chromium/crConnection.js');12const { chromium } = require('playwright');13const browser = await chromium.launch();14const page = await browser.newPage();15await page.fill('input[type="search"]', 'playwright');16await page.click('input[type="submit"]');17await _send(page, 'Emulation.setDeviceMetricsOverride', {18});19await page.screenshot({ path: 'github.png' });20await browser.close();21const { _send } = require('playwright/lib/server/chromium/crConnection.js');22const { chromium } = require('playwright');23const browser = await chromium.launch();24const page = await browser.newPage();25await page.fill('input[type="search"]', 'playwright');26await page.click('input[type="submit"]');27await _send(page, 'Emulation.setDeviceMetricsOverride', {28});29await page.screenshot({
Using AI Code Generation
1const { _send } = require('playwright-core/lib/server/chromium/crConnection');2const { helper } = require('playwright-core/lib/helper');3const { assert } = require('playwright-core/lib/helper');4const { Events } = require('playwright-core/lib/events');5const { BrowserContext } = require('playwright-core/lib/server/browserContext');6const { Page } = require('playwright-core/lib/server/page');7const { Browser } = require('playwright-core/lib/server/browser');8const { BrowserServer } = require('playwright-core/lib/server/browserServer');9const { BrowserType } = require('playwright-core/lib/server/browserType');10const { getTestState } = require('./mocha-utils');11const { it, describe, beforeAll, afterAll } = getTestState();12describe('BrowserContext', function() {13 describe('BrowserContext', function() {14 it('should work', async({browserType, browserOptions, defaultBrowserOptions}) => {15 const browser = await browserType.launch(Object.assign({}, defaultBrowserOptions, browserOptions));16 const context = await browser.newContext();17 const page = await context.newPage();18 await page.screenshot({path: 'example.png'});19 await context.close();20 await browser.close();21 });22 });23});24const { expect } = require('chai');25const { test as base } = require('playwright-core/lib/test');26const { BrowserType } = require('playwright-core/lib/server/browserType');27const { Browser } = require('playwright-core/lib/server/browser');28const { BrowserContext } = require('playwright-core/lib/server/browserContext');29const { Page } = require('playwright-core/lib/server/page');30const { BrowserServer } = require('playwright-core/lib/server/browserServer');31const { Connection } = require('playwright-core/lib/server/connection');32const { Events } = require('playwright-core/lib/events');33const { helper } = require('playwright-core/lib/helper');34const { assert } = require('playwright-core/lib/helper');35const { debugLogger } = require('playwright-core/lib/utils/debugLogger');36const { TimeoutSettings } = require('playwright-core/lib/utils/timeoutSettings');37const { getTestState } = require('./mocha-utils');38const { it, describe, beforeAll, afterAll } = getTestState();
Using AI Code Generation
1const { _send } = require('playwright/lib/protocol/transport.js');2const { readFileSync } = require('fs');3const { join } = require('path');4const { chromium } = require('playwright');5(async () => {6 const browser = await chromium.launch();7 const page = await browser.newPage();8 const cookies = await page.context().cookies();9 const cookiesString = JSON.stringify(cookies);10 const cookiesFile = join(__dirname, 'cookies.json');11 await writeFileSync(cookiesFile, cookiesString);12 await browser.close();13})();14const { _send } = require('playwright/lib/protocol/transport.js');15const { readFileSync } = require('fs');16const { join } = require('path');17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const page = await browser.newPage();21 const cookiesFile = join(__dirname, 'cookies.json');22 const cookiesString = await readFileSync(cookiesFile);23 const cookies = JSON.parse(cookiesString);24 await page.context().addCookies(cookies);25 await browser.close();26})();
Using AI Code Generation
1const { _send } = require('playwright/lib/client/transport');2const { createWriteStream } = require('fs');3(async () => {4 const response = await _send(wsEndpoint, 'Browser.newPage');5 const { page } = response.result;6 const { frame } = pageResponse.result;7 const { result: { data } } = await _send(wsEndpoint, 'Page.captureScreenshot', { format: 'jpeg', page, quality: 100 });8 const writeStream = createWriteStream('screenshot.jpeg');9 writeStream.write(data);10 writeStream.close();11})();12const { chromium } = require('playwright');13const { createServer } = require('http');14const { parse } = require('url');15(async () => {16 const browser = await chromium.launch();17 const server = createServer(async (req, res) => {18 const { pathname } = parse(req.url);19 if (pathname === '/ws') {20 const ws = await browser.newBrowserCDPSession();21 ws.on('message', message => {22 const data = JSON.parse(message);23 if (data.id && data.id in requests) {24 const { response, resolve } = requests[data.id];25 resolve(response);26 delete requests[data.id];27 }28 });29 ws.on('close', () => {30 for (const { reject } of Object.values(requests)) {31 reject(new Error('Browser closed'));32 }33 requests = {};34 });35 ws.on('error', () => {36 for (const { reject } of Object.values(requests)) {37 reject(new Error('Browser closed'));38 }39 requests = {};40 });41 res.end(JSON.stringify({ wsEndpoint: ws._wsEndpoint }));42 return;43 }44 res.statusCode = 404;45 res.end('Not found');46 });47 server.listen(8080);48})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!