sygnal 2.3.0 → 2.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,4660 @@
1
+ 'use strict';
2
+
3
+ Object.defineProperty(exports, '__esModule', { value: true });
4
+
5
+ var isolate = require('@cycle/isolate');
6
+ var state = require('@cycle/state');
7
+ var xs$1 = require('xstream');
8
+ var run$1 = require('@cycle/run');
9
+ var dom = require('@cycle/dom');
10
+
11
+ function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e : { 'default': e }; }
12
+
13
+ var isolate__default = /*#__PURE__*/_interopDefaultLegacy(isolate);
14
+ var xs__default = /*#__PURE__*/_interopDefaultLegacy(xs$1);
15
+
16
+ function collection(component, stateLense, opts={}) {
17
+ const {
18
+ combineList = ['DOM'],
19
+ globalList = ['EVENTS'],
20
+ stateSourceName = 'STATE',
21
+ domSourceName = 'DOM',
22
+ container = 'div',
23
+ containerClass
24
+ } = opts;
25
+
26
+ return (sources) => {
27
+ const key = Date.now();
28
+ const collectionOpts = {
29
+ item: component,
30
+ itemKey: (state, ind) => typeof state.id !== 'undefined' ? state.id : ind,
31
+ itemScope: key => key,
32
+ channel: stateSourceName,
33
+ collectSinks: instances => {
34
+ return Object.entries(sources).reduce((acc, [name, stream]) => {
35
+ if (combineList.includes(name)) {
36
+ const combined = instances.pickCombine(name);
37
+ if (name === domSourceName && container) {
38
+ acc[domSourceName] = combined.map(children => {
39
+ const data = (containerClass) ? { props: { className: containerClass } } : {};
40
+ return { sel: container, data, children, key, text: undefined, elm: undefined}
41
+ });
42
+ } else {
43
+ // console.warn('Collections without wrapping containers will fail in unpredictable ways when used inside JSX fragments')
44
+ acc[name] = combined;
45
+ }
46
+ } else {
47
+ acc[name] = instances.pickMerge(name);
48
+ }
49
+ return acc
50
+ }, {})
51
+ }
52
+ };
53
+
54
+ const isolateOpts = {[stateSourceName]: stateLense};
55
+
56
+ globalList.forEach(global => isolateOpts[global] = null);
57
+ combineList.forEach(combine => isolateOpts[combine] = null);
58
+
59
+ return makeIsolatedCollection(collectionOpts, isolateOpts, sources)
60
+ }
61
+ }
62
+
63
+ /**
64
+ * instantiate a cycle collection and isolate
65
+ * (makes the code for doing isolated collections more readable)
66
+ *
67
+ * @param {Object} collectionOpts options for the makeCollection function (see cycle/state documentation)
68
+ * @param {String|Object} isolateOpts options for the isolate function (see cycle/isolate documentation)
69
+ * @param {Object} sources object of cycle style sources to use for the created collection
70
+ * @return {Object} collection of component sinks
71
+ */
72
+ function makeIsolatedCollection (collectionOpts, isolateOpts, sources) {
73
+ return isolate__default["default"](state.makeCollection(collectionOpts), isolateOpts)(sources)
74
+ }
75
+
76
+ var commonjsGlobal = typeof globalThis !== 'undefined' ? globalThis : typeof window !== 'undefined' ? window : typeof global !== 'undefined' ? global : typeof self !== 'undefined' ? self : {};
77
+
78
+ var dropRepeats$1 = {};
79
+
80
+ var xstream = {};
81
+
82
+ var ponyfill$1 = {exports: {}};
83
+
84
+ var ponyfill = {};
85
+
86
+ (function (exports) {
87
+
88
+ Object.defineProperty(exports, "__esModule", {
89
+ value: true
90
+ });
91
+ exports['default'] = symbolObservablePonyfill;
92
+ function symbolObservablePonyfill(root) {
93
+ var result;
94
+ var _Symbol = root.Symbol;
95
+
96
+ if (typeof _Symbol === 'function') {
97
+ if (_Symbol.observable) {
98
+ result = _Symbol.observable;
99
+ } else {
100
+
101
+ // This just needs to be something that won't trample other user's Symbol.for use
102
+ // It also will guide people to the source of their issues, if this is problematic.
103
+ // META: It's a resource locator!
104
+ result = _Symbol['for']('https://github.com/benlesh/symbol-observable');
105
+ try {
106
+ _Symbol.observable = result;
107
+ } catch (err) {
108
+ // Do nothing. In some environments, users have frozen `Symbol` for security reasons,
109
+ // if it is frozen assigning to it will throw. In this case, we don't care, because
110
+ // they will need to use the returned value from the ponyfill.
111
+ }
112
+ }
113
+ } else {
114
+ result = '@@observable';
115
+ }
116
+
117
+ return result;
118
+ }} (ponyfill));
119
+
120
+ (function (module) {
121
+ module.exports = ponyfill;
122
+ } (ponyfill$1));
123
+
124
+ var toStr$2 = Object.prototype.toString;
125
+
126
+ var isArguments = function isArguments(value) {
127
+ var str = toStr$2.call(value);
128
+ var isArgs = str === '[object Arguments]';
129
+ if (!isArgs) {
130
+ isArgs = str !== '[object Array]' &&
131
+ value !== null &&
132
+ typeof value === 'object' &&
133
+ typeof value.length === 'number' &&
134
+ value.length >= 0 &&
135
+ toStr$2.call(value.callee) === '[object Function]';
136
+ }
137
+ return isArgs;
138
+ };
139
+
140
+ var implementation$5;
141
+ var hasRequiredImplementation;
142
+
143
+ function requireImplementation () {
144
+ if (hasRequiredImplementation) return implementation$5;
145
+ hasRequiredImplementation = 1;
146
+
147
+ var keysShim;
148
+ if (!Object.keys) {
149
+ // modified from https://github.com/es-shims/es5-shim
150
+ var has = Object.prototype.hasOwnProperty;
151
+ var toStr = Object.prototype.toString;
152
+ var isArgs = isArguments; // eslint-disable-line global-require
153
+ var isEnumerable = Object.prototype.propertyIsEnumerable;
154
+ var hasDontEnumBug = !isEnumerable.call({ toString: null }, 'toString');
155
+ var hasProtoEnumBug = isEnumerable.call(function () {}, 'prototype');
156
+ var dontEnums = [
157
+ 'toString',
158
+ 'toLocaleString',
159
+ 'valueOf',
160
+ 'hasOwnProperty',
161
+ 'isPrototypeOf',
162
+ 'propertyIsEnumerable',
163
+ 'constructor'
164
+ ];
165
+ var equalsConstructorPrototype = function (o) {
166
+ var ctor = o.constructor;
167
+ return ctor && ctor.prototype === o;
168
+ };
169
+ var excludedKeys = {
170
+ $applicationCache: true,
171
+ $console: true,
172
+ $external: true,
173
+ $frame: true,
174
+ $frameElement: true,
175
+ $frames: true,
176
+ $innerHeight: true,
177
+ $innerWidth: true,
178
+ $onmozfullscreenchange: true,
179
+ $onmozfullscreenerror: true,
180
+ $outerHeight: true,
181
+ $outerWidth: true,
182
+ $pageXOffset: true,
183
+ $pageYOffset: true,
184
+ $parent: true,
185
+ $scrollLeft: true,
186
+ $scrollTop: true,
187
+ $scrollX: true,
188
+ $scrollY: true,
189
+ $self: true,
190
+ $webkitIndexedDB: true,
191
+ $webkitStorageInfo: true,
192
+ $window: true
193
+ };
194
+ var hasAutomationEqualityBug = (function () {
195
+ /* global window */
196
+ if (typeof window === 'undefined') { return false; }
197
+ for (var k in window) {
198
+ try {
199
+ if (!excludedKeys['$' + k] && has.call(window, k) && window[k] !== null && typeof window[k] === 'object') {
200
+ try {
201
+ equalsConstructorPrototype(window[k]);
202
+ } catch (e) {
203
+ return true;
204
+ }
205
+ }
206
+ } catch (e) {
207
+ return true;
208
+ }
209
+ }
210
+ return false;
211
+ }());
212
+ var equalsConstructorPrototypeIfNotBuggy = function (o) {
213
+ /* global window */
214
+ if (typeof window === 'undefined' || !hasAutomationEqualityBug) {
215
+ return equalsConstructorPrototype(o);
216
+ }
217
+ try {
218
+ return equalsConstructorPrototype(o);
219
+ } catch (e) {
220
+ return false;
221
+ }
222
+ };
223
+
224
+ keysShim = function keys(object) {
225
+ var isObject = object !== null && typeof object === 'object';
226
+ var isFunction = toStr.call(object) === '[object Function]';
227
+ var isArguments = isArgs(object);
228
+ var isString = isObject && toStr.call(object) === '[object String]';
229
+ var theKeys = [];
230
+
231
+ if (!isObject && !isFunction && !isArguments) {
232
+ throw new TypeError('Object.keys called on a non-object');
233
+ }
234
+
235
+ var skipProto = hasProtoEnumBug && isFunction;
236
+ if (isString && object.length > 0 && !has.call(object, 0)) {
237
+ for (var i = 0; i < object.length; ++i) {
238
+ theKeys.push(String(i));
239
+ }
240
+ }
241
+
242
+ if (isArguments && object.length > 0) {
243
+ for (var j = 0; j < object.length; ++j) {
244
+ theKeys.push(String(j));
245
+ }
246
+ } else {
247
+ for (var name in object) {
248
+ if (!(skipProto && name === 'prototype') && has.call(object, name)) {
249
+ theKeys.push(String(name));
250
+ }
251
+ }
252
+ }
253
+
254
+ if (hasDontEnumBug) {
255
+ var skipConstructor = equalsConstructorPrototypeIfNotBuggy(object);
256
+
257
+ for (var k = 0; k < dontEnums.length; ++k) {
258
+ if (!(skipConstructor && dontEnums[k] === 'constructor') && has.call(object, dontEnums[k])) {
259
+ theKeys.push(dontEnums[k]);
260
+ }
261
+ }
262
+ }
263
+ return theKeys;
264
+ };
265
+ }
266
+ implementation$5 = keysShim;
267
+ return implementation$5;
268
+ }
269
+
270
+ var slice$1 = Array.prototype.slice;
271
+ var isArgs = isArguments;
272
+
273
+ var origKeys = Object.keys;
274
+ var keysShim = origKeys ? function keys(o) { return origKeys(o); } : requireImplementation();
275
+
276
+ var originalKeys = Object.keys;
277
+
278
+ keysShim.shim = function shimObjectKeys() {
279
+ if (Object.keys) {
280
+ var keysWorksWithArguments = (function () {
281
+ // Safari 5.0 bug
282
+ var args = Object.keys(arguments);
283
+ return args && args.length === arguments.length;
284
+ }(1, 2));
285
+ if (!keysWorksWithArguments) {
286
+ Object.keys = function keys(object) { // eslint-disable-line func-name-matching
287
+ if (isArgs(object)) {
288
+ return originalKeys(slice$1.call(object));
289
+ }
290
+ return originalKeys(object);
291
+ };
292
+ }
293
+ } else {
294
+ Object.keys = keysShim;
295
+ }
296
+ return Object.keys || keysShim;
297
+ };
298
+
299
+ var objectKeys = keysShim;
300
+
301
+ /* eslint complexity: [2, 18], max-statements: [2, 33] */
302
+ var shams = function hasSymbols() {
303
+ if (typeof Symbol !== 'function' || typeof Object.getOwnPropertySymbols !== 'function') { return false; }
304
+ if (typeof Symbol.iterator === 'symbol') { return true; }
305
+
306
+ var obj = {};
307
+ var sym = Symbol('test');
308
+ var symObj = Object(sym);
309
+ if (typeof sym === 'string') { return false; }
310
+
311
+ if (Object.prototype.toString.call(sym) !== '[object Symbol]') { return false; }
312
+ if (Object.prototype.toString.call(symObj) !== '[object Symbol]') { return false; }
313
+
314
+ // temp disabled per https://github.com/ljharb/object.assign/issues/17
315
+ // if (sym instanceof Symbol) { return false; }
316
+ // temp disabled per https://github.com/WebReflection/get-own-property-symbols/issues/4
317
+ // if (!(symObj instanceof Symbol)) { return false; }
318
+
319
+ // if (typeof Symbol.prototype.toString !== 'function') { return false; }
320
+ // if (String(sym) !== Symbol.prototype.toString.call(sym)) { return false; }
321
+
322
+ var symVal = 42;
323
+ obj[sym] = symVal;
324
+ for (sym in obj) { return false; } // eslint-disable-line no-restricted-syntax, no-unreachable-loop
325
+ if (typeof Object.keys === 'function' && Object.keys(obj).length !== 0) { return false; }
326
+
327
+ if (typeof Object.getOwnPropertyNames === 'function' && Object.getOwnPropertyNames(obj).length !== 0) { return false; }
328
+
329
+ var syms = Object.getOwnPropertySymbols(obj);
330
+ if (syms.length !== 1 || syms[0] !== sym) { return false; }
331
+
332
+ if (!Object.prototype.propertyIsEnumerable.call(obj, sym)) { return false; }
333
+
334
+ if (typeof Object.getOwnPropertyDescriptor === 'function') {
335
+ var descriptor = Object.getOwnPropertyDescriptor(obj, sym);
336
+ if (descriptor.value !== symVal || descriptor.enumerable !== true) { return false; }
337
+ }
338
+
339
+ return true;
340
+ };
341
+
342
+ var origSymbol = typeof Symbol !== 'undefined' && Symbol;
343
+ var hasSymbolSham = shams;
344
+
345
+ var hasSymbols$2 = function hasNativeSymbols() {
346
+ if (typeof origSymbol !== 'function') { return false; }
347
+ if (typeof Symbol !== 'function') { return false; }
348
+ if (typeof origSymbol('foo') !== 'symbol') { return false; }
349
+ if (typeof Symbol('bar') !== 'symbol') { return false; }
350
+
351
+ return hasSymbolSham();
352
+ };
353
+
354
+ /* eslint no-invalid-this: 1 */
355
+
356
+ var ERROR_MESSAGE = 'Function.prototype.bind called on incompatible ';
357
+ var slice = Array.prototype.slice;
358
+ var toStr$1 = Object.prototype.toString;
359
+ var funcType = '[object Function]';
360
+
361
+ var implementation$4 = function bind(that) {
362
+ var target = this;
363
+ if (typeof target !== 'function' || toStr$1.call(target) !== funcType) {
364
+ throw new TypeError(ERROR_MESSAGE + target);
365
+ }
366
+ var args = slice.call(arguments, 1);
367
+
368
+ var bound;
369
+ var binder = function () {
370
+ if (this instanceof bound) {
371
+ var result = target.apply(
372
+ this,
373
+ args.concat(slice.call(arguments))
374
+ );
375
+ if (Object(result) === result) {
376
+ return result;
377
+ }
378
+ return this;
379
+ } else {
380
+ return target.apply(
381
+ that,
382
+ args.concat(slice.call(arguments))
383
+ );
384
+ }
385
+ };
386
+
387
+ var boundLength = Math.max(0, target.length - args.length);
388
+ var boundArgs = [];
389
+ for (var i = 0; i < boundLength; i++) {
390
+ boundArgs.push('$' + i);
391
+ }
392
+
393
+ bound = Function('binder', 'return function (' + boundArgs.join(',') + '){ return binder.apply(this,arguments); }')(binder);
394
+
395
+ if (target.prototype) {
396
+ var Empty = function Empty() {};
397
+ Empty.prototype = target.prototype;
398
+ bound.prototype = new Empty();
399
+ Empty.prototype = null;
400
+ }
401
+
402
+ return bound;
403
+ };
404
+
405
+ var implementation$3 = implementation$4;
406
+
407
+ var functionBind = Function.prototype.bind || implementation$3;
408
+
409
+ var bind$1 = functionBind;
410
+
411
+ var src = bind$1.call(Function.call, Object.prototype.hasOwnProperty);
412
+
413
+ var undefined$1;
414
+
415
+ var $SyntaxError = SyntaxError;
416
+ var $Function = Function;
417
+ var $TypeError = TypeError;
418
+
419
+ // eslint-disable-next-line consistent-return
420
+ var getEvalledConstructor = function (expressionSyntax) {
421
+ try {
422
+ return $Function('"use strict"; return (' + expressionSyntax + ').constructor;')();
423
+ } catch (e) {}
424
+ };
425
+
426
+ var $gOPD = Object.getOwnPropertyDescriptor;
427
+ if ($gOPD) {
428
+ try {
429
+ $gOPD({}, '');
430
+ } catch (e) {
431
+ $gOPD = null; // this is IE 8, which has a broken gOPD
432
+ }
433
+ }
434
+
435
+ var throwTypeError = function () {
436
+ throw new $TypeError();
437
+ };
438
+ var ThrowTypeError = $gOPD
439
+ ? (function () {
440
+ try {
441
+ // eslint-disable-next-line no-unused-expressions, no-caller, no-restricted-properties
442
+ arguments.callee; // IE 8 does not throw here
443
+ return throwTypeError;
444
+ } catch (calleeThrows) {
445
+ try {
446
+ // IE 8 throws on Object.getOwnPropertyDescriptor(arguments, '')
447
+ return $gOPD(arguments, 'callee').get;
448
+ } catch (gOPDthrows) {
449
+ return throwTypeError;
450
+ }
451
+ }
452
+ }())
453
+ : throwTypeError;
454
+
455
+ var hasSymbols$1 = hasSymbols$2();
456
+
457
+ var getProto = Object.getPrototypeOf || function (x) { return x.__proto__; }; // eslint-disable-line no-proto
458
+
459
+ var needsEval = {};
460
+
461
+ var TypedArray = typeof Uint8Array === 'undefined' ? undefined$1 : getProto(Uint8Array);
462
+
463
+ var INTRINSICS = {
464
+ '%AggregateError%': typeof AggregateError === 'undefined' ? undefined$1 : AggregateError,
465
+ '%Array%': Array,
466
+ '%ArrayBuffer%': typeof ArrayBuffer === 'undefined' ? undefined$1 : ArrayBuffer,
467
+ '%ArrayIteratorPrototype%': hasSymbols$1 ? getProto([][Symbol.iterator]()) : undefined$1,
468
+ '%AsyncFromSyncIteratorPrototype%': undefined$1,
469
+ '%AsyncFunction%': needsEval,
470
+ '%AsyncGenerator%': needsEval,
471
+ '%AsyncGeneratorFunction%': needsEval,
472
+ '%AsyncIteratorPrototype%': needsEval,
473
+ '%Atomics%': typeof Atomics === 'undefined' ? undefined$1 : Atomics,
474
+ '%BigInt%': typeof BigInt === 'undefined' ? undefined$1 : BigInt,
475
+ '%Boolean%': Boolean,
476
+ '%DataView%': typeof DataView === 'undefined' ? undefined$1 : DataView,
477
+ '%Date%': Date,
478
+ '%decodeURI%': decodeURI,
479
+ '%decodeURIComponent%': decodeURIComponent,
480
+ '%encodeURI%': encodeURI,
481
+ '%encodeURIComponent%': encodeURIComponent,
482
+ '%Error%': Error,
483
+ '%eval%': eval, // eslint-disable-line no-eval
484
+ '%EvalError%': EvalError,
485
+ '%Float32Array%': typeof Float32Array === 'undefined' ? undefined$1 : Float32Array,
486
+ '%Float64Array%': typeof Float64Array === 'undefined' ? undefined$1 : Float64Array,
487
+ '%FinalizationRegistry%': typeof FinalizationRegistry === 'undefined' ? undefined$1 : FinalizationRegistry,
488
+ '%Function%': $Function,
489
+ '%GeneratorFunction%': needsEval,
490
+ '%Int8Array%': typeof Int8Array === 'undefined' ? undefined$1 : Int8Array,
491
+ '%Int16Array%': typeof Int16Array === 'undefined' ? undefined$1 : Int16Array,
492
+ '%Int32Array%': typeof Int32Array === 'undefined' ? undefined$1 : Int32Array,
493
+ '%isFinite%': isFinite,
494
+ '%isNaN%': isNaN,
495
+ '%IteratorPrototype%': hasSymbols$1 ? getProto(getProto([][Symbol.iterator]())) : undefined$1,
496
+ '%JSON%': typeof JSON === 'object' ? JSON : undefined$1,
497
+ '%Map%': typeof Map === 'undefined' ? undefined$1 : Map,
498
+ '%MapIteratorPrototype%': typeof Map === 'undefined' || !hasSymbols$1 ? undefined$1 : getProto(new Map()[Symbol.iterator]()),
499
+ '%Math%': Math,
500
+ '%Number%': Number,
501
+ '%Object%': Object,
502
+ '%parseFloat%': parseFloat,
503
+ '%parseInt%': parseInt,
504
+ '%Promise%': typeof Promise === 'undefined' ? undefined$1 : Promise,
505
+ '%Proxy%': typeof Proxy === 'undefined' ? undefined$1 : Proxy,
506
+ '%RangeError%': RangeError,
507
+ '%ReferenceError%': ReferenceError,
508
+ '%Reflect%': typeof Reflect === 'undefined' ? undefined$1 : Reflect,
509
+ '%RegExp%': RegExp,
510
+ '%Set%': typeof Set === 'undefined' ? undefined$1 : Set,
511
+ '%SetIteratorPrototype%': typeof Set === 'undefined' || !hasSymbols$1 ? undefined$1 : getProto(new Set()[Symbol.iterator]()),
512
+ '%SharedArrayBuffer%': typeof SharedArrayBuffer === 'undefined' ? undefined$1 : SharedArrayBuffer,
513
+ '%String%': String,
514
+ '%StringIteratorPrototype%': hasSymbols$1 ? getProto(''[Symbol.iterator]()) : undefined$1,
515
+ '%Symbol%': hasSymbols$1 ? Symbol : undefined$1,
516
+ '%SyntaxError%': $SyntaxError,
517
+ '%ThrowTypeError%': ThrowTypeError,
518
+ '%TypedArray%': TypedArray,
519
+ '%TypeError%': $TypeError,
520
+ '%Uint8Array%': typeof Uint8Array === 'undefined' ? undefined$1 : Uint8Array,
521
+ '%Uint8ClampedArray%': typeof Uint8ClampedArray === 'undefined' ? undefined$1 : Uint8ClampedArray,
522
+ '%Uint16Array%': typeof Uint16Array === 'undefined' ? undefined$1 : Uint16Array,
523
+ '%Uint32Array%': typeof Uint32Array === 'undefined' ? undefined$1 : Uint32Array,
524
+ '%URIError%': URIError,
525
+ '%WeakMap%': typeof WeakMap === 'undefined' ? undefined$1 : WeakMap,
526
+ '%WeakRef%': typeof WeakRef === 'undefined' ? undefined$1 : WeakRef,
527
+ '%WeakSet%': typeof WeakSet === 'undefined' ? undefined$1 : WeakSet
528
+ };
529
+
530
+ var doEval = function doEval(name) {
531
+ var value;
532
+ if (name === '%AsyncFunction%') {
533
+ value = getEvalledConstructor('async function () {}');
534
+ } else if (name === '%GeneratorFunction%') {
535
+ value = getEvalledConstructor('function* () {}');
536
+ } else if (name === '%AsyncGeneratorFunction%') {
537
+ value = getEvalledConstructor('async function* () {}');
538
+ } else if (name === '%AsyncGenerator%') {
539
+ var fn = doEval('%AsyncGeneratorFunction%');
540
+ if (fn) {
541
+ value = fn.prototype;
542
+ }
543
+ } else if (name === '%AsyncIteratorPrototype%') {
544
+ var gen = doEval('%AsyncGenerator%');
545
+ if (gen) {
546
+ value = getProto(gen.prototype);
547
+ }
548
+ }
549
+
550
+ INTRINSICS[name] = value;
551
+
552
+ return value;
553
+ };
554
+
555
+ var LEGACY_ALIASES = {
556
+ '%ArrayBufferPrototype%': ['ArrayBuffer', 'prototype'],
557
+ '%ArrayPrototype%': ['Array', 'prototype'],
558
+ '%ArrayProto_entries%': ['Array', 'prototype', 'entries'],
559
+ '%ArrayProto_forEach%': ['Array', 'prototype', 'forEach'],
560
+ '%ArrayProto_keys%': ['Array', 'prototype', 'keys'],
561
+ '%ArrayProto_values%': ['Array', 'prototype', 'values'],
562
+ '%AsyncFunctionPrototype%': ['AsyncFunction', 'prototype'],
563
+ '%AsyncGenerator%': ['AsyncGeneratorFunction', 'prototype'],
564
+ '%AsyncGeneratorPrototype%': ['AsyncGeneratorFunction', 'prototype', 'prototype'],
565
+ '%BooleanPrototype%': ['Boolean', 'prototype'],
566
+ '%DataViewPrototype%': ['DataView', 'prototype'],
567
+ '%DatePrototype%': ['Date', 'prototype'],
568
+ '%ErrorPrototype%': ['Error', 'prototype'],
569
+ '%EvalErrorPrototype%': ['EvalError', 'prototype'],
570
+ '%Float32ArrayPrototype%': ['Float32Array', 'prototype'],
571
+ '%Float64ArrayPrototype%': ['Float64Array', 'prototype'],
572
+ '%FunctionPrototype%': ['Function', 'prototype'],
573
+ '%Generator%': ['GeneratorFunction', 'prototype'],
574
+ '%GeneratorPrototype%': ['GeneratorFunction', 'prototype', 'prototype'],
575
+ '%Int8ArrayPrototype%': ['Int8Array', 'prototype'],
576
+ '%Int16ArrayPrototype%': ['Int16Array', 'prototype'],
577
+ '%Int32ArrayPrototype%': ['Int32Array', 'prototype'],
578
+ '%JSONParse%': ['JSON', 'parse'],
579
+ '%JSONStringify%': ['JSON', 'stringify'],
580
+ '%MapPrototype%': ['Map', 'prototype'],
581
+ '%NumberPrototype%': ['Number', 'prototype'],
582
+ '%ObjectPrototype%': ['Object', 'prototype'],
583
+ '%ObjProto_toString%': ['Object', 'prototype', 'toString'],
584
+ '%ObjProto_valueOf%': ['Object', 'prototype', 'valueOf'],
585
+ '%PromisePrototype%': ['Promise', 'prototype'],
586
+ '%PromiseProto_then%': ['Promise', 'prototype', 'then'],
587
+ '%Promise_all%': ['Promise', 'all'],
588
+ '%Promise_reject%': ['Promise', 'reject'],
589
+ '%Promise_resolve%': ['Promise', 'resolve'],
590
+ '%RangeErrorPrototype%': ['RangeError', 'prototype'],
591
+ '%ReferenceErrorPrototype%': ['ReferenceError', 'prototype'],
592
+ '%RegExpPrototype%': ['RegExp', 'prototype'],
593
+ '%SetPrototype%': ['Set', 'prototype'],
594
+ '%SharedArrayBufferPrototype%': ['SharedArrayBuffer', 'prototype'],
595
+ '%StringPrototype%': ['String', 'prototype'],
596
+ '%SymbolPrototype%': ['Symbol', 'prototype'],
597
+ '%SyntaxErrorPrototype%': ['SyntaxError', 'prototype'],
598
+ '%TypedArrayPrototype%': ['TypedArray', 'prototype'],
599
+ '%TypeErrorPrototype%': ['TypeError', 'prototype'],
600
+ '%Uint8ArrayPrototype%': ['Uint8Array', 'prototype'],
601
+ '%Uint8ClampedArrayPrototype%': ['Uint8ClampedArray', 'prototype'],
602
+ '%Uint16ArrayPrototype%': ['Uint16Array', 'prototype'],
603
+ '%Uint32ArrayPrototype%': ['Uint32Array', 'prototype'],
604
+ '%URIErrorPrototype%': ['URIError', 'prototype'],
605
+ '%WeakMapPrototype%': ['WeakMap', 'prototype'],
606
+ '%WeakSetPrototype%': ['WeakSet', 'prototype']
607
+ };
608
+
609
+ var bind = functionBind;
610
+ var hasOwn = src;
611
+ var $concat = bind.call(Function.call, Array.prototype.concat);
612
+ var $spliceApply = bind.call(Function.apply, Array.prototype.splice);
613
+ var $replace = bind.call(Function.call, String.prototype.replace);
614
+ var $strSlice = bind.call(Function.call, String.prototype.slice);
615
+
616
+ /* adapted from https://github.com/lodash/lodash/blob/4.17.15/dist/lodash.js#L6735-L6744 */
617
+ var rePropName = /[^%.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|%$))/g;
618
+ var reEscapeChar = /\\(\\)?/g; /** Used to match backslashes in property paths. */
619
+ var stringToPath = function stringToPath(string) {
620
+ var first = $strSlice(string, 0, 1);
621
+ var last = $strSlice(string, -1);
622
+ if (first === '%' && last !== '%') {
623
+ throw new $SyntaxError('invalid intrinsic syntax, expected closing `%`');
624
+ } else if (last === '%' && first !== '%') {
625
+ throw new $SyntaxError('invalid intrinsic syntax, expected opening `%`');
626
+ }
627
+ var result = [];
628
+ $replace(string, rePropName, function (match, number, quote, subString) {
629
+ result[result.length] = quote ? $replace(subString, reEscapeChar, '$1') : number || match;
630
+ });
631
+ return result;
632
+ };
633
+ /* end adaptation */
634
+
635
+ var getBaseIntrinsic = function getBaseIntrinsic(name, allowMissing) {
636
+ var intrinsicName = name;
637
+ var alias;
638
+ if (hasOwn(LEGACY_ALIASES, intrinsicName)) {
639
+ alias = LEGACY_ALIASES[intrinsicName];
640
+ intrinsicName = '%' + alias[0] + '%';
641
+ }
642
+
643
+ if (hasOwn(INTRINSICS, intrinsicName)) {
644
+ var value = INTRINSICS[intrinsicName];
645
+ if (value === needsEval) {
646
+ value = doEval(intrinsicName);
647
+ }
648
+ if (typeof value === 'undefined' && !allowMissing) {
649
+ throw new $TypeError('intrinsic ' + name + ' exists, but is not available. Please file an issue!');
650
+ }
651
+
652
+ return {
653
+ alias: alias,
654
+ name: intrinsicName,
655
+ value: value
656
+ };
657
+ }
658
+
659
+ throw new $SyntaxError('intrinsic ' + name + ' does not exist!');
660
+ };
661
+
662
+ var getIntrinsic = function GetIntrinsic(name, allowMissing) {
663
+ if (typeof name !== 'string' || name.length === 0) {
664
+ throw new $TypeError('intrinsic name must be a non-empty string');
665
+ }
666
+ if (arguments.length > 1 && typeof allowMissing !== 'boolean') {
667
+ throw new $TypeError('"allowMissing" argument must be a boolean');
668
+ }
669
+
670
+ var parts = stringToPath(name);
671
+ var intrinsicBaseName = parts.length > 0 ? parts[0] : '';
672
+
673
+ var intrinsic = getBaseIntrinsic('%' + intrinsicBaseName + '%', allowMissing);
674
+ var intrinsicRealName = intrinsic.name;
675
+ var value = intrinsic.value;
676
+ var skipFurtherCaching = false;
677
+
678
+ var alias = intrinsic.alias;
679
+ if (alias) {
680
+ intrinsicBaseName = alias[0];
681
+ $spliceApply(parts, $concat([0, 1], alias));
682
+ }
683
+
684
+ for (var i = 1, isOwn = true; i < parts.length; i += 1) {
685
+ var part = parts[i];
686
+ var first = $strSlice(part, 0, 1);
687
+ var last = $strSlice(part, -1);
688
+ if (
689
+ (
690
+ (first === '"' || first === "'" || first === '`')
691
+ || (last === '"' || last === "'" || last === '`')
692
+ )
693
+ && first !== last
694
+ ) {
695
+ throw new $SyntaxError('property names with quotes must have matching quotes');
696
+ }
697
+ if (part === 'constructor' || !isOwn) {
698
+ skipFurtherCaching = true;
699
+ }
700
+
701
+ intrinsicBaseName += '.' + part;
702
+ intrinsicRealName = '%' + intrinsicBaseName + '%';
703
+
704
+ if (hasOwn(INTRINSICS, intrinsicRealName)) {
705
+ value = INTRINSICS[intrinsicRealName];
706
+ } else if (value != null) {
707
+ if (!(part in value)) {
708
+ if (!allowMissing) {
709
+ throw new $TypeError('base intrinsic for ' + name + ' exists, but the property is not available.');
710
+ }
711
+ return void undefined$1;
712
+ }
713
+ if ($gOPD && (i + 1) >= parts.length) {
714
+ var desc = $gOPD(value, part);
715
+ isOwn = !!desc;
716
+
717
+ // By convention, when a data property is converted to an accessor
718
+ // property to emulate a data property that does not suffer from
719
+ // the override mistake, that accessor's getter is marked with
720
+ // an `originalValue` property. Here, when we detect this, we
721
+ // uphold the illusion by pretending to see that original data
722
+ // property, i.e., returning the value rather than the getter
723
+ // itself.
724
+ if (isOwn && 'get' in desc && !('originalValue' in desc.get)) {
725
+ value = desc.get;
726
+ } else {
727
+ value = value[part];
728
+ }
729
+ } else {
730
+ isOwn = hasOwn(value, part);
731
+ value = value[part];
732
+ }
733
+
734
+ if (isOwn && !skipFurtherCaching) {
735
+ INTRINSICS[intrinsicRealName] = value;
736
+ }
737
+ }
738
+ }
739
+ return value;
740
+ };
741
+
742
+ var GetIntrinsic = getIntrinsic;
743
+
744
+ var $defineProperty = GetIntrinsic('%Object.defineProperty%', true);
745
+
746
+ var hasPropertyDescriptors$1 = function hasPropertyDescriptors() {
747
+ if ($defineProperty) {
748
+ try {
749
+ $defineProperty({}, 'a', { value: 1 });
750
+ return true;
751
+ } catch (e) {
752
+ // IE 8 has a broken defineProperty
753
+ return false;
754
+ }
755
+ }
756
+ return false;
757
+ };
758
+
759
+ hasPropertyDescriptors$1.hasArrayLengthDefineBug = function hasArrayLengthDefineBug() {
760
+ // node v0.6 has a bug where array lengths can be Set but not Defined
761
+ if (!hasPropertyDescriptors$1()) {
762
+ return null;
763
+ }
764
+ try {
765
+ return $defineProperty([], 'length', { value: 1 }).length !== 1;
766
+ } catch (e) {
767
+ // In Firefox 4-22, defining length on an array throws an exception.
768
+ return true;
769
+ }
770
+ };
771
+
772
+ var hasPropertyDescriptors_1 = hasPropertyDescriptors$1;
773
+
774
+ var keys = objectKeys;
775
+ var hasSymbols = typeof Symbol === 'function' && typeof Symbol('foo') === 'symbol';
776
+
777
+ var toStr = Object.prototype.toString;
778
+ var concat$2 = Array.prototype.concat;
779
+ var origDefineProperty = Object.defineProperty;
780
+
781
+ var isFunction = function (fn) {
782
+ return typeof fn === 'function' && toStr.call(fn) === '[object Function]';
783
+ };
784
+
785
+ var hasPropertyDescriptors = hasPropertyDescriptors_1();
786
+
787
+ var supportsDescriptors = origDefineProperty && hasPropertyDescriptors;
788
+
789
+ var defineProperty = function (object, name, value, predicate) {
790
+ if (name in object && (!isFunction(predicate) || !predicate())) {
791
+ return;
792
+ }
793
+ if (supportsDescriptors) {
794
+ origDefineProperty(object, name, {
795
+ configurable: true,
796
+ enumerable: false,
797
+ value: value,
798
+ writable: true
799
+ });
800
+ } else {
801
+ object[name] = value; // eslint-disable-line no-param-reassign
802
+ }
803
+ };
804
+
805
+ var defineProperties$1 = function (object, map) {
806
+ var predicates = arguments.length > 2 ? arguments[2] : {};
807
+ var props = keys(map);
808
+ if (hasSymbols) {
809
+ props = concat$2.call(props, Object.getOwnPropertySymbols(map));
810
+ }
811
+ for (var i = 0; i < props.length; i += 1) {
812
+ defineProperty(object, props[i], map[props[i]], predicates[props[i]]);
813
+ }
814
+ };
815
+
816
+ defineProperties$1.supportsDescriptors = !!supportsDescriptors;
817
+
818
+ var defineProperties_1 = defineProperties$1;
819
+
820
+ var implementation$2 = commonjsGlobal;
821
+
822
+ var implementation$1 = implementation$2;
823
+
824
+ var polyfill$1 = function getPolyfill() {
825
+ if (typeof commonjsGlobal !== 'object' || !commonjsGlobal || commonjsGlobal.Math !== Math || commonjsGlobal.Array !== Array) {
826
+ return implementation$1;
827
+ }
828
+ return commonjsGlobal;
829
+ };
830
+
831
+ var define = defineProperties_1;
832
+ var getPolyfill$1 = polyfill$1;
833
+
834
+ var shim$1 = function shimGlobal() {
835
+ var polyfill = getPolyfill$1();
836
+ if (define.supportsDescriptors) {
837
+ var descriptor = Object.getOwnPropertyDescriptor(polyfill, 'globalThis');
838
+ if (!descriptor || (descriptor.configurable && (descriptor.enumerable || !descriptor.writable || globalThis !== polyfill))) { // eslint-disable-line max-len
839
+ Object.defineProperty(polyfill, 'globalThis', {
840
+ configurable: true,
841
+ enumerable: false,
842
+ value: polyfill,
843
+ writable: true
844
+ });
845
+ }
846
+ } else if (typeof globalThis !== 'object' || globalThis !== polyfill) {
847
+ polyfill.globalThis = polyfill;
848
+ }
849
+ return polyfill;
850
+ };
851
+
852
+ var defineProperties = defineProperties_1;
853
+
854
+ var implementation = implementation$2;
855
+ var getPolyfill = polyfill$1;
856
+ var shim = shim$1;
857
+
858
+ var polyfill = getPolyfill();
859
+
860
+ var getGlobal$1 = function () { return polyfill; };
861
+
862
+ defineProperties(getGlobal$1, {
863
+ getPolyfill: getPolyfill,
864
+ implementation: implementation,
865
+ shim: shim
866
+ });
867
+
868
+ var globalthis = getGlobal$1;
869
+
870
+ var __extends = (commonjsGlobal && commonjsGlobal.__extends) || (function () {
871
+ var extendStatics = function (d, b) {
872
+ extendStatics = Object.setPrototypeOf ||
873
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
874
+ function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; };
875
+ return extendStatics(d, b);
876
+ };
877
+ return function (d, b) {
878
+ extendStatics(d, b);
879
+ function __() { this.constructor = d; }
880
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
881
+ };
882
+ })();
883
+ Object.defineProperty(xstream, "__esModule", { value: true });
884
+ xstream.NO_IL = xstream.NO = xstream.MemoryStream = xstream.Stream = void 0;
885
+ var ponyfill_1 = ponyfill$1.exports;
886
+ var globalthis_1 = globalthis;
887
+ var $$observable = ponyfill_1.default(globalthis_1.getPolyfill());
888
+ var NO$1 = {};
889
+ xstream.NO = NO$1;
890
+ function noop() { }
891
+ function cp(a) {
892
+ var l = a.length;
893
+ var b = Array(l);
894
+ for (var i = 0; i < l; ++i)
895
+ b[i] = a[i];
896
+ return b;
897
+ }
898
+ function and(f1, f2) {
899
+ return function andFn(t) {
900
+ return f1(t) && f2(t);
901
+ };
902
+ }
903
+ function _try(c, t, u) {
904
+ try {
905
+ return c.f(t);
906
+ }
907
+ catch (e) {
908
+ u._e(e);
909
+ return NO$1;
910
+ }
911
+ }
912
+ var NO_IL = {
913
+ _n: noop,
914
+ _e: noop,
915
+ _c: noop,
916
+ };
917
+ xstream.NO_IL = NO_IL;
918
+ // mutates the input
919
+ function internalizeProducer(producer) {
920
+ producer._start = function _start(il) {
921
+ il.next = il._n;
922
+ il.error = il._e;
923
+ il.complete = il._c;
924
+ this.start(il);
925
+ };
926
+ producer._stop = producer.stop;
927
+ }
928
+ var StreamSub = /** @class */ (function () {
929
+ function StreamSub(_stream, _listener) {
930
+ this._stream = _stream;
931
+ this._listener = _listener;
932
+ }
933
+ StreamSub.prototype.unsubscribe = function () {
934
+ this._stream._remove(this._listener);
935
+ };
936
+ return StreamSub;
937
+ }());
938
+ var Observer = /** @class */ (function () {
939
+ function Observer(_listener) {
940
+ this._listener = _listener;
941
+ }
942
+ Observer.prototype.next = function (value) {
943
+ this._listener._n(value);
944
+ };
945
+ Observer.prototype.error = function (err) {
946
+ this._listener._e(err);
947
+ };
948
+ Observer.prototype.complete = function () {
949
+ this._listener._c();
950
+ };
951
+ return Observer;
952
+ }());
953
+ var FromObservable = /** @class */ (function () {
954
+ function FromObservable(observable) {
955
+ this.type = 'fromObservable';
956
+ this.ins = observable;
957
+ this.active = false;
958
+ }
959
+ FromObservable.prototype._start = function (out) {
960
+ this.out = out;
961
+ this.active = true;
962
+ this._sub = this.ins.subscribe(new Observer(out));
963
+ if (!this.active)
964
+ this._sub.unsubscribe();
965
+ };
966
+ FromObservable.prototype._stop = function () {
967
+ if (this._sub)
968
+ this._sub.unsubscribe();
969
+ this.active = false;
970
+ };
971
+ return FromObservable;
972
+ }());
973
+ var Merge = /** @class */ (function () {
974
+ function Merge(insArr) {
975
+ this.type = 'merge';
976
+ this.insArr = insArr;
977
+ this.out = NO$1;
978
+ this.ac = 0;
979
+ }
980
+ Merge.prototype._start = function (out) {
981
+ this.out = out;
982
+ var s = this.insArr;
983
+ var L = s.length;
984
+ this.ac = L;
985
+ for (var i = 0; i < L; i++)
986
+ s[i]._add(this);
987
+ };
988
+ Merge.prototype._stop = function () {
989
+ var s = this.insArr;
990
+ var L = s.length;
991
+ for (var i = 0; i < L; i++)
992
+ s[i]._remove(this);
993
+ this.out = NO$1;
994
+ };
995
+ Merge.prototype._n = function (t) {
996
+ var u = this.out;
997
+ if (u === NO$1)
998
+ return;
999
+ u._n(t);
1000
+ };
1001
+ Merge.prototype._e = function (err) {
1002
+ var u = this.out;
1003
+ if (u === NO$1)
1004
+ return;
1005
+ u._e(err);
1006
+ };
1007
+ Merge.prototype._c = function () {
1008
+ if (--this.ac <= 0) {
1009
+ var u = this.out;
1010
+ if (u === NO$1)
1011
+ return;
1012
+ u._c();
1013
+ }
1014
+ };
1015
+ return Merge;
1016
+ }());
1017
+ var CombineListener = /** @class */ (function () {
1018
+ function CombineListener(i, out, p) {
1019
+ this.i = i;
1020
+ this.out = out;
1021
+ this.p = p;
1022
+ p.ils.push(this);
1023
+ }
1024
+ CombineListener.prototype._n = function (t) {
1025
+ var p = this.p, out = this.out;
1026
+ if (out === NO$1)
1027
+ return;
1028
+ if (p.up(t, this.i)) {
1029
+ var b = cp(p.vals);
1030
+ out._n(b);
1031
+ }
1032
+ };
1033
+ CombineListener.prototype._e = function (err) {
1034
+ var out = this.out;
1035
+ if (out === NO$1)
1036
+ return;
1037
+ out._e(err);
1038
+ };
1039
+ CombineListener.prototype._c = function () {
1040
+ var p = this.p;
1041
+ if (p.out === NO$1)
1042
+ return;
1043
+ if (--p.Nc === 0)
1044
+ p.out._c();
1045
+ };
1046
+ return CombineListener;
1047
+ }());
1048
+ var Combine = /** @class */ (function () {
1049
+ function Combine(insArr) {
1050
+ this.type = 'combine';
1051
+ this.insArr = insArr;
1052
+ this.out = NO$1;
1053
+ this.ils = [];
1054
+ this.Nc = this.Nn = 0;
1055
+ this.vals = [];
1056
+ }
1057
+ Combine.prototype.up = function (t, i) {
1058
+ var v = this.vals[i];
1059
+ var Nn = !this.Nn ? 0 : v === NO$1 ? --this.Nn : this.Nn;
1060
+ this.vals[i] = t;
1061
+ return Nn === 0;
1062
+ };
1063
+ Combine.prototype._start = function (out) {
1064
+ this.out = out;
1065
+ var s = this.insArr;
1066
+ var n = this.Nc = this.Nn = s.length;
1067
+ var vals = this.vals = new Array(n);
1068
+ if (n === 0) {
1069
+ out._n([]);
1070
+ out._c();
1071
+ }
1072
+ else {
1073
+ for (var i = 0; i < n; i++) {
1074
+ vals[i] = NO$1;
1075
+ s[i]._add(new CombineListener(i, out, this));
1076
+ }
1077
+ }
1078
+ };
1079
+ Combine.prototype._stop = function () {
1080
+ var s = this.insArr;
1081
+ var n = s.length;
1082
+ var ils = this.ils;
1083
+ for (var i = 0; i < n; i++)
1084
+ s[i]._remove(ils[i]);
1085
+ this.out = NO$1;
1086
+ this.ils = [];
1087
+ this.vals = [];
1088
+ };
1089
+ return Combine;
1090
+ }());
1091
+ var FromArray = /** @class */ (function () {
1092
+ function FromArray(a) {
1093
+ this.type = 'fromArray';
1094
+ this.a = a;
1095
+ }
1096
+ FromArray.prototype._start = function (out) {
1097
+ var a = this.a;
1098
+ for (var i = 0, n = a.length; i < n; i++)
1099
+ out._n(a[i]);
1100
+ out._c();
1101
+ };
1102
+ FromArray.prototype._stop = function () {
1103
+ };
1104
+ return FromArray;
1105
+ }());
1106
+ var FromPromise = /** @class */ (function () {
1107
+ function FromPromise(p) {
1108
+ this.type = 'fromPromise';
1109
+ this.on = false;
1110
+ this.p = p;
1111
+ }
1112
+ FromPromise.prototype._start = function (out) {
1113
+ var prod = this;
1114
+ this.on = true;
1115
+ this.p.then(function (v) {
1116
+ if (prod.on) {
1117
+ out._n(v);
1118
+ out._c();
1119
+ }
1120
+ }, function (e) {
1121
+ out._e(e);
1122
+ }).then(noop, function (err) {
1123
+ setTimeout(function () { throw err; });
1124
+ });
1125
+ };
1126
+ FromPromise.prototype._stop = function () {
1127
+ this.on = false;
1128
+ };
1129
+ return FromPromise;
1130
+ }());
1131
+ var Periodic = /** @class */ (function () {
1132
+ function Periodic(period) {
1133
+ this.type = 'periodic';
1134
+ this.period = period;
1135
+ this.intervalID = -1;
1136
+ this.i = 0;
1137
+ }
1138
+ Periodic.prototype._start = function (out) {
1139
+ var self = this;
1140
+ function intervalHandler() { out._n(self.i++); }
1141
+ this.intervalID = setInterval(intervalHandler, this.period);
1142
+ };
1143
+ Periodic.prototype._stop = function () {
1144
+ if (this.intervalID !== -1)
1145
+ clearInterval(this.intervalID);
1146
+ this.intervalID = -1;
1147
+ this.i = 0;
1148
+ };
1149
+ return Periodic;
1150
+ }());
1151
+ var Debug = /** @class */ (function () {
1152
+ function Debug(ins, arg) {
1153
+ this.type = 'debug';
1154
+ this.ins = ins;
1155
+ this.out = NO$1;
1156
+ this.s = noop;
1157
+ this.l = '';
1158
+ if (typeof arg === 'string')
1159
+ this.l = arg;
1160
+ else if (typeof arg === 'function')
1161
+ this.s = arg;
1162
+ }
1163
+ Debug.prototype._start = function (out) {
1164
+ this.out = out;
1165
+ this.ins._add(this);
1166
+ };
1167
+ Debug.prototype._stop = function () {
1168
+ this.ins._remove(this);
1169
+ this.out = NO$1;
1170
+ };
1171
+ Debug.prototype._n = function (t) {
1172
+ var u = this.out;
1173
+ if (u === NO$1)
1174
+ return;
1175
+ var s = this.s, l = this.l;
1176
+ if (s !== noop) {
1177
+ try {
1178
+ s(t);
1179
+ }
1180
+ catch (e) {
1181
+ u._e(e);
1182
+ }
1183
+ }
1184
+ else if (l)
1185
+ console.log(l + ':', t);
1186
+ else
1187
+ console.log(t);
1188
+ u._n(t);
1189
+ };
1190
+ Debug.prototype._e = function (err) {
1191
+ var u = this.out;
1192
+ if (u === NO$1)
1193
+ return;
1194
+ u._e(err);
1195
+ };
1196
+ Debug.prototype._c = function () {
1197
+ var u = this.out;
1198
+ if (u === NO$1)
1199
+ return;
1200
+ u._c();
1201
+ };
1202
+ return Debug;
1203
+ }());
1204
+ var Drop = /** @class */ (function () {
1205
+ function Drop(max, ins) {
1206
+ this.type = 'drop';
1207
+ this.ins = ins;
1208
+ this.out = NO$1;
1209
+ this.max = max;
1210
+ this.dropped = 0;
1211
+ }
1212
+ Drop.prototype._start = function (out) {
1213
+ this.out = out;
1214
+ this.dropped = 0;
1215
+ this.ins._add(this);
1216
+ };
1217
+ Drop.prototype._stop = function () {
1218
+ this.ins._remove(this);
1219
+ this.out = NO$1;
1220
+ };
1221
+ Drop.prototype._n = function (t) {
1222
+ var u = this.out;
1223
+ if (u === NO$1)
1224
+ return;
1225
+ if (this.dropped++ >= this.max)
1226
+ u._n(t);
1227
+ };
1228
+ Drop.prototype._e = function (err) {
1229
+ var u = this.out;
1230
+ if (u === NO$1)
1231
+ return;
1232
+ u._e(err);
1233
+ };
1234
+ Drop.prototype._c = function () {
1235
+ var u = this.out;
1236
+ if (u === NO$1)
1237
+ return;
1238
+ u._c();
1239
+ };
1240
+ return Drop;
1241
+ }());
1242
+ var EndWhenListener = /** @class */ (function () {
1243
+ function EndWhenListener(out, op) {
1244
+ this.out = out;
1245
+ this.op = op;
1246
+ }
1247
+ EndWhenListener.prototype._n = function () {
1248
+ this.op.end();
1249
+ };
1250
+ EndWhenListener.prototype._e = function (err) {
1251
+ this.out._e(err);
1252
+ };
1253
+ EndWhenListener.prototype._c = function () {
1254
+ this.op.end();
1255
+ };
1256
+ return EndWhenListener;
1257
+ }());
1258
+ var EndWhen = /** @class */ (function () {
1259
+ function EndWhen(o, ins) {
1260
+ this.type = 'endWhen';
1261
+ this.ins = ins;
1262
+ this.out = NO$1;
1263
+ this.o = o;
1264
+ this.oil = NO_IL;
1265
+ }
1266
+ EndWhen.prototype._start = function (out) {
1267
+ this.out = out;
1268
+ this.o._add(this.oil = new EndWhenListener(out, this));
1269
+ this.ins._add(this);
1270
+ };
1271
+ EndWhen.prototype._stop = function () {
1272
+ this.ins._remove(this);
1273
+ this.o._remove(this.oil);
1274
+ this.out = NO$1;
1275
+ this.oil = NO_IL;
1276
+ };
1277
+ EndWhen.prototype.end = function () {
1278
+ var u = this.out;
1279
+ if (u === NO$1)
1280
+ return;
1281
+ u._c();
1282
+ };
1283
+ EndWhen.prototype._n = function (t) {
1284
+ var u = this.out;
1285
+ if (u === NO$1)
1286
+ return;
1287
+ u._n(t);
1288
+ };
1289
+ EndWhen.prototype._e = function (err) {
1290
+ var u = this.out;
1291
+ if (u === NO$1)
1292
+ return;
1293
+ u._e(err);
1294
+ };
1295
+ EndWhen.prototype._c = function () {
1296
+ this.end();
1297
+ };
1298
+ return EndWhen;
1299
+ }());
1300
+ var Filter = /** @class */ (function () {
1301
+ function Filter(passes, ins) {
1302
+ this.type = 'filter';
1303
+ this.ins = ins;
1304
+ this.out = NO$1;
1305
+ this.f = passes;
1306
+ }
1307
+ Filter.prototype._start = function (out) {
1308
+ this.out = out;
1309
+ this.ins._add(this);
1310
+ };
1311
+ Filter.prototype._stop = function () {
1312
+ this.ins._remove(this);
1313
+ this.out = NO$1;
1314
+ };
1315
+ Filter.prototype._n = function (t) {
1316
+ var u = this.out;
1317
+ if (u === NO$1)
1318
+ return;
1319
+ var r = _try(this, t, u);
1320
+ if (r === NO$1 || !r)
1321
+ return;
1322
+ u._n(t);
1323
+ };
1324
+ Filter.prototype._e = function (err) {
1325
+ var u = this.out;
1326
+ if (u === NO$1)
1327
+ return;
1328
+ u._e(err);
1329
+ };
1330
+ Filter.prototype._c = function () {
1331
+ var u = this.out;
1332
+ if (u === NO$1)
1333
+ return;
1334
+ u._c();
1335
+ };
1336
+ return Filter;
1337
+ }());
1338
+ var FlattenListener = /** @class */ (function () {
1339
+ function FlattenListener(out, op) {
1340
+ this.out = out;
1341
+ this.op = op;
1342
+ }
1343
+ FlattenListener.prototype._n = function (t) {
1344
+ this.out._n(t);
1345
+ };
1346
+ FlattenListener.prototype._e = function (err) {
1347
+ this.out._e(err);
1348
+ };
1349
+ FlattenListener.prototype._c = function () {
1350
+ this.op.inner = NO$1;
1351
+ this.op.less();
1352
+ };
1353
+ return FlattenListener;
1354
+ }());
1355
+ var Flatten = /** @class */ (function () {
1356
+ function Flatten(ins) {
1357
+ this.type = 'flatten';
1358
+ this.ins = ins;
1359
+ this.out = NO$1;
1360
+ this.open = true;
1361
+ this.inner = NO$1;
1362
+ this.il = NO_IL;
1363
+ }
1364
+ Flatten.prototype._start = function (out) {
1365
+ this.out = out;
1366
+ this.open = true;
1367
+ this.inner = NO$1;
1368
+ this.il = NO_IL;
1369
+ this.ins._add(this);
1370
+ };
1371
+ Flatten.prototype._stop = function () {
1372
+ this.ins._remove(this);
1373
+ if (this.inner !== NO$1)
1374
+ this.inner._remove(this.il);
1375
+ this.out = NO$1;
1376
+ this.open = true;
1377
+ this.inner = NO$1;
1378
+ this.il = NO_IL;
1379
+ };
1380
+ Flatten.prototype.less = function () {
1381
+ var u = this.out;
1382
+ if (u === NO$1)
1383
+ return;
1384
+ if (!this.open && this.inner === NO$1)
1385
+ u._c();
1386
+ };
1387
+ Flatten.prototype._n = function (s) {
1388
+ var u = this.out;
1389
+ if (u === NO$1)
1390
+ return;
1391
+ var _a = this, inner = _a.inner, il = _a.il;
1392
+ if (inner !== NO$1 && il !== NO_IL)
1393
+ inner._remove(il);
1394
+ (this.inner = s)._add(this.il = new FlattenListener(u, this));
1395
+ };
1396
+ Flatten.prototype._e = function (err) {
1397
+ var u = this.out;
1398
+ if (u === NO$1)
1399
+ return;
1400
+ u._e(err);
1401
+ };
1402
+ Flatten.prototype._c = function () {
1403
+ this.open = false;
1404
+ this.less();
1405
+ };
1406
+ return Flatten;
1407
+ }());
1408
+ var Fold = /** @class */ (function () {
1409
+ function Fold(f, seed, ins) {
1410
+ var _this = this;
1411
+ this.type = 'fold';
1412
+ this.ins = ins;
1413
+ this.out = NO$1;
1414
+ this.f = function (t) { return f(_this.acc, t); };
1415
+ this.acc = this.seed = seed;
1416
+ }
1417
+ Fold.prototype._start = function (out) {
1418
+ this.out = out;
1419
+ this.acc = this.seed;
1420
+ out._n(this.acc);
1421
+ this.ins._add(this);
1422
+ };
1423
+ Fold.prototype._stop = function () {
1424
+ this.ins._remove(this);
1425
+ this.out = NO$1;
1426
+ this.acc = this.seed;
1427
+ };
1428
+ Fold.prototype._n = function (t) {
1429
+ var u = this.out;
1430
+ if (u === NO$1)
1431
+ return;
1432
+ var r = _try(this, t, u);
1433
+ if (r === NO$1)
1434
+ return;
1435
+ u._n(this.acc = r);
1436
+ };
1437
+ Fold.prototype._e = function (err) {
1438
+ var u = this.out;
1439
+ if (u === NO$1)
1440
+ return;
1441
+ u._e(err);
1442
+ };
1443
+ Fold.prototype._c = function () {
1444
+ var u = this.out;
1445
+ if (u === NO$1)
1446
+ return;
1447
+ u._c();
1448
+ };
1449
+ return Fold;
1450
+ }());
1451
+ var Last = /** @class */ (function () {
1452
+ function Last(ins) {
1453
+ this.type = 'last';
1454
+ this.ins = ins;
1455
+ this.out = NO$1;
1456
+ this.has = false;
1457
+ this.val = NO$1;
1458
+ }
1459
+ Last.prototype._start = function (out) {
1460
+ this.out = out;
1461
+ this.has = false;
1462
+ this.ins._add(this);
1463
+ };
1464
+ Last.prototype._stop = function () {
1465
+ this.ins._remove(this);
1466
+ this.out = NO$1;
1467
+ this.val = NO$1;
1468
+ };
1469
+ Last.prototype._n = function (t) {
1470
+ this.has = true;
1471
+ this.val = t;
1472
+ };
1473
+ Last.prototype._e = function (err) {
1474
+ var u = this.out;
1475
+ if (u === NO$1)
1476
+ return;
1477
+ u._e(err);
1478
+ };
1479
+ Last.prototype._c = function () {
1480
+ var u = this.out;
1481
+ if (u === NO$1)
1482
+ return;
1483
+ if (this.has) {
1484
+ u._n(this.val);
1485
+ u._c();
1486
+ }
1487
+ else
1488
+ u._e(new Error('last() failed because input stream completed'));
1489
+ };
1490
+ return Last;
1491
+ }());
1492
+ var MapOp = /** @class */ (function () {
1493
+ function MapOp(project, ins) {
1494
+ this.type = 'map';
1495
+ this.ins = ins;
1496
+ this.out = NO$1;
1497
+ this.f = project;
1498
+ }
1499
+ MapOp.prototype._start = function (out) {
1500
+ this.out = out;
1501
+ this.ins._add(this);
1502
+ };
1503
+ MapOp.prototype._stop = function () {
1504
+ this.ins._remove(this);
1505
+ this.out = NO$1;
1506
+ };
1507
+ MapOp.prototype._n = function (t) {
1508
+ var u = this.out;
1509
+ if (u === NO$1)
1510
+ return;
1511
+ var r = _try(this, t, u);
1512
+ if (r === NO$1)
1513
+ return;
1514
+ u._n(r);
1515
+ };
1516
+ MapOp.prototype._e = function (err) {
1517
+ var u = this.out;
1518
+ if (u === NO$1)
1519
+ return;
1520
+ u._e(err);
1521
+ };
1522
+ MapOp.prototype._c = function () {
1523
+ var u = this.out;
1524
+ if (u === NO$1)
1525
+ return;
1526
+ u._c();
1527
+ };
1528
+ return MapOp;
1529
+ }());
1530
+ var Remember = /** @class */ (function () {
1531
+ function Remember(ins) {
1532
+ this.type = 'remember';
1533
+ this.ins = ins;
1534
+ this.out = NO$1;
1535
+ }
1536
+ Remember.prototype._start = function (out) {
1537
+ this.out = out;
1538
+ this.ins._add(out);
1539
+ };
1540
+ Remember.prototype._stop = function () {
1541
+ this.ins._remove(this.out);
1542
+ this.out = NO$1;
1543
+ };
1544
+ return Remember;
1545
+ }());
1546
+ var ReplaceError = /** @class */ (function () {
1547
+ function ReplaceError(replacer, ins) {
1548
+ this.type = 'replaceError';
1549
+ this.ins = ins;
1550
+ this.out = NO$1;
1551
+ this.f = replacer;
1552
+ }
1553
+ ReplaceError.prototype._start = function (out) {
1554
+ this.out = out;
1555
+ this.ins._add(this);
1556
+ };
1557
+ ReplaceError.prototype._stop = function () {
1558
+ this.ins._remove(this);
1559
+ this.out = NO$1;
1560
+ };
1561
+ ReplaceError.prototype._n = function (t) {
1562
+ var u = this.out;
1563
+ if (u === NO$1)
1564
+ return;
1565
+ u._n(t);
1566
+ };
1567
+ ReplaceError.prototype._e = function (err) {
1568
+ var u = this.out;
1569
+ if (u === NO$1)
1570
+ return;
1571
+ try {
1572
+ this.ins._remove(this);
1573
+ (this.ins = this.f(err))._add(this);
1574
+ }
1575
+ catch (e) {
1576
+ u._e(e);
1577
+ }
1578
+ };
1579
+ ReplaceError.prototype._c = function () {
1580
+ var u = this.out;
1581
+ if (u === NO$1)
1582
+ return;
1583
+ u._c();
1584
+ };
1585
+ return ReplaceError;
1586
+ }());
1587
+ var StartWith = /** @class */ (function () {
1588
+ function StartWith(ins, val) {
1589
+ this.type = 'startWith';
1590
+ this.ins = ins;
1591
+ this.out = NO$1;
1592
+ this.val = val;
1593
+ }
1594
+ StartWith.prototype._start = function (out) {
1595
+ this.out = out;
1596
+ this.out._n(this.val);
1597
+ this.ins._add(out);
1598
+ };
1599
+ StartWith.prototype._stop = function () {
1600
+ this.ins._remove(this.out);
1601
+ this.out = NO$1;
1602
+ };
1603
+ return StartWith;
1604
+ }());
1605
+ var Take = /** @class */ (function () {
1606
+ function Take(max, ins) {
1607
+ this.type = 'take';
1608
+ this.ins = ins;
1609
+ this.out = NO$1;
1610
+ this.max = max;
1611
+ this.taken = 0;
1612
+ }
1613
+ Take.prototype._start = function (out) {
1614
+ this.out = out;
1615
+ this.taken = 0;
1616
+ if (this.max <= 0)
1617
+ out._c();
1618
+ else
1619
+ this.ins._add(this);
1620
+ };
1621
+ Take.prototype._stop = function () {
1622
+ this.ins._remove(this);
1623
+ this.out = NO$1;
1624
+ };
1625
+ Take.prototype._n = function (t) {
1626
+ var u = this.out;
1627
+ if (u === NO$1)
1628
+ return;
1629
+ var m = ++this.taken;
1630
+ if (m < this.max)
1631
+ u._n(t);
1632
+ else if (m === this.max) {
1633
+ u._n(t);
1634
+ u._c();
1635
+ }
1636
+ };
1637
+ Take.prototype._e = function (err) {
1638
+ var u = this.out;
1639
+ if (u === NO$1)
1640
+ return;
1641
+ u._e(err);
1642
+ };
1643
+ Take.prototype._c = function () {
1644
+ var u = this.out;
1645
+ if (u === NO$1)
1646
+ return;
1647
+ u._c();
1648
+ };
1649
+ return Take;
1650
+ }());
1651
+ var Stream = /** @class */ (function () {
1652
+ function Stream(producer) {
1653
+ this._prod = producer || NO$1;
1654
+ this._ils = [];
1655
+ this._stopID = NO$1;
1656
+ this._dl = NO$1;
1657
+ this._d = false;
1658
+ this._target = null;
1659
+ this._err = NO$1;
1660
+ }
1661
+ Stream.prototype._n = function (t) {
1662
+ var a = this._ils;
1663
+ var L = a.length;
1664
+ if (this._d)
1665
+ this._dl._n(t);
1666
+ if (L == 1)
1667
+ a[0]._n(t);
1668
+ else if (L == 0)
1669
+ return;
1670
+ else {
1671
+ var b = cp(a);
1672
+ for (var i = 0; i < L; i++)
1673
+ b[i]._n(t);
1674
+ }
1675
+ };
1676
+ Stream.prototype._e = function (err) {
1677
+ if (this._err !== NO$1)
1678
+ return;
1679
+ this._err = err;
1680
+ var a = this._ils;
1681
+ var L = a.length;
1682
+ this._x();
1683
+ if (this._d)
1684
+ this._dl._e(err);
1685
+ if (L == 1)
1686
+ a[0]._e(err);
1687
+ else if (L == 0)
1688
+ return;
1689
+ else {
1690
+ var b = cp(a);
1691
+ for (var i = 0; i < L; i++)
1692
+ b[i]._e(err);
1693
+ }
1694
+ if (!this._d && L == 0)
1695
+ throw this._err;
1696
+ };
1697
+ Stream.prototype._c = function () {
1698
+ var a = this._ils;
1699
+ var L = a.length;
1700
+ this._x();
1701
+ if (this._d)
1702
+ this._dl._c();
1703
+ if (L == 1)
1704
+ a[0]._c();
1705
+ else if (L == 0)
1706
+ return;
1707
+ else {
1708
+ var b = cp(a);
1709
+ for (var i = 0; i < L; i++)
1710
+ b[i]._c();
1711
+ }
1712
+ };
1713
+ Stream.prototype._x = function () {
1714
+ if (this._ils.length === 0)
1715
+ return;
1716
+ if (this._prod !== NO$1)
1717
+ this._prod._stop();
1718
+ this._err = NO$1;
1719
+ this._ils = [];
1720
+ };
1721
+ Stream.prototype._stopNow = function () {
1722
+ // WARNING: code that calls this method should
1723
+ // first check if this._prod is valid (not `NO`)
1724
+ this._prod._stop();
1725
+ this._err = NO$1;
1726
+ this._stopID = NO$1;
1727
+ };
1728
+ Stream.prototype._add = function (il) {
1729
+ var ta = this._target;
1730
+ if (ta)
1731
+ return ta._add(il);
1732
+ var a = this._ils;
1733
+ a.push(il);
1734
+ if (a.length > 1)
1735
+ return;
1736
+ if (this._stopID !== NO$1) {
1737
+ clearTimeout(this._stopID);
1738
+ this._stopID = NO$1;
1739
+ }
1740
+ else {
1741
+ var p = this._prod;
1742
+ if (p !== NO$1)
1743
+ p._start(this);
1744
+ }
1745
+ };
1746
+ Stream.prototype._remove = function (il) {
1747
+ var _this = this;
1748
+ var ta = this._target;
1749
+ if (ta)
1750
+ return ta._remove(il);
1751
+ var a = this._ils;
1752
+ var i = a.indexOf(il);
1753
+ if (i > -1) {
1754
+ a.splice(i, 1);
1755
+ if (this._prod !== NO$1 && a.length <= 0) {
1756
+ this._err = NO$1;
1757
+ this._stopID = setTimeout(function () { return _this._stopNow(); });
1758
+ }
1759
+ else if (a.length === 1) {
1760
+ this._pruneCycles();
1761
+ }
1762
+ }
1763
+ };
1764
+ // If all paths stemming from `this` stream eventually end at `this`
1765
+ // stream, then we remove the single listener of `this` stream, to
1766
+ // force it to end its execution and dispose resources. This method
1767
+ // assumes as a precondition that this._ils has just one listener.
1768
+ Stream.prototype._pruneCycles = function () {
1769
+ if (this._hasNoSinks(this, []))
1770
+ this._remove(this._ils[0]);
1771
+ };
1772
+ // Checks whether *there is no* path starting from `x` that leads to an end
1773
+ // listener (sink) in the stream graph, following edges A->B where B is a
1774
+ // listener of A. This means these paths constitute a cycle somehow. Is given
1775
+ // a trace of all visited nodes so far.
1776
+ Stream.prototype._hasNoSinks = function (x, trace) {
1777
+ if (trace.indexOf(x) !== -1)
1778
+ return true;
1779
+ else if (x.out === this)
1780
+ return true;
1781
+ else if (x.out && x.out !== NO$1)
1782
+ return this._hasNoSinks(x.out, trace.concat(x));
1783
+ else if (x._ils) {
1784
+ for (var i = 0, N = x._ils.length; i < N; i++)
1785
+ if (!this._hasNoSinks(x._ils[i], trace.concat(x)))
1786
+ return false;
1787
+ return true;
1788
+ }
1789
+ else
1790
+ return false;
1791
+ };
1792
+ Stream.prototype.ctor = function () {
1793
+ return this instanceof MemoryStream ? MemoryStream : Stream;
1794
+ };
1795
+ /**
1796
+ * Adds a Listener to the Stream.
1797
+ *
1798
+ * @param {Listener} listener
1799
+ */
1800
+ Stream.prototype.addListener = function (listener) {
1801
+ listener._n = listener.next || noop;
1802
+ listener._e = listener.error || noop;
1803
+ listener._c = listener.complete || noop;
1804
+ this._add(listener);
1805
+ };
1806
+ /**
1807
+ * Removes a Listener from the Stream, assuming the Listener was added to it.
1808
+ *
1809
+ * @param {Listener<T>} listener
1810
+ */
1811
+ Stream.prototype.removeListener = function (listener) {
1812
+ this._remove(listener);
1813
+ };
1814
+ /**
1815
+ * Adds a Listener to the Stream returning a Subscription to remove that
1816
+ * listener.
1817
+ *
1818
+ * @param {Listener} listener
1819
+ * @returns {Subscription}
1820
+ */
1821
+ Stream.prototype.subscribe = function (listener) {
1822
+ this.addListener(listener);
1823
+ return new StreamSub(this, listener);
1824
+ };
1825
+ /**
1826
+ * Add interop between most.js and RxJS 5
1827
+ *
1828
+ * @returns {Stream}
1829
+ */
1830
+ Stream.prototype[$$observable] = function () {
1831
+ return this;
1832
+ };
1833
+ /**
1834
+ * Creates a new Stream given a Producer.
1835
+ *
1836
+ * @factory true
1837
+ * @param {Producer} producer An optional Producer that dictates how to
1838
+ * start, generate events, and stop the Stream.
1839
+ * @return {Stream}
1840
+ */
1841
+ Stream.create = function (producer) {
1842
+ if (producer) {
1843
+ if (typeof producer.start !== 'function'
1844
+ || typeof producer.stop !== 'function')
1845
+ throw new Error('producer requires both start and stop functions');
1846
+ internalizeProducer(producer); // mutates the input
1847
+ }
1848
+ return new Stream(producer);
1849
+ };
1850
+ /**
1851
+ * Creates a new MemoryStream given a Producer.
1852
+ *
1853
+ * @factory true
1854
+ * @param {Producer} producer An optional Producer that dictates how to
1855
+ * start, generate events, and stop the Stream.
1856
+ * @return {MemoryStream}
1857
+ */
1858
+ Stream.createWithMemory = function (producer) {
1859
+ if (producer)
1860
+ internalizeProducer(producer); // mutates the input
1861
+ return new MemoryStream(producer);
1862
+ };
1863
+ /**
1864
+ * Creates a Stream that does nothing when started. It never emits any event.
1865
+ *
1866
+ * Marble diagram:
1867
+ *
1868
+ * ```text
1869
+ * never
1870
+ * -----------------------
1871
+ * ```
1872
+ *
1873
+ * @factory true
1874
+ * @return {Stream}
1875
+ */
1876
+ Stream.never = function () {
1877
+ return new Stream({ _start: noop, _stop: noop });
1878
+ };
1879
+ /**
1880
+ * Creates a Stream that immediately emits the "complete" notification when
1881
+ * started, and that's it.
1882
+ *
1883
+ * Marble diagram:
1884
+ *
1885
+ * ```text
1886
+ * empty
1887
+ * -|
1888
+ * ```
1889
+ *
1890
+ * @factory true
1891
+ * @return {Stream}
1892
+ */
1893
+ Stream.empty = function () {
1894
+ return new Stream({
1895
+ _start: function (il) { il._c(); },
1896
+ _stop: noop,
1897
+ });
1898
+ };
1899
+ /**
1900
+ * Creates a Stream that immediately emits an "error" notification with the
1901
+ * value you passed as the `error` argument when the stream starts, and that's
1902
+ * it.
1903
+ *
1904
+ * Marble diagram:
1905
+ *
1906
+ * ```text
1907
+ * throw(X)
1908
+ * -X
1909
+ * ```
1910
+ *
1911
+ * @factory true
1912
+ * @param error The error event to emit on the created stream.
1913
+ * @return {Stream}
1914
+ */
1915
+ Stream.throw = function (error) {
1916
+ return new Stream({
1917
+ _start: function (il) { il._e(error); },
1918
+ _stop: noop,
1919
+ });
1920
+ };
1921
+ /**
1922
+ * Creates a stream from an Array, Promise, or an Observable.
1923
+ *
1924
+ * @factory true
1925
+ * @param {Array|PromiseLike|Observable} input The input to make a stream from.
1926
+ * @return {Stream}
1927
+ */
1928
+ Stream.from = function (input) {
1929
+ if (typeof input[$$observable] === 'function')
1930
+ return Stream.fromObservable(input);
1931
+ else if (typeof input.then === 'function')
1932
+ return Stream.fromPromise(input);
1933
+ else if (Array.isArray(input))
1934
+ return Stream.fromArray(input);
1935
+ throw new TypeError("Type of input to from() must be an Array, Promise, or Observable");
1936
+ };
1937
+ /**
1938
+ * Creates a Stream that immediately emits the arguments that you give to
1939
+ * *of*, then completes.
1940
+ *
1941
+ * Marble diagram:
1942
+ *
1943
+ * ```text
1944
+ * of(1,2,3)
1945
+ * 123|
1946
+ * ```
1947
+ *
1948
+ * @factory true
1949
+ * @param a The first value you want to emit as an event on the stream.
1950
+ * @param b The second value you want to emit as an event on the stream. One
1951
+ * or more of these values may be given as arguments.
1952
+ * @return {Stream}
1953
+ */
1954
+ Stream.of = function () {
1955
+ var items = [];
1956
+ for (var _i = 0; _i < arguments.length; _i++) {
1957
+ items[_i] = arguments[_i];
1958
+ }
1959
+ return Stream.fromArray(items);
1960
+ };
1961
+ /**
1962
+ * Converts an array to a stream. The returned stream will emit synchronously
1963
+ * all the items in the array, and then complete.
1964
+ *
1965
+ * Marble diagram:
1966
+ *
1967
+ * ```text
1968
+ * fromArray([1,2,3])
1969
+ * 123|
1970
+ * ```
1971
+ *
1972
+ * @factory true
1973
+ * @param {Array} array The array to be converted as a stream.
1974
+ * @return {Stream}
1975
+ */
1976
+ Stream.fromArray = function (array) {
1977
+ return new Stream(new FromArray(array));
1978
+ };
1979
+ /**
1980
+ * Converts a promise to a stream. The returned stream will emit the resolved
1981
+ * value of the promise, and then complete. However, if the promise is
1982
+ * rejected, the stream will emit the corresponding error.
1983
+ *
1984
+ * Marble diagram:
1985
+ *
1986
+ * ```text
1987
+ * fromPromise( ----42 )
1988
+ * -----------------42|
1989
+ * ```
1990
+ *
1991
+ * @factory true
1992
+ * @param {PromiseLike} promise The promise to be converted as a stream.
1993
+ * @return {Stream}
1994
+ */
1995
+ Stream.fromPromise = function (promise) {
1996
+ return new Stream(new FromPromise(promise));
1997
+ };
1998
+ /**
1999
+ * Converts an Observable into a Stream.
2000
+ *
2001
+ * @factory true
2002
+ * @param {any} observable The observable to be converted as a stream.
2003
+ * @return {Stream}
2004
+ */
2005
+ Stream.fromObservable = function (obs) {
2006
+ if (obs.endWhen !== undefined)
2007
+ return obs;
2008
+ var o = typeof obs[$$observable] === 'function' ? obs[$$observable]() : obs;
2009
+ return new Stream(new FromObservable(o));
2010
+ };
2011
+ /**
2012
+ * Creates a stream that periodically emits incremental numbers, every
2013
+ * `period` milliseconds.
2014
+ *
2015
+ * Marble diagram:
2016
+ *
2017
+ * ```text
2018
+ * periodic(1000)
2019
+ * ---0---1---2---3---4---...
2020
+ * ```
2021
+ *
2022
+ * @factory true
2023
+ * @param {number} period The interval in milliseconds to use as a rate of
2024
+ * emission.
2025
+ * @return {Stream}
2026
+ */
2027
+ Stream.periodic = function (period) {
2028
+ return new Stream(new Periodic(period));
2029
+ };
2030
+ Stream.prototype._map = function (project) {
2031
+ return new (this.ctor())(new MapOp(project, this));
2032
+ };
2033
+ /**
2034
+ * Transforms each event from the input Stream through a `project` function,
2035
+ * to get a Stream that emits those transformed events.
2036
+ *
2037
+ * Marble diagram:
2038
+ *
2039
+ * ```text
2040
+ * --1---3--5-----7------
2041
+ * map(i => i * 10)
2042
+ * --10--30-50----70-----
2043
+ * ```
2044
+ *
2045
+ * @param {Function} project A function of type `(t: T) => U` that takes event
2046
+ * `t` of type `T` from the input Stream and produces an event of type `U`, to
2047
+ * be emitted on the output Stream.
2048
+ * @return {Stream}
2049
+ */
2050
+ Stream.prototype.map = function (project) {
2051
+ return this._map(project);
2052
+ };
2053
+ /**
2054
+ * It's like `map`, but transforms each input event to always the same
2055
+ * constant value on the output Stream.
2056
+ *
2057
+ * Marble diagram:
2058
+ *
2059
+ * ```text
2060
+ * --1---3--5-----7-----
2061
+ * mapTo(10)
2062
+ * --10--10-10----10----
2063
+ * ```
2064
+ *
2065
+ * @param projectedValue A value to emit on the output Stream whenever the
2066
+ * input Stream emits any value.
2067
+ * @return {Stream}
2068
+ */
2069
+ Stream.prototype.mapTo = function (projectedValue) {
2070
+ var s = this.map(function () { return projectedValue; });
2071
+ var op = s._prod;
2072
+ op.type = 'mapTo';
2073
+ return s;
2074
+ };
2075
+ /**
2076
+ * Only allows events that pass the test given by the `passes` argument.
2077
+ *
2078
+ * Each event from the input stream is given to the `passes` function. If the
2079
+ * function returns `true`, the event is forwarded to the output stream,
2080
+ * otherwise it is ignored and not forwarded.
2081
+ *
2082
+ * Marble diagram:
2083
+ *
2084
+ * ```text
2085
+ * --1---2--3-----4-----5---6--7-8--
2086
+ * filter(i => i % 2 === 0)
2087
+ * ------2--------4---------6----8--
2088
+ * ```
2089
+ *
2090
+ * @param {Function} passes A function of type `(t: T) => boolean` that takes
2091
+ * an event from the input stream and checks if it passes, by returning a
2092
+ * boolean.
2093
+ * @return {Stream}
2094
+ */
2095
+ Stream.prototype.filter = function (passes) {
2096
+ var p = this._prod;
2097
+ if (p instanceof Filter)
2098
+ return new Stream(new Filter(and(p.f, passes), p.ins));
2099
+ return new Stream(new Filter(passes, this));
2100
+ };
2101
+ /**
2102
+ * Lets the first `amount` many events from the input stream pass to the
2103
+ * output stream, then makes the output stream complete.
2104
+ *
2105
+ * Marble diagram:
2106
+ *
2107
+ * ```text
2108
+ * --a---b--c----d---e--
2109
+ * take(3)
2110
+ * --a---b--c|
2111
+ * ```
2112
+ *
2113
+ * @param {number} amount How many events to allow from the input stream
2114
+ * before completing the output stream.
2115
+ * @return {Stream}
2116
+ */
2117
+ Stream.prototype.take = function (amount) {
2118
+ return new (this.ctor())(new Take(amount, this));
2119
+ };
2120
+ /**
2121
+ * Ignores the first `amount` many events from the input stream, and then
2122
+ * after that starts forwarding events from the input stream to the output
2123
+ * stream.
2124
+ *
2125
+ * Marble diagram:
2126
+ *
2127
+ * ```text
2128
+ * --a---b--c----d---e--
2129
+ * drop(3)
2130
+ * --------------d---e--
2131
+ * ```
2132
+ *
2133
+ * @param {number} amount How many events to ignore from the input stream
2134
+ * before forwarding all events from the input stream to the output stream.
2135
+ * @return {Stream}
2136
+ */
2137
+ Stream.prototype.drop = function (amount) {
2138
+ return new Stream(new Drop(amount, this));
2139
+ };
2140
+ /**
2141
+ * When the input stream completes, the output stream will emit the last event
2142
+ * emitted by the input stream, and then will also complete.
2143
+ *
2144
+ * Marble diagram:
2145
+ *
2146
+ * ```text
2147
+ * --a---b--c--d----|
2148
+ * last()
2149
+ * -----------------d|
2150
+ * ```
2151
+ *
2152
+ * @return {Stream}
2153
+ */
2154
+ Stream.prototype.last = function () {
2155
+ return new Stream(new Last(this));
2156
+ };
2157
+ /**
2158
+ * Prepends the given `initial` value to the sequence of events emitted by the
2159
+ * input stream. The returned stream is a MemoryStream, which means it is
2160
+ * already `remember()`'d.
2161
+ *
2162
+ * Marble diagram:
2163
+ *
2164
+ * ```text
2165
+ * ---1---2-----3---
2166
+ * startWith(0)
2167
+ * 0--1---2-----3---
2168
+ * ```
2169
+ *
2170
+ * @param initial The value or event to prepend.
2171
+ * @return {MemoryStream}
2172
+ */
2173
+ Stream.prototype.startWith = function (initial) {
2174
+ return new MemoryStream(new StartWith(this, initial));
2175
+ };
2176
+ /**
2177
+ * Uses another stream to determine when to complete the current stream.
2178
+ *
2179
+ * When the given `other` stream emits an event or completes, the output
2180
+ * stream will complete. Before that happens, the output stream will behaves
2181
+ * like the input stream.
2182
+ *
2183
+ * Marble diagram:
2184
+ *
2185
+ * ```text
2186
+ * ---1---2-----3--4----5----6---
2187
+ * endWhen( --------a--b--| )
2188
+ * ---1---2-----3--4--|
2189
+ * ```
2190
+ *
2191
+ * @param other Some other stream that is used to know when should the output
2192
+ * stream of this operator complete.
2193
+ * @return {Stream}
2194
+ */
2195
+ Stream.prototype.endWhen = function (other) {
2196
+ return new (this.ctor())(new EndWhen(other, this));
2197
+ };
2198
+ /**
2199
+ * "Folds" the stream onto itself.
2200
+ *
2201
+ * Combines events from the past throughout
2202
+ * the entire execution of the input stream, allowing you to accumulate them
2203
+ * together. It's essentially like `Array.prototype.reduce`. The returned
2204
+ * stream is a MemoryStream, which means it is already `remember()`'d.
2205
+ *
2206
+ * The output stream starts by emitting the `seed` which you give as argument.
2207
+ * Then, when an event happens on the input stream, it is combined with that
2208
+ * seed value through the `accumulate` function, and the output value is
2209
+ * emitted on the output stream. `fold` remembers that output value as `acc`
2210
+ * ("accumulator"), and then when a new input event `t` happens, `acc` will be
2211
+ * combined with that to produce the new `acc` and so forth.
2212
+ *
2213
+ * Marble diagram:
2214
+ *
2215
+ * ```text
2216
+ * ------1-----1--2----1----1------
2217
+ * fold((acc, x) => acc + x, 3)
2218
+ * 3-----4-----5--7----8----9------
2219
+ * ```
2220
+ *
2221
+ * @param {Function} accumulate A function of type `(acc: R, t: T) => R` that
2222
+ * takes the previous accumulated value `acc` and the incoming event from the
2223
+ * input stream and produces the new accumulated value.
2224
+ * @param seed The initial accumulated value, of type `R`.
2225
+ * @return {MemoryStream}
2226
+ */
2227
+ Stream.prototype.fold = function (accumulate, seed) {
2228
+ return new MemoryStream(new Fold(accumulate, seed, this));
2229
+ };
2230
+ /**
2231
+ * Replaces an error with another stream.
2232
+ *
2233
+ * When (and if) an error happens on the input stream, instead of forwarding
2234
+ * that error to the output stream, *replaceError* will call the `replace`
2235
+ * function which returns the stream that the output stream will replicate.
2236
+ * And, in case that new stream also emits an error, `replace` will be called
2237
+ * again to get another stream to start replicating.
2238
+ *
2239
+ * Marble diagram:
2240
+ *
2241
+ * ```text
2242
+ * --1---2-----3--4-----X
2243
+ * replaceError( () => --10--| )
2244
+ * --1---2-----3--4--------10--|
2245
+ * ```
2246
+ *
2247
+ * @param {Function} replace A function of type `(err) => Stream` that takes
2248
+ * the error that occurred on the input stream or on the previous replacement
2249
+ * stream and returns a new stream. The output stream will behave like the
2250
+ * stream that this function returns.
2251
+ * @return {Stream}
2252
+ */
2253
+ Stream.prototype.replaceError = function (replace) {
2254
+ return new (this.ctor())(new ReplaceError(replace, this));
2255
+ };
2256
+ /**
2257
+ * Flattens a "stream of streams", handling only one nested stream at a time
2258
+ * (no concurrency).
2259
+ *
2260
+ * If the input stream is a stream that emits streams, then this operator will
2261
+ * return an output stream which is a flat stream: emits regular events. The
2262
+ * flattening happens without concurrency. It works like this: when the input
2263
+ * stream emits a nested stream, *flatten* will start imitating that nested
2264
+ * one. However, as soon as the next nested stream is emitted on the input
2265
+ * stream, *flatten* will forget the previous nested one it was imitating, and
2266
+ * will start imitating the new nested one.
2267
+ *
2268
+ * Marble diagram:
2269
+ *
2270
+ * ```text
2271
+ * --+--------+---------------
2272
+ * \ \
2273
+ * \ ----1----2---3--
2274
+ * --a--b----c----d--------
2275
+ * flatten
2276
+ * -----a--b------1----2---3--
2277
+ * ```
2278
+ *
2279
+ * @return {Stream}
2280
+ */
2281
+ Stream.prototype.flatten = function () {
2282
+ return new Stream(new Flatten(this));
2283
+ };
2284
+ /**
2285
+ * Passes the input stream to a custom operator, to produce an output stream.
2286
+ *
2287
+ * *compose* is a handy way of using an existing function in a chained style.
2288
+ * Instead of writing `outStream = f(inStream)` you can write
2289
+ * `outStream = inStream.compose(f)`.
2290
+ *
2291
+ * @param {function} operator A function that takes a stream as input and
2292
+ * returns a stream as well.
2293
+ * @return {Stream}
2294
+ */
2295
+ Stream.prototype.compose = function (operator) {
2296
+ return operator(this);
2297
+ };
2298
+ /**
2299
+ * Returns an output stream that behaves like the input stream, but also
2300
+ * remembers the most recent event that happens on the input stream, so that a
2301
+ * newly added listener will immediately receive that memorised event.
2302
+ *
2303
+ * @return {MemoryStream}
2304
+ */
2305
+ Stream.prototype.remember = function () {
2306
+ return new MemoryStream(new Remember(this));
2307
+ };
2308
+ /**
2309
+ * Returns an output stream that identically behaves like the input stream,
2310
+ * but also runs a `spy` function for each event, to help you debug your app.
2311
+ *
2312
+ * *debug* takes a `spy` function as argument, and runs that for each event
2313
+ * happening on the input stream. If you don't provide the `spy` argument,
2314
+ * then *debug* will just `console.log` each event. This helps you to
2315
+ * understand the flow of events through some operator chain.
2316
+ *
2317
+ * Please note that if the output stream has no listeners, then it will not
2318
+ * start, which means `spy` will never run because no actual event happens in
2319
+ * that case.
2320
+ *
2321
+ * Marble diagram:
2322
+ *
2323
+ * ```text
2324
+ * --1----2-----3-----4--
2325
+ * debug
2326
+ * --1----2-----3-----4--
2327
+ * ```
2328
+ *
2329
+ * @param {function} labelOrSpy A string to use as the label when printing
2330
+ * debug information on the console, or a 'spy' function that takes an event
2331
+ * as argument, and does not need to return anything.
2332
+ * @return {Stream}
2333
+ */
2334
+ Stream.prototype.debug = function (labelOrSpy) {
2335
+ return new (this.ctor())(new Debug(this, labelOrSpy));
2336
+ };
2337
+ /**
2338
+ * *imitate* changes this current Stream to emit the same events that the
2339
+ * `other` given Stream does. This method returns nothing.
2340
+ *
2341
+ * This method exists to allow one thing: **circular dependency of streams**.
2342
+ * For instance, let's imagine that for some reason you need to create a
2343
+ * circular dependency where stream `first$` depends on stream `second$`
2344
+ * which in turn depends on `first$`:
2345
+ *
2346
+ * <!-- skip-example -->
2347
+ * ```js
2348
+ * import delay from 'xstream/extra/delay'
2349
+ *
2350
+ * var first$ = second$.map(x => x * 10).take(3);
2351
+ * var second$ = first$.map(x => x + 1).startWith(1).compose(delay(100));
2352
+ * ```
2353
+ *
2354
+ * However, that is invalid JavaScript, because `second$` is undefined
2355
+ * on the first line. This is how *imitate* can help solve it:
2356
+ *
2357
+ * ```js
2358
+ * import delay from 'xstream/extra/delay'
2359
+ *
2360
+ * var secondProxy$ = xs.create();
2361
+ * var first$ = secondProxy$.map(x => x * 10).take(3);
2362
+ * var second$ = first$.map(x => x + 1).startWith(1).compose(delay(100));
2363
+ * secondProxy$.imitate(second$);
2364
+ * ```
2365
+ *
2366
+ * We create `secondProxy$` before the others, so it can be used in the
2367
+ * declaration of `first$`. Then, after both `first$` and `second$` are
2368
+ * defined, we hook `secondProxy$` with `second$` with `imitate()` to tell
2369
+ * that they are "the same". `imitate` will not trigger the start of any
2370
+ * stream, it just binds `secondProxy$` and `second$` together.
2371
+ *
2372
+ * The following is an example where `imitate()` is important in Cycle.js
2373
+ * applications. A parent component contains some child components. A child
2374
+ * has an action stream which is given to the parent to define its state:
2375
+ *
2376
+ * <!-- skip-example -->
2377
+ * ```js
2378
+ * const childActionProxy$ = xs.create();
2379
+ * const parent = Parent({...sources, childAction$: childActionProxy$});
2380
+ * const childAction$ = parent.state$.map(s => s.child.action$).flatten();
2381
+ * childActionProxy$.imitate(childAction$);
2382
+ * ```
2383
+ *
2384
+ * Note, though, that **`imitate()` does not support MemoryStreams**. If we
2385
+ * would attempt to imitate a MemoryStream in a circular dependency, we would
2386
+ * either get a race condition (where the symptom would be "nothing happens")
2387
+ * or an infinite cyclic emission of values. It's useful to think about
2388
+ * MemoryStreams as cells in a spreadsheet. It doesn't make any sense to
2389
+ * define a spreadsheet cell `A1` with a formula that depends on `B1` and
2390
+ * cell `B1` defined with a formula that depends on `A1`.
2391
+ *
2392
+ * If you find yourself wanting to use `imitate()` with a
2393
+ * MemoryStream, you should rework your code around `imitate()` to use a
2394
+ * Stream instead. Look for the stream in the circular dependency that
2395
+ * represents an event stream, and that would be a candidate for creating a
2396
+ * proxy Stream which then imitates the target Stream.
2397
+ *
2398
+ * @param {Stream} target The other stream to imitate on the current one. Must
2399
+ * not be a MemoryStream.
2400
+ */
2401
+ Stream.prototype.imitate = function (target) {
2402
+ if (target instanceof MemoryStream)
2403
+ throw new Error('A MemoryStream was given to imitate(), but it only ' +
2404
+ 'supports a Stream. Read more about this restriction here: ' +
2405
+ 'https://github.com/staltz/xstream#faq');
2406
+ this._target = target;
2407
+ for (var ils = this._ils, N = ils.length, i = 0; i < N; i++)
2408
+ target._add(ils[i]);
2409
+ this._ils = [];
2410
+ };
2411
+ /**
2412
+ * Forces the Stream to emit the given value to its listeners.
2413
+ *
2414
+ * As the name indicates, if you use this, you are most likely doing something
2415
+ * The Wrong Way. Please try to understand the reactive way before using this
2416
+ * method. Use it only when you know what you are doing.
2417
+ *
2418
+ * @param value The "next" value you want to broadcast to all listeners of
2419
+ * this Stream.
2420
+ */
2421
+ Stream.prototype.shamefullySendNext = function (value) {
2422
+ this._n(value);
2423
+ };
2424
+ /**
2425
+ * Forces the Stream to emit the given error to its listeners.
2426
+ *
2427
+ * As the name indicates, if you use this, you are most likely doing something
2428
+ * The Wrong Way. Please try to understand the reactive way before using this
2429
+ * method. Use it only when you know what you are doing.
2430
+ *
2431
+ * @param {any} error The error you want to broadcast to all the listeners of
2432
+ * this Stream.
2433
+ */
2434
+ Stream.prototype.shamefullySendError = function (error) {
2435
+ this._e(error);
2436
+ };
2437
+ /**
2438
+ * Forces the Stream to emit the "completed" event to its listeners.
2439
+ *
2440
+ * As the name indicates, if you use this, you are most likely doing something
2441
+ * The Wrong Way. Please try to understand the reactive way before using this
2442
+ * method. Use it only when you know what you are doing.
2443
+ */
2444
+ Stream.prototype.shamefullySendComplete = function () {
2445
+ this._c();
2446
+ };
2447
+ /**
2448
+ * Adds a "debug" listener to the stream. There can only be one debug
2449
+ * listener, that's why this is 'setDebugListener'. To remove the debug
2450
+ * listener, just call setDebugListener(null).
2451
+ *
2452
+ * A debug listener is like any other listener. The only difference is that a
2453
+ * debug listener is "stealthy": its presence/absence does not trigger the
2454
+ * start/stop of the stream (or the producer inside the stream). This is
2455
+ * useful so you can inspect what is going on without changing the behavior
2456
+ * of the program. If you have an idle stream and you add a normal listener to
2457
+ * it, the stream will start executing. But if you set a debug listener on an
2458
+ * idle stream, it won't start executing (not until the first normal listener
2459
+ * is added).
2460
+ *
2461
+ * As the name indicates, we don't recommend using this method to build app
2462
+ * logic. In fact, in most cases the debug operator works just fine. Only use
2463
+ * this one if you know what you're doing.
2464
+ *
2465
+ * @param {Listener<T>} listener
2466
+ */
2467
+ Stream.prototype.setDebugListener = function (listener) {
2468
+ if (!listener) {
2469
+ this._d = false;
2470
+ this._dl = NO$1;
2471
+ }
2472
+ else {
2473
+ this._d = true;
2474
+ listener._n = listener.next || noop;
2475
+ listener._e = listener.error || noop;
2476
+ listener._c = listener.complete || noop;
2477
+ this._dl = listener;
2478
+ }
2479
+ };
2480
+ /**
2481
+ * Blends multiple streams together, emitting events from all of them
2482
+ * concurrently.
2483
+ *
2484
+ * *merge* takes multiple streams as arguments, and creates a stream that
2485
+ * behaves like each of the argument streams, in parallel.
2486
+ *
2487
+ * Marble diagram:
2488
+ *
2489
+ * ```text
2490
+ * --1----2-----3--------4---
2491
+ * ----a-----b----c---d------
2492
+ * merge
2493
+ * --1-a--2--b--3-c---d--4---
2494
+ * ```
2495
+ *
2496
+ * @factory true
2497
+ * @param {Stream} stream1 A stream to merge together with other streams.
2498
+ * @param {Stream} stream2 A stream to merge together with other streams. Two
2499
+ * or more streams may be given as arguments.
2500
+ * @return {Stream}
2501
+ */
2502
+ Stream.merge = function merge() {
2503
+ var streams = [];
2504
+ for (var _i = 0; _i < arguments.length; _i++) {
2505
+ streams[_i] = arguments[_i];
2506
+ }
2507
+ return new Stream(new Merge(streams));
2508
+ };
2509
+ /**
2510
+ * Combines multiple input streams together to return a stream whose events
2511
+ * are arrays that collect the latest events from each input stream.
2512
+ *
2513
+ * *combine* internally remembers the most recent event from each of the input
2514
+ * streams. When any of the input streams emits an event, that event together
2515
+ * with all the other saved events are combined into an array. That array will
2516
+ * be emitted on the output stream. It's essentially a way of joining together
2517
+ * the events from multiple streams.
2518
+ *
2519
+ * Marble diagram:
2520
+ *
2521
+ * ```text
2522
+ * --1----2-----3--------4---
2523
+ * ----a-----b-----c--d------
2524
+ * combine
2525
+ * ----1a-2a-2b-3b-3c-3d-4d--
2526
+ * ```
2527
+ *
2528
+ * @factory true
2529
+ * @param {Stream} stream1 A stream to combine together with other streams.
2530
+ * @param {Stream} stream2 A stream to combine together with other streams.
2531
+ * Multiple streams, not just two, may be given as arguments.
2532
+ * @return {Stream}
2533
+ */
2534
+ Stream.combine = function combine() {
2535
+ var streams = [];
2536
+ for (var _i = 0; _i < arguments.length; _i++) {
2537
+ streams[_i] = arguments[_i];
2538
+ }
2539
+ return new Stream(new Combine(streams));
2540
+ };
2541
+ return Stream;
2542
+ }());
2543
+ xstream.Stream = Stream;
2544
+ var MemoryStream = /** @class */ (function (_super) {
2545
+ __extends(MemoryStream, _super);
2546
+ function MemoryStream(producer) {
2547
+ var _this = _super.call(this, producer) || this;
2548
+ _this._has = false;
2549
+ return _this;
2550
+ }
2551
+ MemoryStream.prototype._n = function (x) {
2552
+ this._v = x;
2553
+ this._has = true;
2554
+ _super.prototype._n.call(this, x);
2555
+ };
2556
+ MemoryStream.prototype._add = function (il) {
2557
+ var ta = this._target;
2558
+ if (ta)
2559
+ return ta._add(il);
2560
+ var a = this._ils;
2561
+ a.push(il);
2562
+ if (a.length > 1) {
2563
+ if (this._has)
2564
+ il._n(this._v);
2565
+ return;
2566
+ }
2567
+ if (this._stopID !== NO$1) {
2568
+ if (this._has)
2569
+ il._n(this._v);
2570
+ clearTimeout(this._stopID);
2571
+ this._stopID = NO$1;
2572
+ }
2573
+ else if (this._has)
2574
+ il._n(this._v);
2575
+ else {
2576
+ var p = this._prod;
2577
+ if (p !== NO$1)
2578
+ p._start(this);
2579
+ }
2580
+ };
2581
+ MemoryStream.prototype._stopNow = function () {
2582
+ this._has = false;
2583
+ _super.prototype._stopNow.call(this);
2584
+ };
2585
+ MemoryStream.prototype._x = function () {
2586
+ this._has = false;
2587
+ _super.prototype._x.call(this);
2588
+ };
2589
+ MemoryStream.prototype.map = function (project) {
2590
+ return this._map(project);
2591
+ };
2592
+ MemoryStream.prototype.mapTo = function (projectedValue) {
2593
+ return _super.prototype.mapTo.call(this, projectedValue);
2594
+ };
2595
+ MemoryStream.prototype.take = function (amount) {
2596
+ return _super.prototype.take.call(this, amount);
2597
+ };
2598
+ MemoryStream.prototype.endWhen = function (other) {
2599
+ return _super.prototype.endWhen.call(this, other);
2600
+ };
2601
+ MemoryStream.prototype.replaceError = function (replace) {
2602
+ return _super.prototype.replaceError.call(this, replace);
2603
+ };
2604
+ MemoryStream.prototype.remember = function () {
2605
+ return this;
2606
+ };
2607
+ MemoryStream.prototype.debug = function (labelOrSpy) {
2608
+ return _super.prototype.debug.call(this, labelOrSpy);
2609
+ };
2610
+ return MemoryStream;
2611
+ }(Stream));
2612
+ xstream.MemoryStream = MemoryStream;
2613
+ var xs = Stream;
2614
+ xstream.default = xs;
2615
+
2616
+ Object.defineProperty(dropRepeats$1, "__esModule", { value: true });
2617
+ dropRepeats$1.DropRepeatsOperator = void 0;
2618
+ var index_1$5 = xstream;
2619
+ var empty = {};
2620
+ var DropRepeatsOperator = /** @class */ (function () {
2621
+ function DropRepeatsOperator(ins, fn) {
2622
+ this.ins = ins;
2623
+ this.type = 'dropRepeats';
2624
+ this.out = null;
2625
+ this.v = empty;
2626
+ this.isEq = fn ? fn : function (x, y) { return x === y; };
2627
+ }
2628
+ DropRepeatsOperator.prototype._start = function (out) {
2629
+ this.out = out;
2630
+ this.ins._add(this);
2631
+ };
2632
+ DropRepeatsOperator.prototype._stop = function () {
2633
+ this.ins._remove(this);
2634
+ this.out = null;
2635
+ this.v = empty;
2636
+ };
2637
+ DropRepeatsOperator.prototype._n = function (t) {
2638
+ var u = this.out;
2639
+ if (!u)
2640
+ return;
2641
+ var v = this.v;
2642
+ if (v !== empty && this.isEq(t, v))
2643
+ return;
2644
+ this.v = t;
2645
+ u._n(t);
2646
+ };
2647
+ DropRepeatsOperator.prototype._e = function (err) {
2648
+ var u = this.out;
2649
+ if (!u)
2650
+ return;
2651
+ u._e(err);
2652
+ };
2653
+ DropRepeatsOperator.prototype._c = function () {
2654
+ var u = this.out;
2655
+ if (!u)
2656
+ return;
2657
+ u._c();
2658
+ };
2659
+ return DropRepeatsOperator;
2660
+ }());
2661
+ dropRepeats$1.DropRepeatsOperator = DropRepeatsOperator;
2662
+ /**
2663
+ * Drops consecutive duplicate values in a stream.
2664
+ *
2665
+ * Marble diagram:
2666
+ *
2667
+ * ```text
2668
+ * --1--2--1--1--1--2--3--4--3--3|
2669
+ * dropRepeats
2670
+ * --1--2--1--------2--3--4--3---|
2671
+ * ```
2672
+ *
2673
+ * Example:
2674
+ *
2675
+ * ```js
2676
+ * import dropRepeats from 'xstream/extra/dropRepeats'
2677
+ *
2678
+ * const stream = xs.of(1, 2, 1, 1, 1, 2, 3, 4, 3, 3)
2679
+ * .compose(dropRepeats())
2680
+ *
2681
+ * stream.addListener({
2682
+ * next: i => console.log(i),
2683
+ * error: err => console.error(err),
2684
+ * complete: () => console.log('completed')
2685
+ * })
2686
+ * ```
2687
+ *
2688
+ * ```text
2689
+ * > 1
2690
+ * > 2
2691
+ * > 1
2692
+ * > 2
2693
+ * > 3
2694
+ * > 4
2695
+ * > 3
2696
+ * > completed
2697
+ * ```
2698
+ *
2699
+ * Example with a custom isEqual function:
2700
+ *
2701
+ * ```js
2702
+ * import dropRepeats from 'xstream/extra/dropRepeats'
2703
+ *
2704
+ * const stream = xs.of('a', 'b', 'a', 'A', 'B', 'b')
2705
+ * .compose(dropRepeats((x, y) => x.toLowerCase() === y.toLowerCase()))
2706
+ *
2707
+ * stream.addListener({
2708
+ * next: i => console.log(i),
2709
+ * error: err => console.error(err),
2710
+ * complete: () => console.log('completed')
2711
+ * })
2712
+ * ```
2713
+ *
2714
+ * ```text
2715
+ * > a
2716
+ * > b
2717
+ * > a
2718
+ * > B
2719
+ * > completed
2720
+ * ```
2721
+ *
2722
+ * @param {Function} isEqual An optional function of type
2723
+ * `(x: T, y: T) => boolean` that takes an event from the input stream and
2724
+ * checks if it is equal to previous event, by returning a boolean.
2725
+ * @return {Stream}
2726
+ */
2727
+ function dropRepeats(isEqual) {
2728
+ if (isEqual === void 0) { isEqual = void 0; }
2729
+ return function dropRepeatsOperator(ins) {
2730
+ return new index_1$5.Stream(new DropRepeatsOperator(ins, isEqual));
2731
+ };
2732
+ }
2733
+ var _default$5 = dropRepeats$1.default = dropRepeats;
2734
+
2735
+ function switchable(factories, name$, initial, opts={}) {
2736
+ const {
2737
+ switched=['DOM'],
2738
+ stateSourceName='STATE'
2739
+ } = opts;
2740
+ const nameType = typeof name$;
2741
+
2742
+ if (!name$) throw new Error(`Missing 'name$' parameter for switchable()`)
2743
+ if (!(nameType === 'string' || nameType === 'function' || name$ instanceof xs$1.Stream)) {
2744
+ throw new Error(`Invalid 'name$' parameter for switchable(): expects Stream, String, or Function`)
2745
+ }
2746
+
2747
+ if (name$ instanceof xs$1.Stream) {
2748
+ const withInitial$ = name$
2749
+ .compose(_default$5())
2750
+ .startWith(initial)
2751
+ .remember();
2752
+ return sources => _switchable(factories, sources, withInitial$, switched)
2753
+ } else {
2754
+ const mapFunction = (nameType === 'function' && name$) || (state => state[name$]);
2755
+ return sources => {
2756
+ const state$ = sources && ((typeof stateSourceName === 'string' && sources[stateSourceName]) || sources.STATE || sources.state).stream;
2757
+ if (!state$ instanceof xs$1.Stream) throw new Error(`Could not find the state source: ${ stateSourceName }`)
2758
+ const _name$ = state$
2759
+ .map(mapFunction)
2760
+ .filter(name => typeof name === 'string')
2761
+ .compose(_default$5())
2762
+ .startWith(initial)
2763
+ .remember();
2764
+ return _switchable(factories, sources, _name$, switched, stateSourceName)
2765
+ }
2766
+ }
2767
+ }
2768
+
2769
+
2770
+
2771
+ /**
2772
+ * create a group of components which can be switched between based on a stream of component names
2773
+ *
2774
+ * @param {Object} factories maps names to component creation functions
2775
+ * @param {Object} sources standard cycle sources object provided to each component
2776
+ * @param {Observable} name$ stream of names corresponding to the component names
2777
+ * @param {Array} switched which cycle sinks from the components should be `switched` when a new `name$` is emitted
2778
+ * @return {Object} cycle sinks object where the selected sinks are switched to the last component name emitted to `name$`
2779
+ *
2780
+ * any component sinks not dsignated in `switched` will be merged across all components
2781
+ */
2782
+ function _switchable (factories, sources, name$, switched=['DOM'], stateSourceName='STATE') {
2783
+ if (typeof switched === 'string') switched = [switched];
2784
+
2785
+ const sinks = Object.entries(factories)
2786
+ .map(([name, factory]) => {
2787
+ if (sources[stateSourceName]) {
2788
+ const state$ = sources[stateSourceName].stream;
2789
+ const switched = xs__default["default"].combine(name$, state$)
2790
+ .filter(([newComponentName, _]) => newComponentName == name)
2791
+ .map(([_, state]) => state)
2792
+ .remember();
2793
+
2794
+ const state = new sources[stateSourceName].constructor(switched, sources[stateSourceName]._name);
2795
+ return [name, factory({ ...sources, state })]
2796
+ }
2797
+ return [name, factory(sources)]
2798
+ });
2799
+
2800
+ const switchedSinks = Object.keys(sources)
2801
+ .reduce((obj, sinkName) => {
2802
+ if (switched.includes(sinkName)) {
2803
+ obj[sinkName] = name$
2804
+ .map( newComponentName => {
2805
+ const sink = sinks.find(([componentName, _]) => componentName === newComponentName);
2806
+ return (sink && sink[1][sinkName]) || xs__default["default"].never()
2807
+ })
2808
+ .flatten()
2809
+ .remember()
2810
+ .startWith(undefined);
2811
+ } else {
2812
+ const definedSinks = sinks.filter(([_,sink]) => sink[sinkName] !== undefined)
2813
+ .map(([_,sink]) => sink[sinkName]);
2814
+ obj[sinkName] = xs__default["default"].merge(...definedSinks);
2815
+ }
2816
+ return obj
2817
+ }, {});
2818
+
2819
+ return switchedSinks
2820
+ }
2821
+
2822
+ var delay$1 = {};
2823
+
2824
+ Object.defineProperty(delay$1, "__esModule", { value: true });
2825
+ var index_1$4 = xstream;
2826
+ var DelayOperator = /** @class */ (function () {
2827
+ function DelayOperator(dt, ins) {
2828
+ this.dt = dt;
2829
+ this.ins = ins;
2830
+ this.type = 'delay';
2831
+ this.out = null;
2832
+ }
2833
+ DelayOperator.prototype._start = function (out) {
2834
+ this.out = out;
2835
+ this.ins._add(this);
2836
+ };
2837
+ DelayOperator.prototype._stop = function () {
2838
+ this.ins._remove(this);
2839
+ this.out = null;
2840
+ };
2841
+ DelayOperator.prototype._n = function (t) {
2842
+ var u = this.out;
2843
+ if (!u)
2844
+ return;
2845
+ var id = setInterval(function () {
2846
+ u._n(t);
2847
+ clearInterval(id);
2848
+ }, this.dt);
2849
+ };
2850
+ DelayOperator.prototype._e = function (err) {
2851
+ var u = this.out;
2852
+ if (!u)
2853
+ return;
2854
+ var id = setInterval(function () {
2855
+ u._e(err);
2856
+ clearInterval(id);
2857
+ }, this.dt);
2858
+ };
2859
+ DelayOperator.prototype._c = function () {
2860
+ var u = this.out;
2861
+ if (!u)
2862
+ return;
2863
+ var id = setInterval(function () {
2864
+ u._c();
2865
+ clearInterval(id);
2866
+ }, this.dt);
2867
+ };
2868
+ return DelayOperator;
2869
+ }());
2870
+ /**
2871
+ * Delays periodic events by a given time period.
2872
+ *
2873
+ * Marble diagram:
2874
+ *
2875
+ * ```text
2876
+ * 1----2--3--4----5|
2877
+ * delay(60)
2878
+ * ---1----2--3--4----5|
2879
+ * ```
2880
+ *
2881
+ * Example:
2882
+ *
2883
+ * ```js
2884
+ * import fromDiagram from 'xstream/extra/fromDiagram'
2885
+ * import delay from 'xstream/extra/delay'
2886
+ *
2887
+ * const stream = fromDiagram('1----2--3--4----5|')
2888
+ * .compose(delay(60))
2889
+ *
2890
+ * stream.addListener({
2891
+ * next: i => console.log(i),
2892
+ * error: err => console.error(err),
2893
+ * complete: () => console.log('completed')
2894
+ * })
2895
+ * ```
2896
+ *
2897
+ * ```text
2898
+ * > 1 (after 60 ms)
2899
+ * > 2 (after 160 ms)
2900
+ * > 3 (after 220 ms)
2901
+ * > 4 (after 280 ms)
2902
+ * > 5 (after 380 ms)
2903
+ * > completed
2904
+ * ```
2905
+ *
2906
+ * @param {number} period The amount of silence required in milliseconds.
2907
+ * @return {Stream}
2908
+ */
2909
+ function delay(period) {
2910
+ return function delayOperator(ins) {
2911
+ return new index_1$4.Stream(new DelayOperator(period, ins));
2912
+ };
2913
+ }
2914
+ var _default$4 = delay$1.default = delay;
2915
+
2916
+ var concat$1 = {};
2917
+
2918
+ Object.defineProperty(concat$1, "__esModule", { value: true });
2919
+ var index_1$3 = xstream;
2920
+ var ConcatProducer = /** @class */ (function () {
2921
+ function ConcatProducer(streams) {
2922
+ this.streams = streams;
2923
+ this.type = 'concat';
2924
+ this.out = null;
2925
+ this.i = 0;
2926
+ }
2927
+ ConcatProducer.prototype._start = function (out) {
2928
+ this.out = out;
2929
+ this.streams[this.i]._add(this);
2930
+ };
2931
+ ConcatProducer.prototype._stop = function () {
2932
+ var streams = this.streams;
2933
+ if (this.i < streams.length) {
2934
+ streams[this.i]._remove(this);
2935
+ }
2936
+ this.i = 0;
2937
+ this.out = null;
2938
+ };
2939
+ ConcatProducer.prototype._n = function (t) {
2940
+ var u = this.out;
2941
+ if (!u)
2942
+ return;
2943
+ u._n(t);
2944
+ };
2945
+ ConcatProducer.prototype._e = function (err) {
2946
+ var u = this.out;
2947
+ if (!u)
2948
+ return;
2949
+ u._e(err);
2950
+ };
2951
+ ConcatProducer.prototype._c = function () {
2952
+ var u = this.out;
2953
+ if (!u)
2954
+ return;
2955
+ var streams = this.streams;
2956
+ streams[this.i]._remove(this);
2957
+ if (++this.i < streams.length) {
2958
+ streams[this.i]._add(this);
2959
+ }
2960
+ else {
2961
+ u._c();
2962
+ }
2963
+ };
2964
+ return ConcatProducer;
2965
+ }());
2966
+ /**
2967
+ * Puts one stream after the other. *concat* is a factory that takes multiple
2968
+ * streams as arguments, and starts the `n+1`-th stream only when the `n`-th
2969
+ * stream has completed. It concatenates those streams together.
2970
+ *
2971
+ * Marble diagram:
2972
+ *
2973
+ * ```text
2974
+ * --1--2---3---4-|
2975
+ * ...............--a-b-c--d-|
2976
+ * concat
2977
+ * --1--2---3---4---a-b-c--d-|
2978
+ * ```
2979
+ *
2980
+ * Example:
2981
+ *
2982
+ * ```js
2983
+ * import concat from 'xstream/extra/concat'
2984
+ *
2985
+ * const streamA = xs.of('a', 'b', 'c')
2986
+ * const streamB = xs.of(10, 20, 30)
2987
+ * const streamC = xs.of('X', 'Y', 'Z')
2988
+ *
2989
+ * const outputStream = concat(streamA, streamB, streamC)
2990
+ *
2991
+ * outputStream.addListener({
2992
+ * next: (x) => console.log(x),
2993
+ * error: (err) => console.error(err),
2994
+ * complete: () => console.log('concat completed'),
2995
+ * })
2996
+ * ```
2997
+ *
2998
+ * @factory true
2999
+ * @param {Stream} stream1 A stream to concatenate together with other streams.
3000
+ * @param {Stream} stream2 A stream to concatenate together with other streams. Two
3001
+ * or more streams may be given as arguments.
3002
+ * @return {Stream}
3003
+ */
3004
+ function concat() {
3005
+ var streams = [];
3006
+ for (var _i = 0; _i < arguments.length; _i++) {
3007
+ streams[_i] = arguments[_i];
3008
+ }
3009
+ return new index_1$3.Stream(new ConcatProducer(streams));
3010
+ }
3011
+ var _default$3 = concat$1.default = concat;
3012
+
3013
+ var debounce$1 = {};
3014
+
3015
+ Object.defineProperty(debounce$1, "__esModule", { value: true });
3016
+ var index_1$2 = xstream;
3017
+ var DebounceOperator = /** @class */ (function () {
3018
+ function DebounceOperator(dt, ins) {
3019
+ this.dt = dt;
3020
+ this.ins = ins;
3021
+ this.type = 'debounce';
3022
+ this.out = null;
3023
+ this.id = null;
3024
+ this.t = index_1$2.NO;
3025
+ }
3026
+ DebounceOperator.prototype._start = function (out) {
3027
+ this.out = out;
3028
+ this.ins._add(this);
3029
+ };
3030
+ DebounceOperator.prototype._stop = function () {
3031
+ this.ins._remove(this);
3032
+ this.out = null;
3033
+ this.clearInterval();
3034
+ };
3035
+ DebounceOperator.prototype.clearInterval = function () {
3036
+ var id = this.id;
3037
+ if (id !== null) {
3038
+ clearInterval(id);
3039
+ }
3040
+ this.id = null;
3041
+ };
3042
+ DebounceOperator.prototype._n = function (t) {
3043
+ var _this = this;
3044
+ var u = this.out;
3045
+ if (!u)
3046
+ return;
3047
+ this.clearInterval();
3048
+ this.t = t;
3049
+ this.id = setInterval(function () {
3050
+ _this.clearInterval();
3051
+ u._n(t);
3052
+ _this.t = index_1$2.NO;
3053
+ }, this.dt);
3054
+ };
3055
+ DebounceOperator.prototype._e = function (err) {
3056
+ var u = this.out;
3057
+ if (!u)
3058
+ return;
3059
+ this.clearInterval();
3060
+ u._e(err);
3061
+ };
3062
+ DebounceOperator.prototype._c = function () {
3063
+ var u = this.out;
3064
+ if (!u)
3065
+ return;
3066
+ this.clearInterval();
3067
+ if (this.t != index_1$2.NO)
3068
+ u._n(this.t);
3069
+ this.t = index_1$2.NO;
3070
+ u._c();
3071
+ };
3072
+ return DebounceOperator;
3073
+ }());
3074
+ /**
3075
+ * Delays events until a certain amount of silence has passed. If that timespan
3076
+ * of silence is not met the event is dropped.
3077
+ *
3078
+ * Marble diagram:
3079
+ *
3080
+ * ```text
3081
+ * --1----2--3--4----5|
3082
+ * debounce(60)
3083
+ * -----1----------4--|
3084
+ * ```
3085
+ *
3086
+ * Example:
3087
+ *
3088
+ * ```js
3089
+ * import fromDiagram from 'xstream/extra/fromDiagram'
3090
+ * import debounce from 'xstream/extra/debounce'
3091
+ *
3092
+ * const stream = fromDiagram('--1----2--3--4----5|')
3093
+ * .compose(debounce(60))
3094
+ *
3095
+ * stream.addListener({
3096
+ * next: i => console.log(i),
3097
+ * error: err => console.error(err),
3098
+ * complete: () => console.log('completed')
3099
+ * })
3100
+ * ```
3101
+ *
3102
+ * ```text
3103
+ * > 1
3104
+ * > 4
3105
+ * > completed
3106
+ * ```
3107
+ *
3108
+ * @param {number} period The amount of silence required in milliseconds.
3109
+ * @return {Stream}
3110
+ */
3111
+ function debounce(period) {
3112
+ return function debounceOperator(ins) {
3113
+ return new index_1$2.Stream(new DebounceOperator(period, ins));
3114
+ };
3115
+ }
3116
+ var _default$2 = debounce$1.default = debounce;
3117
+
3118
+ // import syntax has bugs for xstream in Node context
3119
+ // this attempts to normalize to work in both Node and browser
3120
+ // if (!xs.never && xs.default && xs.default.never) {
3121
+ // xs.never = xs.default.never
3122
+ // xs.merge = xs.default.merge
3123
+ // xs.of = xs.default.of
3124
+ // }
3125
+ // const concat = (Concat && Concat.default) ? Concat.default : Concat
3126
+ // const delay = (Delay && Delay.default) ? Delay.default : Delay
3127
+ // const dropRepeats = (DropRepeats && DropRepeats.default) ? DropRepeats.default : DropRepeats
3128
+
3129
+ const ENVIRONMENT = ((typeof window != 'undefined' && window) || (process && process.env)) || {};
3130
+
3131
+
3132
+ const REQUEST_SELECTOR_METHOD = 'request';
3133
+ const BOOTSTRAP_ACTION = 'BOOTSTRAP';
3134
+ const INITIALIZE_ACTION = 'INITIALIZE';
3135
+ const HYDRATE_ACTION = 'HYDRATE';
3136
+
3137
+
3138
+ let IS_ROOT_COMPONENT = true;
3139
+
3140
+
3141
+ const ABORT = '~#~#~ABORT~#~#~';
3142
+
3143
+ function component (opts) {
3144
+ const { name, sources, isolateOpts, stateSourceName='STATE' } = opts;
3145
+
3146
+ if (sources && typeof sources !== 'object') {
3147
+ throw new Error('Sources must be a Cycle.js sources object:', name)
3148
+ }
3149
+
3150
+ let fixedIsolateOpts;
3151
+ if (typeof isolateOpts == 'string') {
3152
+ fixedIsolateOpts = { [stateSourceName]: isolateOpts };
3153
+ } else {
3154
+ if (isolateOpts === true) {
3155
+ fixedIsolateOpts = {};
3156
+ } else {
3157
+ fixedIsolateOpts = isolateOpts;
3158
+ }
3159
+ }
3160
+
3161
+ const currySources = typeof sources === 'undefined';
3162
+
3163
+ if (typeof fixedIsolateOpts == 'object') {
3164
+ const wrapped = (sources) => {
3165
+ const fixedOpts = { ...opts, sources };
3166
+ return (new Component(fixedOpts)).sinks
3167
+ };
3168
+ return currySources ? isolate__default["default"](wrapped, fixedIsolateOpts) : isolate__default["default"](wrapped, fixedIsolateOpts)(sources)
3169
+ } else {
3170
+ return currySources ? (sources) => (new Component({ ...opts, sources })).sinks : (new Component(opts)).sinks
3171
+ }
3172
+ }
3173
+
3174
+
3175
+
3176
+
3177
+
3178
+ class Component {
3179
+ // [ PASSED PARAMETERS ]
3180
+ // name
3181
+ // sources
3182
+ // intent
3183
+ // request
3184
+ // model
3185
+ // response
3186
+ // view
3187
+ // children
3188
+ // initialState
3189
+ // calculated
3190
+ // storeCalculatedInState
3191
+ // DOMSourceName
3192
+ // stateSourceName
3193
+ // requestSourceName
3194
+
3195
+ // [ PRIVATE / CALCULATED VALUES ]
3196
+ // sourceNames
3197
+ // intent$
3198
+ // action$
3199
+ // model$
3200
+ // response$
3201
+ // sendResponse$
3202
+ // children$
3203
+ // vdom$
3204
+ // subComponentSink$
3205
+
3206
+ // [ INSTANTIATED STREAM OPERATOR ]
3207
+ // log
3208
+
3209
+ // [ OUTPUT ]
3210
+ // sinks
3211
+
3212
+ constructor({ name='NO NAME', sources, intent, request, model, response, view, children={}, components={}, initialState, calculated, storeCalculatedInState=true, DOMSourceName='DOM', stateSourceName='STATE', requestSourceName='HTTP' }) {
3213
+ if (!sources || typeof sources != 'object') throw new Error('Missing or invalid sources')
3214
+
3215
+ this.name = name;
3216
+ this.sources = sources;
3217
+ this.intent = intent;
3218
+ this.request = request;
3219
+ this.model = model;
3220
+ this.response = response;
3221
+ this.view = view;
3222
+ this.children = children;
3223
+ this.components = components;
3224
+ this.initialState = initialState;
3225
+ this.calculated = calculated;
3226
+ this.storeCalculatedInState = storeCalculatedInState;
3227
+ this.DOMSourceName = DOMSourceName;
3228
+ this.stateSourceName = stateSourceName;
3229
+ this.requestSourceName = requestSourceName;
3230
+ this.sourceNames = Object.keys(sources);
3231
+
3232
+ this.isSubComponent = this.sourceNames.includes('props$');
3233
+
3234
+ const state$ = sources[stateSourceName] && sources[stateSourceName].stream;
3235
+
3236
+ if (state$) {
3237
+ this.currentState = initialState || {};
3238
+ this.sources[this.stateSourceName] = new state.StateSource(state$.map(val => {
3239
+ this.currentState = val;
3240
+ return val
3241
+ }));
3242
+ }
3243
+
3244
+ if (IS_ROOT_COMPONENT && typeof this.intent === 'undefined' && typeof this.model === 'undefined') {
3245
+ this.initialState = initialState || true;
3246
+ this.intent = _ => ({__NOOP_ACTION__:xs__default["default"].never()});
3247
+ this.model = {
3248
+ __NOOP_ACTION__: state => state
3249
+ };
3250
+ }
3251
+ IS_ROOT_COMPONENT = false;
3252
+
3253
+ this.log = makeLog(name);
3254
+
3255
+ this.initIntent$();
3256
+ this.initAction$();
3257
+ this.initResponse$();
3258
+ this.initState();
3259
+ this.initModel$();
3260
+ this.initSendResponse$();
3261
+ this.initChildren$();
3262
+ this.initSubComponentSink$();
3263
+ this.initSubComponentsRendered$();
3264
+ this.initVdom$();
3265
+ this.initSinks();
3266
+ }
3267
+
3268
+ initIntent$() {
3269
+ if (!this.intent) {
3270
+ return
3271
+ }
3272
+ if (typeof this.intent != 'function') {
3273
+ throw new Error('Intent must be a function')
3274
+ }
3275
+
3276
+ this.intent$ = this.intent(this.sources);
3277
+
3278
+ if (!(this.intent$ instanceof xs$1.Stream) && (typeof this.intent$ != 'object')) {
3279
+ throw new Error('Intent must return either an action$ stream or map of event streams')
3280
+ }
3281
+ }
3282
+
3283
+ initAction$() {
3284
+ const requestSource = (this.sources && this.sources[this.requestSourceName]) || null;
3285
+
3286
+ if (!this.intent$) {
3287
+ this.action$ = xs__default["default"].never();
3288
+ return
3289
+ }
3290
+
3291
+ let runner;
3292
+ if (this.intent$ instanceof xs$1.Stream) {
3293
+ runner = this.intent$;
3294
+ } else {
3295
+ const mapped = Object.entries(this.intent$)
3296
+ .map(([type, data$]) => data$.map(data => ({type, data})));
3297
+ runner = xs__default["default"].merge(xs__default["default"].never(), ...mapped);
3298
+ }
3299
+
3300
+ const action$ = ((runner instanceof xs$1.Stream) ? runner : (runner.apply && runner(this.sources) || xs__default["default"].never()));
3301
+ const wrapped$ = _default$3(xs__default["default"].of({ type: BOOTSTRAP_ACTION }), action$)
3302
+ .compose(_default$4(10));
3303
+
3304
+ let initialApiData;
3305
+ if (requestSource && typeof requestSource.select == 'function') {
3306
+ initialApiData = requestSource.select('initial')
3307
+ .flatten();
3308
+ } else {
3309
+ initialApiData = xs__default["default"].never();
3310
+ }
3311
+
3312
+ const hydrate$ = initialApiData.map(data => ({ type: HYDRATE_ACTION, data }));
3313
+
3314
+ this.action$ = xs__default["default"].merge(wrapped$, hydrate$)
3315
+ .compose(this.log(({ type }) => `Action triggered: <${ type }>`));
3316
+ }
3317
+
3318
+ initResponse$() {
3319
+ if (typeof this.request == 'undefined') {
3320
+ return
3321
+ } else if (typeof this.request != 'object') {
3322
+ throw new Error('The request parameter must be an object')
3323
+ }
3324
+
3325
+ const router$ = this.sources[this.requestSourceName];
3326
+ const methods = Object.entries(this.request);
3327
+
3328
+ const wrapped = methods.reduce((acc, [method, routes]) => {
3329
+ const _method = method.toLowerCase();
3330
+ if (typeof router$[_method] != 'function') {
3331
+ throw new Error('Invalid method in request object:', method)
3332
+ }
3333
+ const entries = Object.entries(routes);
3334
+ const mapped = entries.reduce((acc, [route, action]) => {
3335
+ const routeString = `[${_method.toUpperCase()}]:${route || 'none'}`;
3336
+ const actionType = typeof action;
3337
+ if (actionType === 'undefined') {
3338
+ throw new Error(`Action for '${ route }' route in request object not specified`)
3339
+ } else if (actionType !== 'string' && actionType !== 'function') {
3340
+ throw new Error(`Invalid action for '${ route }' route: expecting string or function`)
3341
+ }
3342
+ const actionString = (actionType === 'function') ? '[ FUNCTION ]' : `< ${ action } >`;
3343
+ console.log(`[${ this.name }] Adding ${ this.requestSourceName } route:`, _method.toUpperCase(), `'${ route }' <${ actionString }>`);
3344
+ const route$ = router$[_method](route)
3345
+ .compose(_default$5((a, b) => a.id == b.id))
3346
+ .map(req => {
3347
+ if (!req || !req.id) {
3348
+ throw new Error(`No id found in request: ${ routeString }`)
3349
+ }
3350
+ try {
3351
+ const _reqId = req.id;
3352
+ const params = req.params;
3353
+ const body = req.body;
3354
+ const cookies = req.cookies;
3355
+ const type = (actionType === 'function') ? 'FUNCTION' : action;
3356
+ const data = { params, body, cookies, req };
3357
+ const obj = { type, data: body, req, _reqId, _action: type };
3358
+
3359
+ const timestamp = (new Date()).toISOString();
3360
+ const ip = req.get ? req.get('host') : '0.0.0.0';
3361
+
3362
+ console.log(`${ timestamp } ${ ip } ${ req.method } ${ req.url }`);
3363
+
3364
+ if (ENVIRONMENT.DEBUG) {
3365
+ this.action$.setDebugListener({next: ({ type }) => console.log(`[${ this.name }] Action from ${ this.requestSourceName } request: <${ type }>`)});
3366
+ }
3367
+
3368
+ if (actionType === 'function') {
3369
+ const enhancedState = this.addCalculated(this.currentState);
3370
+ const result = action(enhancedState, req);
3371
+ return xs__default["default"].of({ ...obj, data: result })
3372
+ } else {
3373
+ this.action$.shamefullySendNext(obj);
3374
+
3375
+ const sourceEntries = Object.entries(this.sources);
3376
+ const responses = sourceEntries.reduce((acc, [name, source]) => {
3377
+ if (!source || typeof source[REQUEST_SELECTOR_METHOD] != 'function') return acc
3378
+ const selected$ = source[REQUEST_SELECTOR_METHOD](_reqId);
3379
+ return [ ...acc, selected$ ]
3380
+ }, []);
3381
+ return xs__default["default"].merge(...responses)
3382
+ }
3383
+ } catch(err) {
3384
+ console.error(err);
3385
+ }
3386
+ }).flatten();
3387
+ return [ ...acc, route$ ]
3388
+ }, []);
3389
+ const mapped$ = xs__default["default"].merge(...mapped);
3390
+ return [ ...acc, mapped$ ]
3391
+ }, []);
3392
+
3393
+ this.response$ = xs__default["default"].merge(...wrapped)
3394
+ .compose(this.log(res => {
3395
+ if (res._action) return `[${ this.requestSourceName }] response data received for Action: <${ res._action }>`
3396
+ return `[${ this.requestSourceName }] response data received from FUNCTION`
3397
+ }));
3398
+
3399
+ if (typeof this.response != 'undefined' && typeof this.response$ == 'undefined') {
3400
+ throw new Error('Cannot have a response parameter without a request parameter')
3401
+ }
3402
+ }
3403
+
3404
+ initState() {
3405
+ if (this.model != undefined) {
3406
+ if (this.model[INITIALIZE_ACTION] === undefined) {
3407
+ this.model[INITIALIZE_ACTION] = {
3408
+ [this.stateSourceName]: (_, data) => ({ ...this.addCalculated(data) })
3409
+ };
3410
+ } else {
3411
+ Object.keys(this.model[INITIALIZE_ACTION]).forEach(name => {
3412
+ if (name !== this.stateSourceName) {
3413
+ console.warn(`${ INITIALIZE_ACTION } can only be used with the ${ this.stateSourceName } source... disregarding ${ name }`);
3414
+ delete this.model[INITIALIZE_ACTION][name];
3415
+ }
3416
+ });
3417
+ }
3418
+ }
3419
+ }
3420
+
3421
+ initModel$() {
3422
+ if (typeof this.model == 'undefined') {
3423
+ this.model$ = this.sourceNames.reduce((a,s) => {
3424
+ a[s] = xs__default["default"].never();
3425
+ return a
3426
+ }, {});
3427
+ return
3428
+ }
3429
+
3430
+ const initial = { type: INITIALIZE_ACTION, data: this.initialState };
3431
+ const shimmed$ = this.initialState ? _default$3(xs__default["default"].of(initial), this.action$).compose(_default$4(0)) : this.action$;
3432
+ const onState = this.makeOnAction(shimmed$, true, this.action$);
3433
+ const onNormal = this.makeOnAction(this.action$, false, this.action$);
3434
+
3435
+
3436
+ const modelEntries = Object.entries(this.model);
3437
+
3438
+ const reducers = {};
3439
+
3440
+ modelEntries.forEach((entry) => {
3441
+ let [action, sinks] = entry;
3442
+
3443
+ if (typeof sinks === 'function') {
3444
+ sinks = { [this.stateSourceName]: sinks };
3445
+ }
3446
+
3447
+ if (typeof sinks !== 'object') {
3448
+ throw new Error(`Entry for each action must be an object: ${ this.name } ${ action }`)
3449
+ }
3450
+
3451
+ const sinkEntries = Object.entries(sinks);
3452
+
3453
+ sinkEntries.forEach((entry) => {
3454
+ const [sink, reducer] = entry;
3455
+
3456
+ const isStateSink = (sink == this.stateSourceName);
3457
+
3458
+ const on = isStateSink ? onState : onNormal;
3459
+ const onned = on(action, reducer);
3460
+
3461
+ const wrapped = onned.compose(this.log(data => {
3462
+ if (isStateSink) {
3463
+ return `State reducer added: <${ action }>`
3464
+ } else {
3465
+ const extra = data && (data.type || data.command || data.name || data.key || (Array.isArray(data) && 'Array') || data);
3466
+ return `Data sent to [${ sink }]: <${ action }> ${ extra }`
3467
+ }
3468
+ }));
3469
+
3470
+ if (Array.isArray(reducers[sink])) {
3471
+ reducers[sink].push(wrapped);
3472
+ } else {
3473
+ reducers[sink] = [wrapped];
3474
+ }
3475
+ });
3476
+ });
3477
+
3478
+ const model$ = Object.entries(reducers).reduce((acc, entry) => {
3479
+ const [sink, streams] = entry;
3480
+ acc[sink] = xs__default["default"].merge(xs__default["default"].never(), ...streams);
3481
+ return acc
3482
+ }, {});
3483
+
3484
+ this.model$ = model$;
3485
+ }
3486
+
3487
+ initSendResponse$() {
3488
+ const responseType = typeof this.response;
3489
+ if (responseType != 'function' && responseType != 'undefined') {
3490
+ throw new Error('The response parameter must be a function')
3491
+ }
3492
+
3493
+ if (responseType == 'undefined') {
3494
+ if (this.response$) {
3495
+ this.response$.subscribe({
3496
+ next: this.log(({ _reqId, _action }) => `Unhandled response for request: ${ _action } ${ _reqId }`)
3497
+ });
3498
+ }
3499
+ this.sendResponse$ = xs__default["default"].never();
3500
+ return
3501
+ }
3502
+
3503
+ const selectable = {
3504
+ select: (actions) => {
3505
+ if (typeof actions == 'undefined') return this.response$
3506
+ if (!Array.isArray(actions)) actions = [actions];
3507
+ return this.response$.filter(({_action}) => (actions.length > 0) ? (_action === 'FUNCTION' || actions.includes(_action)) : true)
3508
+ }
3509
+ };
3510
+
3511
+ const out = this.response(selectable);
3512
+ if (typeof out != 'object') {
3513
+ throw new Error('The response function must return an object')
3514
+ }
3515
+
3516
+ const entries = Object.entries(out);
3517
+ const out$ = entries.reduce((acc, [command, response$]) => {
3518
+ const mapped$ = response$.map(({ _reqId, _action, data }) => {
3519
+ if (!_reqId) {
3520
+ throw new Error(`No request id found for response for: ${ command }`)
3521
+ }
3522
+ return { _reqId, _action, command, data }
3523
+ });
3524
+ return [ ...acc, mapped$ ]
3525
+ }, []);
3526
+
3527
+ this.sendResponse$ = xs__default["default"].merge(...out$)
3528
+ .compose(this.log(({ _reqId, _action }) => `[${ this.requestSourceName }] response sent for: <${ _action }>`));
3529
+ }
3530
+
3531
+ initChildren$() {
3532
+ const initial = this.sourceNames.reduce((acc, name) => {
3533
+ if (name == this.DOMSourceName) {
3534
+ acc[name] = {};
3535
+ } else {
3536
+ acc[name] = [];
3537
+ }
3538
+ return acc
3539
+ }, {});
3540
+
3541
+ this.children$ = Object.entries(this.children).reduce((acc, [childName, childFactory]) => {
3542
+ const child$ = childFactory(this.sources);
3543
+ this.sourceNames.forEach(source => {
3544
+ if (source == this.DOMSourceName) {
3545
+ acc[source][childName] = child$[source];
3546
+ } else {
3547
+ acc[source].push(child$[source]);
3548
+ }
3549
+ });
3550
+ return acc
3551
+ }, initial);
3552
+ }
3553
+
3554
+ initSubComponentSink$() {
3555
+ const subComponentSink$ = xs__default["default"].create({
3556
+ start: listener => {
3557
+ this.newSubComponentSinks = listener.next.bind(listener);
3558
+ },
3559
+ stop: _ => {
3560
+
3561
+ }
3562
+ });
3563
+ subComponentSink$.subscribe({ next: _ => _ });
3564
+ this.subComponentSink$ = subComponentSink$.filter(sinks => Object.keys(sinks).length > 0);
3565
+ }
3566
+
3567
+ initSubComponentsRendered$() {
3568
+ const stream = xs__default["default"].create({
3569
+ start: (listener) => {
3570
+ this.subComponentsRendered = listener.next.bind(listener);
3571
+ },
3572
+ stop: _ => {
3573
+
3574
+ }
3575
+ });
3576
+ this.subComponentsRendered$ = stream.startWith(null);
3577
+ }
3578
+
3579
+ initVdom$() {
3580
+ if (typeof this.view != 'function') {
3581
+ this.vdom$ = xs__default["default"].of(null);
3582
+ return
3583
+ }
3584
+
3585
+ const renderParameters$ = this.collectRenderParameters();
3586
+
3587
+ this.vdom$ = renderParameters$
3588
+ .map(this.view)
3589
+ .map(vDom => vDom || { sel: 'div', data: {}, children: [] })
3590
+ .compose(this.instantiateSubComponents.bind(this))
3591
+ .filter(val => val !== undefined)
3592
+ .compose(this.renderVdom.bind(this));
3593
+
3594
+ }
3595
+
3596
+ initSinks() {
3597
+ this.sinks = this.sourceNames.reduce((acc, name) => {
3598
+ if (name == this.DOMSourceName) return acc
3599
+ const subComponentSink$ = this.subComponentSink$ ? this.subComponentSink$.map(sinks => sinks[name]).filter(sink => !!sink).flatten() : xs__default["default"].never();
3600
+ if (name === this.stateSourceName) {
3601
+ acc[name] = xs__default["default"].merge((this.model$[name] || xs__default["default"].never()), subComponentSink$, this.sources[this.stateSourceName].stream.filter(_ => false), ...this.children$[name]);
3602
+ } else {
3603
+ acc[name] = xs__default["default"].merge((this.model$[name] || xs__default["default"].never()), subComponentSink$, ...this.children$[name]);
3604
+ }
3605
+ return acc
3606
+ }, {});
3607
+
3608
+ this.sinks[this.DOMSourceName] = this.vdom$;
3609
+ this.sinks[this.requestSourceName] = xs__default["default"].merge(this.sendResponse$ ,this.sinks[this.requestSourceName]);
3610
+ }
3611
+
3612
+ makeOnAction(action$, isStateSink=true, rootAction$) {
3613
+ rootAction$ = rootAction$ || action$;
3614
+ return (name, reducer) => {
3615
+ const filtered$ = action$.filter(({type}) => type == name);
3616
+
3617
+ let returnStream$;
3618
+ if (typeof reducer === 'function') {
3619
+ returnStream$ = filtered$.map(action => {
3620
+ const next = (type, data) => {
3621
+ const _reqId = action._reqId || (action.req && action.req.id);
3622
+ const _data = _reqId ? (typeof data == 'object' ? { ...data, _reqId, _action: name } : { data, _reqId, _action: name }) : data;
3623
+ // put the "next" action request at the end of the event loop so the "current" action completes first
3624
+ setTimeout(() => {
3625
+ // push the "next" action request into the action$ stream
3626
+ rootAction$.shamefullySendNext({ type, data: _data });
3627
+ }, 10);
3628
+ };
3629
+
3630
+ let data = action.data;
3631
+ if (data && data.data && data._reqId) data = data.data;
3632
+ if (isStateSink) {
3633
+ return (state) => {
3634
+ const _state = this.isSubComponent ? this.currentState : state;
3635
+ const enhancedState = this.addCalculated(_state);
3636
+ const newState = reducer(enhancedState, data, next, action.req);
3637
+ if (newState == ABORT) return _state
3638
+ return this.cleanupCalculated(newState)
3639
+ }
3640
+ } else {
3641
+ const enhancedState = this.addCalculated(this.currentState);
3642
+ const reduced = reducer(enhancedState, data, next, action.req);
3643
+ const type = typeof reduced;
3644
+ const _reqId = action._reqId || (action.req && action.req.id);
3645
+ if (['string', 'number', 'boolean', 'function'].includes(type)) return reduced
3646
+ if (type == 'object') return { ...reduced, _reqId, _action: name }
3647
+ if (type == 'undefined') {
3648
+ console.warn(`'undefined' value sent to ${ name }`);
3649
+ return reduced
3650
+ }
3651
+ throw new Error(`Invalid reducer type for ${ name } ${ type }`)
3652
+ }
3653
+ }).filter(result => result != ABORT);
3654
+ } else if (reducer === undefined || reducer === true) {
3655
+ returnStream$ = filtered$.map(({data}) => data);
3656
+ } else {
3657
+ const value = reducer;
3658
+ returnStream$ = filtered$.mapTo(value);
3659
+ }
3660
+
3661
+ return returnStream$
3662
+ }
3663
+ }
3664
+
3665
+ addCalculated(state) {
3666
+ if (!this.calculated || typeof state !== 'object') return state
3667
+ if (typeof this.calculated !== 'object') throw new Error(`'calculated' parameter must be an object mapping calculated state field named to functions`)
3668
+ const entries = Object.entries(this.calculated);
3669
+ const calculated = entries.reduce((acc, [field, fn]) => {
3670
+ if (typeof fn !== 'function') throw new Error(`Missing or invalid calculator function for calculated field '${ field }`)
3671
+ try {
3672
+ acc[field] = fn(state);
3673
+ } catch(e) {
3674
+ console.warn(`Calculated field '${ field }' threw an error during calculation: ${ e.message }`);
3675
+ }
3676
+ return acc
3677
+ }, {});
3678
+ return { ...state, ...calculated }
3679
+ }
3680
+
3681
+ cleanupCalculated(state) {
3682
+ if (this.storeCalculatedInState) return this.addCalculated(state)
3683
+ if (!this.calculated || !state || typeof state !== 'object') return state
3684
+ const keys = Object.keys(this.calculated);
3685
+ const copy = { ...state };
3686
+ keys.forEach(key => {
3687
+ if (this.initialState && typeof this.initialState[key] !== 'undefined') {
3688
+ copy[key] = this.initialState[key];
3689
+ } else {
3690
+ delete copy[key];
3691
+ }
3692
+ });
3693
+ return copy
3694
+ }
3695
+
3696
+ collectRenderParameters() {
3697
+ const state = this.sources[this.stateSourceName];
3698
+ const renderParams = { ...this.children$[this.DOMSourceName] };
3699
+
3700
+ const enhancedState = state && state.isolateSource(state, { get: state => this.addCalculated(state) });
3701
+ const stateStream = (enhancedState && enhancedState.stream) || xs__default["default"].never();
3702
+
3703
+ renderParams.state = stateStream;
3704
+ renderParams[this.stateSourceName] = stateStream;
3705
+
3706
+ if (this.sources.props$) {
3707
+ renderParams.props = this.sources.props$;
3708
+ }
3709
+
3710
+ if (this.sources.children$) {
3711
+ renderParams.children = this.sources.children$;
3712
+ }
3713
+
3714
+ const names = [];
3715
+ const streams = [];
3716
+
3717
+ Object.entries(renderParams).forEach(([name, stream]) => {
3718
+ names.push(name);
3719
+ streams.push(stream);
3720
+ });
3721
+
3722
+ const combined = xs__default["default"].combine(...streams)
3723
+ // map the streams from an array back to an object with the render parameter names as the keys
3724
+ .map(arr => {
3725
+ return names.reduce((acc, name, index) => {
3726
+ acc[name] = arr[index];
3727
+ return acc
3728
+ }, {})
3729
+ });
3730
+
3731
+ return combined
3732
+ }
3733
+
3734
+ instantiateSubComponents(vDom$) {
3735
+ return vDom$.fold((previousComponents, vDom) => {
3736
+ const componentNames = Object.keys(this.components);
3737
+ const foundComponents = getComponents(vDom, componentNames);
3738
+ const entries = Object.entries(foundComponents);
3739
+
3740
+ const rootEntry = { '::ROOT::': vDom };
3741
+
3742
+ if (entries.length === 0) {
3743
+ return rootEntry
3744
+ }
3745
+
3746
+ const sinkArrsByType = {};
3747
+
3748
+ const newComponents = entries.reduce((acc, [id, el]) => {
3749
+ const data = el.data;
3750
+ const props = data.props || {};
3751
+ const children = el.children || [];
3752
+
3753
+ const isCollection = data.isCollection || false;
3754
+ const isSwitchable = data.isSwitchable || false;
3755
+
3756
+ if (previousComponents[id]) {
3757
+ const entry = previousComponents[id];
3758
+ acc[id] = entry;
3759
+ entry.props$.shamefullySendNext(props);
3760
+ entry.children$.shamefullySendNext(children);
3761
+ return acc
3762
+ }
3763
+
3764
+ const props$ = xs__default["default"].create().startWith(props);
3765
+ const children$ = xs__default["default"].create().startWith(children);
3766
+
3767
+ let instantiator;
3768
+
3769
+ if (isCollection) {
3770
+ instantiator = this.instantiateCollection.bind(this);
3771
+ } else if (isSwitchable) {
3772
+ instantiator = this.instantiateSwitchable.bind(this);
3773
+ } else {
3774
+ instantiator = this.instantiateCustomComponent.bind(this);
3775
+ }
3776
+
3777
+ const { sink$, preventStateUpdates } = instantiator(el, props$, children$);
3778
+
3779
+ if (preventStateUpdates) {
3780
+ const originalStateSink = sink$[this.stateSourceName];
3781
+ sink$[this.stateSourceName] = originalStateSink.filter(state => {
3782
+ console.warn('State update attempt from component with inderect link to state: Components with state set through HTML properties/attributes cannot update application state directly');
3783
+ return false
3784
+ });
3785
+ }
3786
+
3787
+ sink$[this.DOMSourceName] = this.makeCoordinatedSubComponentDomSink(sink$[this.DOMSourceName]);
3788
+
3789
+ acc[id] = { sink$, props$, children$ };
3790
+
3791
+ Object.entries(sink$).map(([name, stream]) => {
3792
+ sinkArrsByType[name] ||= [];
3793
+ if (name !== this.DOMSourceName) sinkArrsByType[name].push(stream);
3794
+ });
3795
+
3796
+ return acc
3797
+ }, rootEntry);
3798
+
3799
+ const mergedSinksByType = Object.entries(sinkArrsByType).reduce((acc, [name, streamArr]) => {
3800
+ if (streamArr.length === 0) return acc
3801
+ acc[name] = streamArr.length === 1 ? streamArr[0] : xs__default["default"].merge(...streamArr);
3802
+ return acc
3803
+ }, {});
3804
+
3805
+ this.newSubComponentSinks(mergedSinksByType);
3806
+
3807
+ return newComponents
3808
+ }, {})
3809
+ }
3810
+
3811
+ makeCoordinatedSubComponentDomSink(domSink$) {
3812
+ const remembered$ = domSink$.remember();
3813
+ const repeatChecker = (a, b) => JSON.stringify(a) === JSON.stringify(b);
3814
+
3815
+ const coordinated = this.sources[this.stateSourceName].stream
3816
+ .compose(_default$5(repeatChecker))
3817
+ .map(state => remembered$)
3818
+ .compose(_default$2(10))
3819
+ .flatten()
3820
+ .debug(_ => this.subComponentsRendered())
3821
+ .remember();
3822
+
3823
+ return coordinated
3824
+ }
3825
+
3826
+ instantiateCollection(el, props$, children$) {
3827
+ const data = el.data;
3828
+ const props = data.props || {};
3829
+ el.children || [];
3830
+ let stateSource = new state.StateSource(this.sources[this.stateSourceName].stream.startWith(this.currentState));
3831
+
3832
+ let preventStateUpdates = false;
3833
+ let sink$, field, lense;
3834
+
3835
+ const stateGetter = state => {
3836
+ const arr = state[field];
3837
+ if (typeof arr === 'undefined') return
3838
+ if (!Array.isArray(arr)) {
3839
+ const label = typeof props.of === 'string' ? props.of : 'components';
3840
+ console.warn(`Collection of ${ label } does not have a valid array in the 'for' property: expects either an array or a string of the name of an array property on the state`);
3841
+ return []
3842
+ }
3843
+ return arr
3844
+ };
3845
+
3846
+ if (typeof props.for === 'undefined') {
3847
+ lense = {
3848
+ get: state => {
3849
+ if (!Array.isArray(state)) {
3850
+ console.warn(`Collection sub-component of ${ this.name } has no 'for' attribute and the parent state is not an array: Provide a 'for' attribute with either an array or the name of a state property containing an array`);
3851
+ return []
3852
+ }
3853
+ return state
3854
+ },
3855
+ set: (oldState, newState) => newState
3856
+ };
3857
+ } else if (typeof props.for === 'string') {
3858
+ field = props.for;
3859
+ lense = {
3860
+ get: stateGetter,
3861
+ set: (state, arr) => {
3862
+ if (this.calculated && field in this.calculated) {
3863
+ console.warn(`Collection sub-component of ${ this.name } attempted to update state on a calculated field '${ field }': Update ignored`);
3864
+ return state
3865
+ }
3866
+ return { ...state, [field]: arr }
3867
+ }
3868
+ };
3869
+ } else {
3870
+ field = 'for';
3871
+ stateSource = new state.StateSource(props$.remember());
3872
+ lense = {
3873
+ get: stateGetter,
3874
+ set: (state, arr) => state
3875
+ };
3876
+ preventStateUpdates = true;
3877
+ }
3878
+ const sources = { ...this.sources, [this.stateSourceName]: stateSource, props$, children$ };
3879
+ const factory = typeof props.of === 'function' ? props.of : this.components[props.of];
3880
+ sink$ = collection(factory, lense, { container: null })(sources);
3881
+ if (typeof sink$ !== 'object') {
3882
+ throw new Error('Invalid sinks returned from component factory of collection element')
3883
+ }
3884
+ return { sink$, preventStateUpdates }
3885
+ }
3886
+
3887
+ instantiateSwitchable(el, props$, children$) {
3888
+ const data = el.data;
3889
+ const props = data.props || {};
3890
+ el.children || [];
3891
+ let stateSource = new state.StateSource(this.sources[this.stateSourceName].stream.startWith(this.currentState));
3892
+
3893
+ const stateField = props.state;
3894
+ let preventStateUpdates = false;
3895
+ let isolateSwitchable = false;
3896
+ let sink$, lense;
3897
+
3898
+ if (typeof stateField === 'string') {
3899
+ isolateSwitchable = true;
3900
+ lense = {
3901
+ get: state => {
3902
+ return state[stateField]
3903
+ },
3904
+ set: (oldState, newState) => {
3905
+ if (this.calculated && stateField in this.calculated) {
3906
+ console.warn(`Switchable sub-component of ${ this.name } attempted to update state on a calculated field '${ stateField }': Update ignored`);
3907
+ return oldState
3908
+ }
3909
+ return { ...oldState, [stateField]: newState }
3910
+ }
3911
+ };
3912
+ preventStateUpdates = false;
3913
+ } else if (typeof stateField === 'undefined') {
3914
+ isolateSwitchable = true;
3915
+ lense = {
3916
+ get: state => state,
3917
+ set: (oldState, newState) => newState
3918
+ };
3919
+ preventStateUpdates = false;
3920
+ } else if (typeof stateField === 'object') {
3921
+ stateSource = new state.StateSource(props$.map(props => props.state));
3922
+ } else {
3923
+ throw new Error(`Invalid state provided to collection sub-component of ${ this.name }: Expecting string, object, or none, but found ${ typeof stateField }`)
3924
+ }
3925
+
3926
+ const switchableComponents = data.props.of;
3927
+ const sources = { ...this.sources, [this.stateSourceName]: stateSource, props$, children$ };
3928
+ if (isolateSwitchable) {
3929
+ sink$ = isolate__default["default"](switchable(switchableComponents, props$.map(props => props.current)), { [this.stateSourceName]: lense })(sources);
3930
+ } else {
3931
+ sink$ = switchable(switchableComponents, props$.map(props => props.current))(sources);
3932
+ }
3933
+
3934
+ if (typeof sink$ !== 'object') {
3935
+ throw new Error('Invalid sinks returned from component factory of switchable element')
3936
+ }
3937
+
3938
+ return { sink$, preventStateUpdates }
3939
+ }
3940
+
3941
+ instantiateCustomComponent(el, props$, children$) {
3942
+ const componentName = el.sel;
3943
+ const data = el.data;
3944
+ const props = data.props || {};
3945
+ el.children || [];
3946
+ let stateSource = new state.StateSource(this.sources[this.stateSourceName].stream.startWith(this.currentState));
3947
+
3948
+ const factory = componentName === 'sygnal-factory' ? props.sygnalFactory : (this.components[componentName] || props.sygnalFactory);
3949
+ if (!factory && !isCollection && !isSwitchable) {
3950
+ if (componentName === 'sygnal-factory') throw new Error(`Component not found on element with Capitalized selector and nameless function: JSX transpilation replaces selectors starting with upper case letters with functions in-scope with the same name, Sygnal cannot see the name of the resulting component.`)
3951
+ throw new Error(`Component not found: ${ componentName }`)
3952
+ }
3953
+
3954
+ let preventStateUpdates = false;
3955
+ let sink$;
3956
+
3957
+ const { state: stateProp, sygnalFactory, id, ...sanitizedProps } = props;
3958
+ if (typeof stateProp === 'undefined' && (typeof sanitizedProps !== 'object' || Object.keys(sanitizedProps).length === 0)) {
3959
+ const sources = { ...this.sources, [this.stateSourceName]: stateSource, props$: xs__default["default"].never().startWith(null), children$ };
3960
+ sink$ = factory(sources);
3961
+ preventStateUpdates = false;
3962
+ } else {
3963
+ const lense = (props) => {
3964
+ const state = props.state;
3965
+ if (typeof state === 'undefined') return props
3966
+ if (typeof state !== 'object') return state
3967
+
3968
+ const copy = { ...props };
3969
+ delete copy.state;
3970
+ return { ...copy, ...state }
3971
+ };
3972
+ stateSource = new state.StateSource(props$.map(lense));
3973
+ const sources = { ...this.sources, [this.stateSourceName]: stateSource, props$, children$ };
3974
+ sink$ = factory(sources);
3975
+ }
3976
+
3977
+ if (typeof sink$ !== 'object') {
3978
+ const name = componentName === 'sygnal-factory' ? 'custom element' : componentName;
3979
+ throw new Error('Invalid sinks returned from component factory:', name)
3980
+ }
3981
+
3982
+ return { sink$, preventStateUpdates }
3983
+ }
3984
+
3985
+ renderVdom(componentInstances$) {
3986
+ return xs__default["default"].combine(this.subComponentsRendered$, componentInstances$)
3987
+ .compose(_default$2(5))
3988
+ .map(([_, components]) => {
3989
+ const componentNames = Object.keys(this.components);
3990
+
3991
+ const root = components['::ROOT::'];
3992
+ const entries = Object.entries(components).filter(([id]) => id !== '::ROOT::');
3993
+
3994
+ if (entries.length === 0) {
3995
+ return xs__default["default"].of(root)
3996
+ }
3997
+
3998
+ const ids = [];
3999
+ const vdom$ = entries
4000
+ .map(([id, val]) => {
4001
+ ids.push(id);
4002
+ return val.sink$[this.DOMSourceName].startWith(undefined)
4003
+ });
4004
+
4005
+ if (vdom$.length === 0) return xs__default["default"].of(root)
4006
+
4007
+ return xs__default["default"].combine(...vdom$)
4008
+ .compose(_default$2(10))
4009
+ .map(vdoms => {
4010
+ const withIds = vdoms.reduce((acc, vdom, index) => {
4011
+ acc[ids[index]] = vdom;
4012
+ return acc
4013
+ }, {});
4014
+ const rootCopy = deepCopyVdom(root);
4015
+ const injected = injectComponents(rootCopy, withIds, componentNames);
4016
+ return injected
4017
+ })
4018
+ })
4019
+ .flatten()
4020
+ .filter(val => !!val)
4021
+ .remember()
4022
+ .compose(this.log('View Rendered'))
4023
+ }
4024
+
4025
+ }
4026
+
4027
+
4028
+
4029
+
4030
+
4031
+
4032
+
4033
+ /**
4034
+ * factory to create a logging function meant to be used inside of an xstream .compose()
4035
+ *
4036
+ * @param {String} context name of the component or file to be prepended to any messages
4037
+ * @return {Function}
4038
+ *
4039
+ * returned function accepts either a `String` of `Function`
4040
+ * `String` values will be logged to `console` as is
4041
+ * `Function` values will be called with the current `stream` value and the result will be logged to `console`
4042
+ * all output will be prepended with the `context` (ex. "[CONTEXT] My output")
4043
+ * ONLY outputs if the global `DEBUG` variable is set to `true`
4044
+ */
4045
+ function makeLog (context) {
4046
+ return function (msg) {
4047
+ const fixedMsg = (typeof msg === 'function') ? msg : _ => msg;
4048
+ return stream => {
4049
+ return stream.debug(msg => {
4050
+ if (ENVIRONMENT.DEBUG == 'true' || ENVIRONMENT.DEBUG === true) {
4051
+ console.log(`[${context}] ${fixedMsg(msg)}`);
4052
+ }
4053
+ })
4054
+ }
4055
+ }
4056
+ }
4057
+
4058
+
4059
+
4060
+ function getComponents(currentElement, componentNames, depth=0, index=0) {
4061
+ if (!currentElement) return {}
4062
+
4063
+ if (currentElement.data?.componentsProcessed) return {}
4064
+ if (depth === 0) currentElement.data.componentsProcessed = true;
4065
+
4066
+ const sel = currentElement.sel;
4067
+ const isCollection = sel && sel.toLowerCase() === 'collection';
4068
+ const isSwitchable = sel && sel.toLowerCase() === 'switchable';
4069
+ const isComponent = sel && (['collection', 'switchable', 'sygnal-factory', ...componentNames].includes(currentElement.sel)) || typeof currentElement.data?.props?.sygnalFactory === 'function';
4070
+ const props = (currentElement.data && currentElement.data.props) || {};
4071
+ const attrs = (currentElement.data && currentElement.data.attrs) || {};
4072
+ const children = currentElement.children || [];
4073
+
4074
+ let found = {};
4075
+
4076
+ if (isComponent) {
4077
+ const id = getComponentIdFromElement(currentElement, depth, index);
4078
+ if (isCollection) {
4079
+ if (!props.of) throw new Error(`Collection element missing required 'component' property`)
4080
+ if (typeof props.of !== 'string' && typeof props.of !== 'function') throw new Error(`Invalid 'component' property of collection element: found ${ typeof props.of } requires string or component factory function`)
4081
+ if (typeof props.of !== 'function' && !componentNames.includes(props.of)) throw new Error(`Specified component for collection not found: ${ props.of }`)
4082
+ if (typeof attrs.for !== 'undefined' && !(typeof attrs.for === 'string' || Array.isArray(attrs.for))) console.warn(`No valid array found in the 'value' property of collection ${ typeof props.of === 'string' ? props.of : 'function component' }: no collection components will be created`);
4083
+ currentElement.data.isCollection = true;
4084
+ currentElement.data.props ||= {};
4085
+ currentElement.data.props.for = attrs.for;
4086
+ currentElement.data.attrs = undefined;
4087
+ } else if (isSwitchable) {
4088
+ if (!props.of) throw new Error(`Switchable element missing required 'of' property`)
4089
+ if (typeof props.of !== 'object') throw new Error(`Invalid 'components' property of switchable element: found ${ typeof props.of } requires object mapping names to component factories`)
4090
+ const switchableComponents = Object.values(props.of);
4091
+ if (!switchableComponents.every(comp => typeof comp === 'function')) throw new Error(`One or more components provided to switchable element is not a valid component factory`)
4092
+ if (!props.current || (typeof props.current !== 'string' && typeof props.current !== 'function')) throw new Error(`Missing or invalid 'current' property for switchable element: found '${ typeof props.current }' requires string or function`)
4093
+ const switchableComponentNames = Object.keys(props.of);
4094
+ if (!switchableComponentNames.includes(props.current)) throw new Error(`Component '${ props.current }' not found in switchable element`)
4095
+ currentElement.data.isSwitchable = true;
4096
+ } else ;
4097
+ found[id] = currentElement;
4098
+ }
4099
+
4100
+ if (children.length > 0) {
4101
+ children.map((child, i) => getComponents(child, componentNames, depth + 1, i))
4102
+ .forEach((child) => {
4103
+ Object.entries(child).forEach(([id, el]) => found[id] = el);
4104
+ });
4105
+ }
4106
+
4107
+ return found
4108
+ }
4109
+
4110
+ function injectComponents(currentElement, components, componentNames, depth=0, index) {
4111
+ if (!currentElement) return
4112
+ if (currentElement.data?.componentsInjected) return currentElement
4113
+ if (depth === 0 && currentElement.data) currentElement.data.componentsInjected = true;
4114
+
4115
+
4116
+ const sel = currentElement.sel || 'NO SELECTOR';
4117
+ const isComponent = ['collection', 'switchable', 'sygnal-factory', ...componentNames].includes(sel) || typeof currentElement.data?.props?.sygnalFactory === 'function';
4118
+ const isCollection = currentElement?.data?.isCollection;
4119
+ const isSwitchable = currentElement?.data?.isSwitchable;
4120
+ (currentElement.data && currentElement.data.props) || {};
4121
+ const children = currentElement.children || [];
4122
+
4123
+ if (isComponent) {
4124
+ const id = getComponentIdFromElement(currentElement, depth, index);
4125
+ const component = components[id];
4126
+ if (isCollection) {
4127
+ currentElement.sel = 'div';
4128
+ currentElement.children = Array.isArray(component) ? component : [component];
4129
+ return currentElement
4130
+ } else if (isSwitchable) {
4131
+ return component
4132
+ } else {
4133
+ return component
4134
+ }
4135
+ } else if (children.length > 0) {
4136
+ currentElement.children = children.map((child, i) => injectComponents(child, components, componentNames, depth + 1, i)).flat();
4137
+ return currentElement
4138
+ } else {
4139
+ return currentElement
4140
+ }
4141
+ }
4142
+
4143
+ const selMap = new Map();
4144
+ function getComponentIdFromElement(el, depth, index) {
4145
+ const sel = el.sel;
4146
+ const name = typeof sel === 'string' ? sel : 'functionComponent';
4147
+ let base = selMap.get(sel);
4148
+ if (!base) {
4149
+ const date = Date.now();
4150
+ const rand = Math.floor(Math.random() * 10000);
4151
+ base = `${date}-${rand}`;
4152
+ selMap.set(sel, base);
4153
+ }
4154
+ const uid = `${base}-${depth}-${index}`;
4155
+ const props = (el.data && el.data.props) || {};
4156
+ const id = (props.id && JSON.stringify(props.id)) || uid;
4157
+ const fullId = `${ name }::${ id }`;
4158
+ return fullId
4159
+ }
4160
+
4161
+
4162
+ function deepCopyVdom(obj) {
4163
+ if (typeof obj === 'undefined') return obj
4164
+ return { ...obj, children: Array.isArray(obj.children) ? obj.children.map(deepCopyVdom) : undefined, data: obj.data && { ...obj.data, componentsInjected: false } }
4165
+ }
4166
+
4167
+ function processForm(form, options={}) {
4168
+ let { events = ['input', 'submit'], preventDefault = true } = options;
4169
+ if (typeof events === 'string') events = [events];
4170
+
4171
+ const eventStream$ = events.map(event => form.events(event));
4172
+
4173
+ const merged$ = xs__default["default"].merge(...eventStream$);
4174
+
4175
+ return merged$.map((e) => {
4176
+ if (preventDefault) e.preventDefault();
4177
+ const form = (e.type === 'submit') ? e.srcElement : e.currentTarget;
4178
+ const formData = new FormData(form);
4179
+ let entries = {};
4180
+ entries.event = e;
4181
+ entries.eventType = e.type;
4182
+ const submitBtn = form.querySelector('input[type=submit]:focus');
4183
+ if (submitBtn) {
4184
+ const { name, value } = submitBtn;
4185
+ entries[name || 'submit'] = value;
4186
+ }
4187
+ for (let [name, value] of formData.entries()) {
4188
+ entries[name] = value;
4189
+ }
4190
+ return entries
4191
+ })
4192
+ }
4193
+
4194
+ var adapt$1 = {};
4195
+
4196
+ Object.defineProperty(adapt$1, "__esModule", { value: true });
4197
+ function getGlobal() {
4198
+ var globalObj;
4199
+ if (typeof window !== 'undefined') {
4200
+ globalObj = window;
4201
+ }
4202
+ else if (typeof commonjsGlobal !== 'undefined') {
4203
+ globalObj = commonjsGlobal;
4204
+ }
4205
+ else {
4206
+ globalObj = this;
4207
+ }
4208
+ globalObj.Cyclejs = globalObj.Cyclejs || {};
4209
+ globalObj = globalObj.Cyclejs;
4210
+ globalObj.adaptStream = globalObj.adaptStream || (function (x) { return x; });
4211
+ return globalObj;
4212
+ }
4213
+ function setAdapt(f) {
4214
+ getGlobal().adaptStream = f;
4215
+ }
4216
+ adapt$1.setAdapt = setAdapt;
4217
+ function adapt(stream) {
4218
+ return getGlobal().adaptStream(stream);
4219
+ }
4220
+ var adapt_2 = adapt$1.adapt = adapt;
4221
+
4222
+ function eventBusDriver(out$) {
4223
+ const events = new EventTarget();
4224
+
4225
+ out$.subscribe({
4226
+ next: event => events.dispatchEvent(new CustomEvent('data', { detail: event }))
4227
+ });
4228
+
4229
+ return {
4230
+ select: (type) => {
4231
+ const all = !type;
4232
+ const _type = (Array.isArray(type)) ? type : [type];
4233
+ let cb;
4234
+ const in$ = xs__default["default"].create({
4235
+ start: (listener) => {
4236
+ cb = ({detail: event}) => {
4237
+ const data = (event && event.data) || null;
4238
+ if (all || _type.includes(event.type)) listener.next(data);
4239
+ };
4240
+ events.addEventListener('data', cb);
4241
+ },
4242
+ stop: _ => events.removeEventListener('data', cb)
4243
+ });
4244
+
4245
+ return adapt_2(in$)
4246
+ }
4247
+ }
4248
+ }
4249
+
4250
+ function logDriver(out$) {
4251
+ out$.addListener({
4252
+ next: (val) => {
4253
+ console.log(val);
4254
+ }
4255
+ });
4256
+ }
4257
+
4258
+ function run(app, drivers={}, options={}) {
4259
+ const { mountPoint='#root', fragments=true } = options;
4260
+
4261
+ const wrapped = state.withState(app, 'STATE');
4262
+
4263
+ const baseDrivers = {
4264
+ EVENTS: eventBusDriver,
4265
+ DOM: dom.makeDOMDriver(mountPoint, { snabbdomOptions: { experimental: { fragments } } }),
4266
+ LOG: logDriver
4267
+ };
4268
+
4269
+ const combinedDrivers = { ...baseDrivers, ...drivers };
4270
+
4271
+ return run$1.run(wrapped, combinedDrivers)
4272
+ }
4273
+
4274
+ /**
4275
+ * return a validated and properly separated string of CSS class names from any number of strings, arrays, and objects
4276
+ *
4277
+ * @param {...String|Array|Object} args any number of strings or arrays with valid CSS class names, or objects where the keys are valid class names and the values evaluate to true or false
4278
+ * @return {String} list of `active` classes separated by spaces
4279
+ *
4280
+ * any `string` or `array` arguments are simply validated and appended to the result
4281
+ * `objects` will evaluate the values (which can be booleans or functions), and the keys with `thruthy` values will be validated and appended to the result
4282
+ * this function makes it easier to set dynamic classes on HTML elements
4283
+ */
4284
+ function classes(...args) {
4285
+ return args.reduce((acc, arg) => {
4286
+ if (typeof arg === 'string' && !acc.includes(arg)) {
4287
+ acc.push(...classes_processString(arg));
4288
+ } else if (Array.isArray(arg)) {
4289
+ acc.push(...classes_processArray(arg));
4290
+ } else if (typeof arg === 'object') {
4291
+ acc.push(...classes_processObject(arg));
4292
+ }
4293
+ return acc
4294
+ }, []).join(' ')
4295
+ }
4296
+
4297
+
4298
+
4299
+ /**
4300
+ * validate a string as a CSS class name
4301
+ *
4302
+ * @param {String} className CSS class name to validate
4303
+ * @return {Boolean} true if the name is a valid CSS class, false otherwise
4304
+ */
4305
+ function isValidClassName (className) {
4306
+ return /^[a-zA-Z0-9-_]+$/.test(className)
4307
+ }
4308
+
4309
+ /**
4310
+ * find and validate CSS class names in a string
4311
+ *
4312
+ * @param {String} str string containing one or more CSS class names
4313
+ * @return {Array} valid CSS classnames from the provided string
4314
+ */
4315
+ function classes_processString(str) {
4316
+ if (typeof str !== 'string') throw new Error('Class name must be a string')
4317
+ return str.trim().split(' ').reduce((acc, item) => {
4318
+ if (item.trim().length === 0) return acc
4319
+ if (!isValidClassName(item)) throw new Error(`${item} is not a valid CSS class name`)
4320
+ acc.push(item);
4321
+ return acc
4322
+ }, [])
4323
+ }
4324
+
4325
+ /**
4326
+ * find and validate CSS class names in an array of strings
4327
+ *
4328
+ * @param {Array} arr array containing one or more strings with valid CSS class names
4329
+ * @return {Array} valid CSS class names from the provided array
4330
+ */
4331
+ function classes_processArray(arr) {
4332
+ return arr.map(classes_processString).flat()
4333
+ }
4334
+
4335
+ /**
4336
+ * find and validate CSS class names in an object, and exclude keys whose value evaluates to `false`
4337
+ *
4338
+ * @param {Object} obj object with keys as CSS class names and values which if `truthy` cause the associated key to be returned
4339
+ * @return {Array} valid CSS class names from the keys of the provided object where the associated value evaluated to `true`
4340
+ *
4341
+ * the value for each key can be either a value that evaluates to a boolean or a function that returns a boolean
4342
+ * if the value is a function, it will be run and the returned value will be used
4343
+ */
4344
+ function classes_processObject(obj) {
4345
+ const ret = Object.entries(obj)
4346
+ .filter(([key, predicate]) => (typeof predicate === 'function') ? predicate() : !!predicate)
4347
+ .map(([key, _]) => {
4348
+ const trimmed = key.trim();
4349
+ if (!isValidClassName(trimmed)) throw new Error (`${trimmed} is not a valid CSS class name`)
4350
+ return trimmed
4351
+ });
4352
+ return ret
4353
+ }
4354
+
4355
+ var throttle$1 = {};
4356
+
4357
+ Object.defineProperty(throttle$1, "__esModule", { value: true });
4358
+ var index_1$1 = xstream;
4359
+ var ThrottleOperator = /** @class */ (function () {
4360
+ function ThrottleOperator(dt, ins) {
4361
+ this.dt = dt;
4362
+ this.ins = ins;
4363
+ this.type = 'throttle';
4364
+ this.out = null;
4365
+ this.id = null;
4366
+ }
4367
+ ThrottleOperator.prototype._start = function (out) {
4368
+ this.out = out;
4369
+ this.ins._add(this);
4370
+ };
4371
+ ThrottleOperator.prototype._stop = function () {
4372
+ this.ins._remove(this);
4373
+ this.out = null;
4374
+ this.id = null;
4375
+ };
4376
+ ThrottleOperator.prototype.clearInterval = function () {
4377
+ var id = this.id;
4378
+ if (id !== null) {
4379
+ clearInterval(id);
4380
+ }
4381
+ this.id = null;
4382
+ };
4383
+ ThrottleOperator.prototype._n = function (t) {
4384
+ var _this = this;
4385
+ var u = this.out;
4386
+ if (!u)
4387
+ return;
4388
+ if (this.id)
4389
+ return;
4390
+ u._n(t);
4391
+ this.id = setInterval(function () {
4392
+ _this.clearInterval();
4393
+ }, this.dt);
4394
+ };
4395
+ ThrottleOperator.prototype._e = function (err) {
4396
+ var u = this.out;
4397
+ if (!u)
4398
+ return;
4399
+ this.clearInterval();
4400
+ u._e(err);
4401
+ };
4402
+ ThrottleOperator.prototype._c = function () {
4403
+ var u = this.out;
4404
+ if (!u)
4405
+ return;
4406
+ this.clearInterval();
4407
+ u._c();
4408
+ };
4409
+ return ThrottleOperator;
4410
+ }());
4411
+ /**
4412
+ * Emits event and drops subsequent events until a certain amount of silence has passed.
4413
+ *
4414
+ * Marble diagram:
4415
+ *
4416
+ * ```text
4417
+ * --1-2-----3--4----5|
4418
+ * throttle(60)
4419
+ * --1-------3-------5-|
4420
+ * ```
4421
+ *
4422
+ * Example:
4423
+ *
4424
+ * ```js
4425
+ * import fromDiagram from 'xstream/extra/fromDiagram'
4426
+ * import throttle from 'xstream/extra/throttle'
4427
+ *
4428
+ * const stream = fromDiagram('--1-2-----3--4----5|')
4429
+ * .compose(throttle(60))
4430
+ *
4431
+ * stream.addListener({
4432
+ * next: i => console.log(i),
4433
+ * error: err => console.error(err),
4434
+ * complete: () => console.log('completed')
4435
+ * })
4436
+ * ```
4437
+ *
4438
+ * ```text
4439
+ * > 1
4440
+ * > 3
4441
+ * > 5
4442
+ * > completed
4443
+ * ```
4444
+ *
4445
+ * @param {number} period The amount of silence required in milliseconds.
4446
+ * @return {Stream}
4447
+ */
4448
+ function throttle(period) {
4449
+ return function throttleOperator(ins) {
4450
+ return new index_1$1.Stream(new ThrottleOperator(period, ins));
4451
+ };
4452
+ }
4453
+ var _default$1 = throttle$1.default = throttle;
4454
+
4455
+ var sampleCombine$1 = {};
4456
+
4457
+ var __spreadArrays = (commonjsGlobal && commonjsGlobal.__spreadArrays) || function () {
4458
+ for (var s = 0, i = 0, il = arguments.length; i < il; i++) s += arguments[i].length;
4459
+ for (var r = Array(s), k = 0, i = 0; i < il; i++)
4460
+ for (var a = arguments[i], j = 0, jl = a.length; j < jl; j++, k++)
4461
+ r[k] = a[j];
4462
+ return r;
4463
+ };
4464
+ Object.defineProperty(sampleCombine$1, "__esModule", { value: true });
4465
+ sampleCombine$1.SampleCombineOperator = sampleCombine$1.SampleCombineListener = void 0;
4466
+ var index_1 = xstream;
4467
+ var NO = {};
4468
+ var SampleCombineListener = /** @class */ (function () {
4469
+ function SampleCombineListener(i, p) {
4470
+ this.i = i;
4471
+ this.p = p;
4472
+ p.ils[i] = this;
4473
+ }
4474
+ SampleCombineListener.prototype._n = function (t) {
4475
+ var p = this.p;
4476
+ if (p.out === NO)
4477
+ return;
4478
+ p.up(t, this.i);
4479
+ };
4480
+ SampleCombineListener.prototype._e = function (err) {
4481
+ this.p._e(err);
4482
+ };
4483
+ SampleCombineListener.prototype._c = function () {
4484
+ this.p.down(this.i, this);
4485
+ };
4486
+ return SampleCombineListener;
4487
+ }());
4488
+ sampleCombine$1.SampleCombineListener = SampleCombineListener;
4489
+ var SampleCombineOperator = /** @class */ (function () {
4490
+ function SampleCombineOperator(ins, streams) {
4491
+ this.type = 'sampleCombine';
4492
+ this.ins = ins;
4493
+ this.others = streams;
4494
+ this.out = NO;
4495
+ this.ils = [];
4496
+ this.Nn = 0;
4497
+ this.vals = [];
4498
+ }
4499
+ SampleCombineOperator.prototype._start = function (out) {
4500
+ this.out = out;
4501
+ var s = this.others;
4502
+ var n = this.Nn = s.length;
4503
+ var vals = this.vals = new Array(n);
4504
+ for (var i = 0; i < n; i++) {
4505
+ vals[i] = NO;
4506
+ s[i]._add(new SampleCombineListener(i, this));
4507
+ }
4508
+ this.ins._add(this);
4509
+ };
4510
+ SampleCombineOperator.prototype._stop = function () {
4511
+ var s = this.others;
4512
+ var n = s.length;
4513
+ var ils = this.ils;
4514
+ this.ins._remove(this);
4515
+ for (var i = 0; i < n; i++) {
4516
+ s[i]._remove(ils[i]);
4517
+ }
4518
+ this.out = NO;
4519
+ this.vals = [];
4520
+ this.ils = [];
4521
+ };
4522
+ SampleCombineOperator.prototype._n = function (t) {
4523
+ var out = this.out;
4524
+ if (out === NO)
4525
+ return;
4526
+ if (this.Nn > 0)
4527
+ return;
4528
+ out._n(__spreadArrays([t], this.vals));
4529
+ };
4530
+ SampleCombineOperator.prototype._e = function (err) {
4531
+ var out = this.out;
4532
+ if (out === NO)
4533
+ return;
4534
+ out._e(err);
4535
+ };
4536
+ SampleCombineOperator.prototype._c = function () {
4537
+ var out = this.out;
4538
+ if (out === NO)
4539
+ return;
4540
+ out._c();
4541
+ };
4542
+ SampleCombineOperator.prototype.up = function (t, i) {
4543
+ var v = this.vals[i];
4544
+ if (this.Nn > 0 && v === NO) {
4545
+ this.Nn--;
4546
+ }
4547
+ this.vals[i] = t;
4548
+ };
4549
+ SampleCombineOperator.prototype.down = function (i, l) {
4550
+ this.others[i]._remove(l);
4551
+ };
4552
+ return SampleCombineOperator;
4553
+ }());
4554
+ sampleCombine$1.SampleCombineOperator = SampleCombineOperator;
4555
+ var sampleCombine;
4556
+ /**
4557
+ *
4558
+ * Combines a source stream with multiple other streams. The result stream
4559
+ * will emit the latest events from all input streams, but only when the
4560
+ * source stream emits.
4561
+ *
4562
+ * If the source, or any input stream, throws an error, the result stream
4563
+ * will propagate the error. If any input streams end, their final emitted
4564
+ * value will remain in the array of any subsequent events from the result
4565
+ * stream.
4566
+ *
4567
+ * The result stream will only complete upon completion of the source stream.
4568
+ *
4569
+ * Marble diagram:
4570
+ *
4571
+ * ```text
4572
+ * --1----2-----3--------4--- (source)
4573
+ * ----a-----b-----c--d------ (other)
4574
+ * sampleCombine
4575
+ * -------2a----3b-------4d--
4576
+ * ```
4577
+ *
4578
+ * Examples:
4579
+ *
4580
+ * ```js
4581
+ * import sampleCombine from 'xstream/extra/sampleCombine'
4582
+ * import xs from 'xstream'
4583
+ *
4584
+ * const sampler = xs.periodic(1000).take(3)
4585
+ * const other = xs.periodic(100)
4586
+ *
4587
+ * const stream = sampler.compose(sampleCombine(other))
4588
+ *
4589
+ * stream.addListener({
4590
+ * next: i => console.log(i),
4591
+ * error: err => console.error(err),
4592
+ * complete: () => console.log('completed')
4593
+ * })
4594
+ * ```
4595
+ *
4596
+ * ```text
4597
+ * > [0, 8]
4598
+ * > [1, 18]
4599
+ * > [2, 28]
4600
+ * ```
4601
+ *
4602
+ * ```js
4603
+ * import sampleCombine from 'xstream/extra/sampleCombine'
4604
+ * import xs from 'xstream'
4605
+ *
4606
+ * const sampler = xs.periodic(1000).take(3)
4607
+ * const other = xs.periodic(100).take(2)
4608
+ *
4609
+ * const stream = sampler.compose(sampleCombine(other))
4610
+ *
4611
+ * stream.addListener({
4612
+ * next: i => console.log(i),
4613
+ * error: err => console.error(err),
4614
+ * complete: () => console.log('completed')
4615
+ * })
4616
+ * ```
4617
+ *
4618
+ * ```text
4619
+ * > [0, 1]
4620
+ * > [1, 1]
4621
+ * > [2, 1]
4622
+ * ```
4623
+ *
4624
+ * @param {...Stream} streams One or more streams to combine with the sampler
4625
+ * stream.
4626
+ * @return {Stream}
4627
+ */
4628
+ sampleCombine = function sampleCombine() {
4629
+ var streams = [];
4630
+ for (var _i = 0; _i < arguments.length; _i++) {
4631
+ streams[_i] = arguments[_i];
4632
+ }
4633
+ return function sampleCombineOperator(sampler) {
4634
+ return new index_1.Stream(new SampleCombineOperator(sampler, streams));
4635
+ };
4636
+ };
4637
+ var _default = sampleCombine$1.default = sampleCombine;
4638
+
4639
+ Object.defineProperty(exports, 'xs', {
4640
+ enumerable: true,
4641
+ get: function () { return xs__default["default"]; }
4642
+ });
4643
+ exports.ABORT = ABORT;
4644
+ exports.classes = classes;
4645
+ exports.collection = collection;
4646
+ exports.component = component;
4647
+ exports.debounce = _default$2;
4648
+ exports.delay = _default$4;
4649
+ exports.dropRepeats = _default$5;
4650
+ exports.processForm = processForm;
4651
+ exports.run = run;
4652
+ exports.sampleCombine = _default;
4653
+ exports.switchable = switchable;
4654
+ exports.throttle = _default$1;
4655
+ Object.keys(dom).forEach(function (k) {
4656
+ if (k !== 'default' && !exports.hasOwnProperty(k)) Object.defineProperty(exports, k, {
4657
+ enumerable: true,
4658
+ get: function () { return dom[k]; }
4659
+ });
4660
+ });