-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathobservable.js
More file actions
1867 lines (1744 loc) · 80 KB
/
observable.js
File metadata and controls
1867 lines (1744 loc) · 80 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// getting a reference of some used global objects as globalThis is getting undefined when a iframe is removed
const { AbortController, AbortSignal, WeakMap, WeakRef, Window, reportError = console.log } = globalThis;
// https://html.spec.whatwg.org/multipage/document-sequences.html#fully-active
// A Document d is said to be fully active when d is the active document of
// a navigable navigable, and either navigable is a top-level traversable or
// navigable's container document is fully active.
const isDocumentFullyActive = (d) => d && d.defaultView !== null && d.defaultView.document === d && (d.defaultView.top === d.defaultView || isDocumentFullyActive(d.defaultView.parent.document));
// check if we run in a browser
const isBrowserContext = () => !!Window && globalThis instanceof Window;
const unset = Symbol("unset");
const [Observable, Subscriber] = (() => {
function enumerate(obj, key, enumerable = true) {
Object.defineProperty(obj, key, {
...Object.getOwnPropertyDescriptor(obj, key),
enumerable,
});
}
const pTry = "try" in Promise ? Promise.try.bind(Promise) : (fn, ...args) => new Promise((r) => r(fn(...args)));
const pWithResolvers = 'withResolvers' in Promise ? Promise.withResolvers.bind(Promise) : () => {
let resolve, reject;
const promise = new Promise((res, rej) => ((resolve = res), (reject = rej)));
return { promise, resolve, reject };
};
function getIteratorFromMethod(obj, method) {
// 1. Let iterator be ? Call(method, obj).
const iterator = method.call(obj);
// 2. If iterator is not an Object, throw a TypeError exception.
if (iterator === null || typeof iterator !== "object") throw new TypeError("Iterator is not an object");
// 3. Return ? GetIteratorDirect(iterator)
return iterator;
}
const privateState = new WeakMap();
const AsyncFromSyncIteratorPrototype = {
next(...args) {
// 1. Let O be the this value.
const O = this;
// 2. Assert: O is an Object that has a [[SyncIteratorRecord]] internal slot.
const state = privateState.get(O);
if (!state?.syncIteratorRecord)
throw new TypeError(
"AsyncFromSyncIteratorPrototype.next called on invalid object"
);
// 4. Let syncIteratorRecord be O.[[SyncIteratorRecord]].
const { syncIteratorRecord } = state;
return pTry(() => syncIteratorRecord.next(...args));
},
return(...args) {
// 1. Let O be the this value.
const O = this;
// 2. Assert: O is an Object that has a [[SyncIteratorRecord]] internal slot.
const state = privateState.get(O);
if (!state?.syncIteratorRecord)
throw new TypeError(
"AsyncFromSyncIteratorPrototype.return called on invalid object"
);
// 4. Let syncIteratorRecord be O.[[SyncIteratorRecord]].
const { syncIteratorRecord } = state;
return pTry(() => {
if (!syncIteratorRecord.return) return { value: undefined, done: true };
return syncIteratorRecord.return(...args);
});
},
throw(...args) {
// 1. Let O be the this value.
const O = this;
// 2. Assert: O is an Object that has a [[SyncIteratorRecord]] internal slot.
const state = privateState.get(O);
if (!state?.syncIteratorRecord)
throw new TypeError(
"AsyncFromSyncIteratorPrototype.throw called on invalid object"
);
// 4. Let syncIteratorRecord be O.[[SyncIteratorRecord]].
const { syncIteratorRecord } = state;
return pTry(() => {
if (!syncIteratorRecord.throw) {
// a. NOTE: If syncIterator does not have a throw method, close it to give it a chance to clean up before we reject the capability.
syncIteratorRecord.return();
throw new TypeError("no throw method");
}
return syncIteratorRecord.throw(...args);
});
},
};
function createAsyncFromSyncIterator(syncIteratorRecord) {
// 1. Let asyncIterator be OrdinaryObjectCreate(%AsyncFromSyncIteratorPrototype%, « [[SyncIteratorRecord]] »).
const asyncIterator = Object.create(AsyncFromSyncIteratorPrototype);
// 2. Set asyncIterator.[[SyncIteratorRecord]] to syncIteratorRecord.
privateState.set(asyncIterator, { syncIteratorRecord });
return asyncIterator;
}
function getIterator(obj, isAsync) {
let method = undefined;
// 1. if kind is ASYNC, then
if (isAsync) {
// 1.a. Let method be ? GetMethod(obj, %Symbol.asyncIterator%).
method = obj[Symbol.asyncIterator];
// 1.b. If method is undefined, then
if (method == undefined) {
// 1.b.i. Let method be ? GetMethod(obj, %Symbol.iterator%).
method = obj[Symbol.iterator];
// 1.b.ii. If method is undefined, throw a TypeError exception.
if (method == undefined) throw new TypeError("Object is not async iterable");
// 1.b.iii. Let syncIteratorRecord be ? GetIteratorFromMethod(obj, syncMethod).
const syncIteratorRecord = getIteratorFromMethod(obj, method);
// 1.b.iv. Return ! CreateAsyncFromSyncIterator(syncIteratorRecord).
return createAsyncFromSyncIterator(syncIteratorRecord);
}
// 2. Else,
} else {
// 2.a. Let method be ? GetMethod(obj, %Symbol.iterator%).
method = obj[Symbol.iterator];
}
// 3. If method is undefined, throw a TypeError exception.
if (method == undefined) throw new TypeError("Object is not iterable");
// 4. Return ? GetIteratorFromMethod(obj, method).
return getIteratorFromMethod(obj, method);
}
const abortSignalAny = "any" in AbortSignal ? AbortSignal.any.bind(AbortSignal) : (signals) => {
// create a signal that will abort when any of the signals aborts.
const ac = new AbortController();
// when any of the signals is already aborted, abort ac immediately and return its signal.
for (const signal of signals) {
if (signal.aborted) {
ac.abort(signal.reason);
return ac.signal;
}
}
// otherwise, add an abort listener to each signal that will abort ac.
for (const signal of signals) {
signal.addEventListener("abort", () => {
ac.abort(signal.reason);
}, { signal: ac.signal });
}
// return the signal.
return ac.signal;
};
// wrapper for AbortSignal.any that removes null and undefined, for convenience.
const anySignal = (signalArray) => abortSignalAny(signalArray.filter(Boolean));
class InternalObserver {
constructor({ next, error, complete } = {}) {
privateState.set(this, { next, error, complete });
}
next(value) {
const { next } = privateState.get(this) || {};
if (next) next(value);
}
error(value) {
const { error } = privateState.get(this) || {};
if (error) error(value);
else reportError(value);
}
complete() {
const { complete } = privateState.get(this) || {};
if (complete) complete();
}
}
// https://wicg.github.io/observable/#close-a-subscription
function closeASubscription(subscriber, reason) {
const state = privateState.get(subscriber);
// 1. If subscriber’s active is false, then return.
if (!state?.active) return;
// 2. Set subscriber’s active boolean to false.
state.active = false;
// 3. Signal abort subscriber’s subscription controller with reason, if it is given.
state.subscriptionController.abort(reason);
// 4. For each teardown of subscriber’s teardown callbacks sorted in reverse insertion order:
for (const teardown of state.teardowns.reverse()) {
// 4.1. If subscriber’s relevant global object is a Window object, and its associated Document is not fully active, then abort these steps.
if (isBrowserContext() && !isDocumentFullyActive(document)) return;
// 4.2. Invoke teardown.
try {
teardown();
} catch (e) {
reportError(e);
}
}
}
// https://wicg.github.io/observable/#observable-subscribe-to-an-observable
function subscribeTo(observable, observer, options = {}) {
// 1. If this’s relevant global object is a Window object, and its associated Document is not fully active, then return.
if (isBrowserContext() && !isDocumentFullyActive(document)) return;
// 2. Let internal observer be a new internal observer.
let internalObserver;
// 3. Process observer as follows:
// 3.1. If observer is an ObservableSubscriptionCallback
if (typeof observer == "function") {
// 3.2. Set internal observer’s next steps to these steps that take an
// any value:
internalObserver = new InternalObserver({ next: observer });
// 4. If observer is a SubscriptionObserver
} else if (observer && !(observer instanceof InternalObserver)) {
// 4.1. If observer’s next exists, then set internal observer’s next
// steps to these steps that take an any value:
// 4.2. If observer’s error exists, then set internal observer’s error
// steps to these steps that take an any error:
// 4.3. If observer’s complete exists, then set internal observer’s
// complete steps to these steps:
internalObserver = new InternalObserver(observer);
} else {
internalObserver = observer || new InternalObserver();
}
const observableState = privateState.get(observable);
// 5. If this’s weak subscriber is not null and this’s weak subscriber’s active is true:
const existingSubscriber = observableState.weakSubscriber?.deref();
if (existingSubscriber?.active) {
// 5.1. Let subscriber be this’s weak subscriber.
const subscriber = existingSubscriber;
const subscriberState = privateState.get(subscriber);
// 5.2. Append internal observer to subscriber’s internal observers.
subscriberState.observers.add(internalObserver);
// 5.3. If options’s signal exists, then:
if (options.signal) {
// 5.3.1 If options’s signal is aborted, then remove internal observer from subscriber’s internal observers.
if (options.signal.aborted) subscriberState.observers.delete(internalObserver);
// 5.3.2 Otherwise, add the following abort algorithm to options’s signal:
else options.signal.addEventListener("abort", () => {
const subscriberState = privateState.get(subscriber);
// 5.3.2.1 If subscriber’s active is false, then abort these steps.
if (!subscriberState?.active) return;
// 5.3.2.2 Remove internal observer from subscriber’s internal observers.
subscriberState.observers.delete(internalObserver);
// 5.3.2.3 If subscriber’s internal observers is empty, then close subscriber with options’s signal’s abort reason.
if (subscriberState.observers.size == 0) {
closeASubscription(subscriber, options.signal.reason);
}
});
}
// 5.4. return
return;
}
// 6. Let subscriber be a new Subscriber.
// 7. Append internal observer to subscriber’s internal observers.
const subscriber = new Subscriber(internalObserver);
// 8. Set this’s weak subscriber to subscriber.
observableState.weakSubscriber = new WeakRef(subscriber);
// 9. If options’s signal exists, then:
if ("signal" in options) {
// 9.1. If options’s signal is aborted, then close subscriber given options’s signal abort reason.
if (options.signal.aborted)
closeASubscription(subscriber, options.signal.reason);
// 9.2. Otherwise, add the following abort algorithm to options’s signal:
else
options.signal.addEventListener("abort", () => {
const subscriberState = privateState.get(subscriber);
// 9.2.1. If subscriber’s active is false, then abort these steps.
if (!subscriberState?.active) return;
// 9.2.2. Remove internal observer from subscriber’s internal observers.
subscriberState.observers.delete(internalObserver);
// 9.2.3. If subscriber’s internal observers is empty, then close subscriber with options’s signal’s abort reason.
if (subscriberState.observers.size == 0) {
closeASubscription(subscriber, options.signal.reason);
}
});
}
// 7. If observable's subscribe callback is a SubscribeCallback, invoke it with subscriber.
if (observableState.subscribeCallback) {
// If an exception E was thrown, call subscriber’s error() method with E.
try {
observableState.subscribeCallback(subscriber);
} catch (e) {
subscriber.error(e);
}
}
// 8. Otherwise, run the steps given by observable's subscribe callback, given subscriber.
// (Not needed because internal subscribers use the same callback function)
}
// https://wicg.github.io/observable/#subscriber-api
class Subscriber {
get [Symbol.toStringTag]() {
return "Subscriber";
}
constructor(internalObserver = null) {
if (!(internalObserver instanceof InternalObserver)) {
throw new TypeError("Illegal constructor");
}
privateState.set(this, {
active: true,
observers: new Set([internalObserver]),
teardowns: [],
subscriptionController: new AbortController(),
});
}
// https://wicg.github.io/observable/#dom-subscriber-next
next(value) {
if (!(this instanceof Subscriber))
throw new TypeError("illegal invocation");
if (!arguments.length) throw new TypeError("too few arguments");
const state = privateState.get(this);
// 1. If this's active is false, then return.
if (!state?.active) return;
// 2. If this’s relevant global object is a Window object, and its associated Document is not fully active, then return.
if (isBrowserContext() && !isDocumentFullyActive(document)) return;
// 3. Let internal observers copy be a copy of this’s internal observers.
const internalObservers = new Set(state.observers);
// 4. For each observer of this’s internal observers copy:
for (const observer of internalObservers) {
// 3.1. Run observer’s next steps given value.
observer.next(value);
}
}
// https://wicg.github.io/observable/#dom-subscriber-error
error(error) {
if (!(this instanceof Subscriber))
throw new TypeError("illegal invocation");
if (!arguments.length) throw new TypeError("too few arguments");
const state = privateState.get(this);
// 1. If this’s active is false, report an exception with error and this’s relevant global object, then return.
if (!state?.active) {
reportError(error);
return;
}
// 2. If this’s relevant global object is a Window object, and its associated Document is not fully active, then return.
if (isBrowserContext() && !isDocumentFullyActive(document)) return;
// 3. Close this.
closeASubscription(this, error);
// 4. Let internal observers copy be a copy of this’s internal observers.
const internalObservers = new Set(state.observers);
// 5. For each observer of this’s internal observers copy:
for (const observer of internalObservers) {
// 5.1. Run observer’s error steps given error.
observer.error(error);
}
}
// https://wicg.github.io/observable/#dom-subscriber-complete
complete() {
if (!(this instanceof Subscriber))
throw new TypeError("illegal invocation");
const state = privateState.get(this);
// 1. If this's active is false, then return.
if (!state?.active) return;
// 2. If this’s relevant global object is a Window object, and its associated Document is not fully active, then return.
if (isBrowserContext() && !isDocumentFullyActive(document)) return;
// 3. Close this.
closeASubscription(this);
// 4. Let internal observers copy be a copy of this’s internal observers.
const internalObservers = new Set(state.observers);
// 5. For each observer of this’s internal observers copy:
for (const observer of internalObservers) {
// 5.1. Run observer’s complete steps.
observer.complete();
}
}
// https://wicg.github.io/observable/#dom-subscriber-addteardown
addTeardown(teardown) {
if (!(this instanceof Subscriber))
throw new TypeError("illegal invocation");
if (typeof teardown != "function") {
throw new TypeError(`Parameter 1 is not of type 'Function'`);
}
// 1. If this’s relevant global object is a Window object, and its associated Document is not fully active, then return.
if (isBrowserContext() && !isDocumentFullyActive(document)) return;
// 2. If this's active is true, then append teardown to this's teardown callbacks list.
const state = privateState.get(this);
if (state?.active)
state.teardowns.push(teardown);
// 3. Otherwise, invoke teardown.
else teardown();
}
get active() {
if (!(this instanceof Subscriber))
throw new TypeError("illegal invocation");
return !!privateState.get(this)?.active;
}
get signal() {
if (!(this instanceof Subscriber))
throw new TypeError("illegal invocation");
if (!privateState.has(this)) {
const controller = new AbortController();
controller.abort();
return controller.signal;
}
return privateState.get(this).subscriptionController.signal;
}
}
enumerate(Subscriber.prototype, "next");
enumerate(Subscriber.prototype, "error");
enumerate(Subscriber.prototype, "complete");
enumerate(Subscriber.prototype, "addTeardown");
enumerate(Subscriber.prototype, "active");
enumerate(Subscriber.prototype, "signal");
// https://wicg.github.io/observable/#observable-api
class Observable {
get [Symbol.toStringTag]() {
return "Observable";
}
// https://wicg.github.io/observable/#dom-observable-observable
constructor(subscribeCallback) {
if (!subscribeCallback) {
throw new TypeError("1 argument required but 0 present");
}
privateState.set(this, {
weakSubscriber: null,
subscribeCallback,
});
}
// https://wicg.github.io/observable/#observable-from
static from(value) {
// 1. If Type(value) is not Object, throw a TypeError.
if (value === null || typeof value !== "object") throw new TypeError("Observable.from only accepts objects");
// 2. From Observable: If value’s specific type is an Observable, then return value.
if (value instanceof Observable) return value;
// 3. Let asyncIteratorMethodRecord be GetMethod(value, %Symbol.asyncIterator%).
const asyncIteratorMethodRecord = Symbol.asyncIterator in value && value[Symbol.asyncIterator];
// 4. If asyncIteratorMethod’s is undefined or null, then jump to the step labeled From iterable.
if (typeof asyncIteratorMethodRecord === "function") {
let done = false;
// 5. Let nextAlgorithm be the following steps, given a Subscriber subscriber and an Iterator Record iteratorRecord:
function nextAlgorithm(subscriber, iteratorRecord) {
// 5.1. If subscriber’s subscription controller’s signal is aborted, then return.
if (subscriber.signal.aborted) return;
// 5.2. Let nextPromise be a Promise-or-undefined, initially undefined.
let nextPromise = undefined;
try {
// 5.3. Let nextCompletion be IteratorNext(iteratorRecord).
let nextCompletion = iteratorRecord.next();
// 5.5. Otherwise, if nextRecord is normal completion, then set nextPromise to a promise resolved with nextRecord’s [[Value]].
nextPromise = Promise.resolve(nextCompletion);
} catch (error) {
// 5.4. If nextCompletion is a throw completion, then:
// 5.4.1. Assert: iteratorRecord’s [[Done]] is true.
// 5.4.2. Set nextPromise to a promise rejected with nextRecord’s [[Value]].
nextPromise = Promise.reject(error);
}
// 5.6. React to nextPromise:
nextPromise.then(
// If nextPromise was fulfilled with value iteratorResult, then:
(iteratorResult) => {
// 5.6.1 If Type(iteratorResult) is not Object, then run subscriber’s error() method with a TypeError and abort these steps.
if (iteratorResult === null || typeof iteratorResult !== "object") {
subscriber.error(new TypeError("Not an IteratorResult."));
return;
}
try {
// 5.6.2 Let done be IteratorComplete(iteratorResult).
({ done } = iteratorResult);
} catch (error) {
// 5.6.3 If done is a throw completion, then run subscriber’s error() method with done’s [[Value]] and abort these steps.
subscriber.error(error);
return;
}
// 5.6.4. If done’s [[Value]] is true, then run subscriber’s complete() and abort these steps.
if (done) {
subscriber.complete();
return;
}
let value;
try {
// 5.6.5. Let value be IteratorValue(iteratorResult).
value = iteratorResult.value;
} catch (error) {
// 5.6.6. If value is a throw completion, then run subscriber’s error() method with value’s [[Value]] and abort these steps.
subscriber.error(error);
return;
}
// 5.6.7. Run subscriber’s next() given value’s [[Value]].
subscriber.next(value);
// 5.6.8. Run nextAlgorithm given subscriber and iteratorRecord.
nextAlgorithm(subscriber, iteratorRecord);
},
// If nextPromise was rejected with reason r, then run subscriber’s error() method given r.
(r) => {
subscriber.error(r);
}
);
}
// 6. Return a new Observable whose subscribe callback is an algorithm that takes a Subscriber subscriber and does the following:
return new Observable((subscriber) => {
// 6.1. If subscriber’s subscription controller’s signal is aborted, then return.
if (subscriber.signal.aborted) return;
let iteratorRecordCompletion;
try {
// 6.2. Let iteratorRecordCompletion be GetIterator(value, async).
iteratorRecordCompletion = getIterator(value, true);
} catch (error) {
// 6.3. If iteratorRecordCompletion is a throw completion, then run subscriber’s error() method with iteratorRecordCompletion’s [[Value]] and abort these steps.
subscriber.error(error);
return;
}
// 6.4. Let iteratorRecord be ! iteratorRecordCompletion.
// 6.5. Assert: iteratorRecord is an Iterator Record.
const iteratorRecord = iteratorRecordCompletion;
// 6.6. If subscriber’s subscription controller’s signal is aborted, then return.
if (subscriber.signal.aborted) return;
// 6.7. Add the following abort algorithm to subscriber’s subscription controller’s signal:
subscriber.signal.addEventListener("abort", () => {
// 6.7.1. Run AsyncIteratorClose(iteratorRecord, NormalCompletion(subscriber’s subscription controller’s abort reason)).
if (typeof iteratorRecord.return !== "function" || done) return;
const returnPromise = pTry(() => iteratorRecord.return(subscriber.signal.reason));
returnPromise.then((result) => {
if (result === null || typeof result !== "object") {
throw new TypeError("Iterator .return() must return an Object");
}
});
});
// 6.8. Run nextAlgorithm given subscriber and iteratorRecord.
nextAlgorithm(subscriber, iteratorRecord);
});
}
// 7. From iterable: Let iteratorMethod be ? GetMethod(value, %Symbol.iterator%).
let iteratorMethod = Symbol.iterator in value && value[Symbol.iterator];
// 8. If iteratorMethod is undefined, then jump to the step labeled From Promise.
if (typeof iteratorMethod === "function") {
// Otherwise, return a new Observable whose subscribe callback is an algorithm that takes a Subscriber subscriber and does the following:
return new Observable((subscriber) => {
// 8.1. If subscriber’s subscription controller’s signal is aborted, then return.
if (subscriber.signal.aborted) return;
let iteratorRecordCompletion;
try {
// 8.2. Let iteratorRecordCompletion be GetIterator(value, sync).
iteratorRecordCompletion = getIterator(value, false);
} catch (error) {
// 8.3. If iteratorRecordCompletion is a throw completion, then run subscriber’s error() method, given iteratorRecordCompletion’s [[Value]], and abort these steps.
subscriber.error(error);
return;
}
let done = false;
// 8.4. Let iteratorRecord be ! iteratorRecordCompletion.
let iteratorRecord = iteratorRecordCompletion;
// 8.5 If subscriber’s subscription controller’s signal is aborted, then return.
if (subscriber.signal.aborted) return;
// 8.6. Add the following abort algorithm to subscriber’s subscription controller’s signal:
subscriber.signal.addEventListener("abort", () => {
// 8.6.1. Run IteratorClose(iteratorRecord, NormalCompletion(UNUSED)).
if (typeof iteratorRecord.return !== "function" || done) return;
const returnResult = iteratorRecord.return();
if (returnResult === null || typeof returnResult !== "object") {
throw new TypeError("Iterator .return() must return an Object");
}
});
// 8.7. While true:
while (true) {
try {
// 8.7.1. Let next be IteratorStepValue(iteratorRecord).
let next = iteratorRecord.next();
({ done } = next);
// 8.7.3. Set next to ! to next.
// 8.7.4. If next is done, then:
if (done) {
// 8.7.4.1. Assert: iteratorRecord’s [[Done]] is true.
// 8.7.4.2. Run subscriber’s complete().
subscriber.complete();
// 8.7.4.3. return
return;
}
// 8.7.5 Run subscriber’s next() given next.
subscriber.next(next.value);
// 8.7.6. If subscriber’s subscription controller’s signal is aborted, then break.
if (subscriber.signal.aborted) break;
} catch (error) {
// 8.7.2. If next is a throw completion, then run subscriber’s error() method, given next’s [[Value]], and break.
subscriber.error(error);
break;
}
}
});
}
// 9. From Promise: If IsPromise(value) is true, then:
if (value instanceof Promise || typeof value.then === "function") {
// 9.1. Return a new Observable whose subscribe callback is an algorithm that takes a Subscriber subscriber and does the following:
return new Observable((subscriber) => {
// 9.1.1. React to value:
value.then(
// 9.1.1.1. If value was fulfilled with value v, then:
(v) => {
// 9.1.1.1.1 Run subscriber’s next() method, given v.
subscriber.next(v);
// 9.1.1.1.2 Run subscriber’s complete() method.
subscriber.complete();
},
// 9.1.1.2 If value was rejected with reason r, then run subscriber’s error() method, given r.
(r) => {
subscriber.error(r);
}
);
});
}
// 10. Throw a TypeError.
throw new TypeError("Could not convert value to Observable");
}
// https://wicg.github.io/observable/#dom-observable-subscribe
subscribe(observer = null, options = {}) {
if (!(this instanceof Observable))
throw new TypeError("illegal invocation");
// 1. Subscribe to this given observer and options.
subscribeTo(this, observer, options);
}
// https://wicg.github.io/observable/#dom-observable-takeuntil
takeUntil(value) {
if (!(this instanceof Observable))
throw new TypeError("illegal invocation");
// 1. Let sourceObservable be this.
let sourceObservable = this;
// 2. Let notifier be the result of converting value to an Observable.
let notifier = Observable.from(value);
// 3. Let observable be a new Observable whose subscribe callback is an algorithm that takes a Subscriber subscriber and does the following:
return new Observable((subscriber) => {
// 3.1. Let notifierObserver be a new internal observer, initialized as follows:
const notifierObserver = new InternalObserver({
// 3.1.1. For the next callback, run subscriber’s complete() method.
next() {
subscriber.complete();
},
// 3.1.2. For the error callback, run subscriber’s complete() method.
error() {
subscriber.complete();
},
});
// 3.2. Let options be a new SubscribeOptions whose signal is subscriber’s subscription controller's signal.
let options = { signal: subscriber.signal };
// 3.3. Subscribe to notifier given notifierObserver and options.
subscribeTo(notifier, notifierObserver, options);
// 3.4. If subscriber’s active is false, then return.
if (!subscriber.active) return;
// 3.5. Let sourceObserver be a new internal observer, initialized as follows:
let sourceObserver = new InternalObserver({
// 3.5.1. For the next callback, run subscriber’s next() method, given the passed in value.
next(value) {
subscriber.next(value);
},
// 3.5.2. For the error callback, run subscriber’s error() method, given the passed in error.
error(value) {
subscriber.error(value);
},
// 3.5.3. For the complete callback, run subscriber’s complete() method.
complete() {
subscriber.complete();
},
});
// 3.6. Subscribe to sourceObservable given sourceObserver and options.
subscribeTo(sourceObservable, sourceObserver, options);
});
}
// https://wicg.github.io/observable/#dom-observable-map
map(mapper) {
if (!(this instanceof Observable))
throw new TypeError("illegal invocation");
if (typeof mapper !== "function")
throw new TypeError(`Parameter 1 is not of type 'Function'`);
// 1. Let sourceObservable be this.
let sourceObservable = this;
// 2. Let observable be a new Observable whose subscribe callback is an algorithm that takes a Subscriber subscriber and does the following:
// 3. Return observable.
return new Observable((subscriber) => {
// 2.1. Let idx be an unsigned long long, initially 0.
let idx = 0;
// 2.2. Let sourceObserver be a new internal observer, initialized as follows:
let sourceObserver = new InternalObserver({
next(value) {
let mappedValue;
// 1. Invoke mapper with the passed in value, and idx, and let mappedValue be the returned value.
try {
mappedValue = mapper(value, idx);
} catch (e) {
// 2. If an exception E was thrown, then run subscriber’s error() method, given E, and abort these steps.
subscriber.error(e);
return;
}
// 3. Increment idx.
idx += 1;
// 4. Run subscriber’s next() method, given mappedValue.
subscriber.next(mappedValue);
},
error(value) {
// Run subscriber’s error() method, given the passed in error.
subscriber.error(value);
},
complete() {
// Run subscriber’s complete() method.
subscriber.complete();
},
});
// 3. Let options be a new SubscribeOptions whose signal is subscriber’s subscription controller's signal.
let options = { signal: subscriber.signal };
// 4. Subscribe to sourceObservable given sourceObserver and options.
subscribeTo(sourceObservable, sourceObserver, options);
});
}
// https://wicg.github.io/observable/#dom-observable-inspect
inspect(inspectorUnion = {}) {
// 1: Let subscribe callback be a `VoidFunction`-or-null, initially null.
let subscribeCallback = null;
// 2: Let next callback be a `ObservableSubscriptionCallback`-or-null, initially null.
let nextCallback = null;
// 3: Let error callback be a `ObservableSubscriptionCallback`-or-null, initially null.
let errorCallback = null;
// 4: Let complete callback be a `VoidFunction`-or-null, initially null.
let completeCallback = null;
// 5: Let abort callback be a `ObservableInspectorAbortHandler`-or-null, initially null.
let abortCallback = null;
// 6: Process inspectorUnion as follows:
if (typeof inspectorUnion === "function") {
// If inspectorUnion is an `ObservableSubscriptionCallback`
// 6.1: Set next callback to inspectorUnion.
nextCallback = inspectorUnion;
} else if (inspectorUnion && typeof inspectorUnion === "object") {
// If inspectorUnion is an `ObservableInspector`
// 6.1: If `subscribe` exists in inspectorUnion, then set subscribe callback to it.
if ("subscribe" in inspectorUnion) subscribeCallback = inspectorUnion.subscribe;
// 6.2: If `next` exists in inspectorUnion, then set next callback to it.
if ("next" in inspectorUnion) nextCallback = inspectorUnion.next;
// 6.3: If `error` exists in inspectorUnion, then set error callback to it.
if ("error" in inspectorUnion) errorCallback = inspectorUnion.error;
// 6.4: If `complete` exists in inspectorUnion, then set complete callback to it.
if ("complete" in inspectorUnion) completeCallback = inspectorUnion.complete;
// 6.5: If `abort` exists in inspectorUnion, then set abort callback to it.
if ("abort" in inspectorUnion) abortCallback = inspectorUnion.abort;
}
// 7: Let sourceObservable be this.
const sourceObservable = this;
// 8: Let observable be a new `Observable` whose subscribe callback is an algorithm that takes a `Subscriber` subscriber and does the following:
return new Observable((subscriber) => {
// 8.1: If subscribe callback is not null, then invoke it.
if (subscribeCallback !== null) {
try {
subscribeCallback();
} catch (e) {
// If an exception E was thrown, then run subscriber’s `error()` method, given E, and abort these steps.
subscriber.error(e);
return;
}
}
// 8.2: If abort callback is not null, then add the following abort algorithm to subscriber’s subscription controller’s signal:
const abortCallbackWrapped = () => {
// 8.2.1: Invoke abort callback with subscriber’s subscription controller’s signal’s abort reason.
try {
if (abortCallback !== null) {
abortCallback(subscriber.signal.reason);
}
} catch (e) {
// If an exception E was thrown, then report the exception E.
reportError(e);
}
};
subscriber.signal.addEventListener("abort", abortCallbackWrapped, { once: true });
// 8.3: Let sourceObserver be a new internal observer, initialized as follows:
const sourceObserver = new InternalObserver({
next(value) {
// next steps
// 8.3.next.1: If next callback is not null, then invoke next callback with the passed in value.
if (nextCallback !== null) {
try {
nextCallback(value);
} catch (e) {
// If an exception E was thrown, then:
// 8.3.next.1.1: Remove abort callback from subscriber’s subscription controller’s signal.
subscriber.signal.removeEventListener("abort", abortCallbackWrapped);
// 8.3.next.1.2: Run subscriber’s `error()` method, given E, and abort these steps.
subscriber.error(e);
return;
}
}
// 8.3.next.2: Run subscriber’s `next()` method with the passed in value.
subscriber.next(value);
},
error(error) {
// error steps
// 8.3.error.1: Remove abort callback from subscriber’s subscription controller’s signal.
subscriber.signal.removeEventListener("abort", abortCallbackWrapped);
// 8.3.error.2: If error callback is not null, then invoke error callback given the passed in error.
if (errorCallback !== null) {
try {
errorCallback(error);
} catch (e) {
// If an exception E was thrown, then run subscriber’s `error()` method, given E, and abort these steps.
subscriber.error(e);
return;
}
}
// 8.3.error.3: Run subscriber’s `error()` method, given the passed in error.
subscriber.error(error);
},
complete() {
// complete steps
// 8.3.complete.1: Remove abort callback from subscriber’s subscription controller’s signal.
subscriber.signal.removeEventListener("abort", abortCallbackWrapped);
// 8.3.complete.2: If complete callback is not null, then invoke complete callback.
if (completeCallback !== null) {
try {
completeCallback();
} catch (e) {
// If an exception E was thrown, then run subscriber’s `error()` method, given E, and abort these steps.
subscriber.error(e);
return;
}
}
// 8.3.complete.3: Run subscriber’s `complete()` method.
subscriber.complete();
},
});
// 8.4: Let options be a new `SubscribeOptions` whose `signal` is subscriber’s subscription controller’s signal.
const options = { signal: subscriber.signal };
// 8.5: Subscribe to sourceObservable given sourceObserver and options.
subscribeTo(sourceObservable, sourceObserver, options);
});
}
// https://wicg.github.io/observable/#dom-observable-filter
filter(predicate) {
if (!(this instanceof Observable))
throw new TypeError("illegal invocation");
if (typeof predicate !== "function")
throw new TypeError(`Parameter 1 is not of type 'Function'`);
// 1. Let sourceObservable be this.
let sourceObservable = this;
// 2. Let observable be a new Observable whose subscribe callback is an algorithm that takes a Subscriber subscriber and does the following:
// 3. Return observable.
return new Observable((subscriber) => {
// 2.1. Let idx be an unsigned long long, initially 0.
let idx = 0;
// 2.2. Let sourceObserver be a new internal observer, initialized as follows:
let sourceObserver = new InternalObserver({
next(value) {
let matches = false;
// 1. Invoke mapper with the passed in value, and idx, and let mappedValue be the returned value.
try {
matches = predicate(value, idx);
} catch (e) {
// 2. If an exception E was thrown, then run subscriber’s error() method, given E, and abort these steps.
subscriber.error(e);
return;
}
// 3. Set idx to idx + 1.
idx += 1;
// 4. If matches is true, then run subscriber’s next() method, given value.
if (matches) {
subscriber.next(value);
}
},
error(value) {
// Run subscriber’s error() method, given the passed in error.
subscriber.error(value);
},
complete() {
// Run subscriber’s complete() method.
subscriber.complete();
},
});
// 3. Let options be a new SubscribeOptions whose signal is subscriber’s subscription controller's signal.
let options = { signal: subscriber.signal };
// 4. Subscribe to sourceObservable given sourceObserver and options.
subscribeTo(sourceObservable, sourceObserver, options);
});
}
// https://wicg.github.io/observable/#dom-observable-take
take(amount) {
if (!(this instanceof Observable))
throw new TypeError("illegal invocation");
// 1. Let sourceObservable be this.
let sourceObservable = this;
// 2. Let observable be a new Observable whose subscribe callback is an algorithm that takes a Subscriber subscriber and does the following:
// 3. Return observable.
return new Observable((subscriber) => {
// 2.1. Let remaining be amount.
let remaining = amount;
// 2.2. If remaining is 0, then run subscriber’s complete() method and abort these steps.
if (remaining == 0) return subscriber.complete();
// 2.3. Let sourceObserver be a new internal observer, initialized as follows:
let sourceObserver = new InternalObserver({
next(value) {
// 1. Run subscriber’s next() method with the passed in value.
subscriber.next(value);
// 2. Decrement remaining.
remaining -= 1;
// 3. If remaining is 0, then run subscriber’s complete() method.
if (remaining == 0) subscriber.complete();
},
error(value) {
// Run subscriber’s error() method, given the passed in error.
subscriber.error(value);
},
complete() {
// Run subscriber’s complete() method.
subscriber.complete();
},
});
// 3. Let options be a new SubscribeOptions whose signal is subscriber’s subscription controller's signal.
let options = { signal: subscriber.signal };
// 4. Subscribe to sourceObservable given sourceObserver and options.
subscribeTo(sourceObservable, sourceObserver, options);
});
}
// https://wicg.github.io/observable/#dom-observable-drop
drop(amount) {
if (!(this instanceof Observable))
throw new TypeError("illegal invocation");
// 1. Let sourceObservable be this.
let sourceObservable = this;
// 2. Let observable be a new Observable whose subscribe callback is an algorithm that takes a Subscriber subscriber and does the following:
// 3. Return observable.
return new Observable((subscriber) => {
// 2.1. Let remaining be amount.
let remaining = amount;
// 2.3. Let sourceObserver be a new internal observer, initialized as follows:
let sourceObserver = new InternalObserver({
next(value) {
// 1. If remaining is > 0, then decrement remaining and abort these steps.
if (remaining > 0) return (remaining -= 1);
// 2. Assert: remaining is 0.
if (remaining != 0) return;
// 3. Run subscriber’s next() method with the passed in value.
subscriber.next(value);
},
error(value) {
// Run subscriber’s error() method, given the passed in error.
subscriber.error(value);
},
complete() {
// Run subscriber’s complete() method.
subscriber.complete();
},