2023-03-14 13:18:55 +00:00
|
|
|
/**
|
|
|
|
* Copyright (c) HashiCorp, Inc.
|
2023-08-11 13:12:13 +00:00
|
|
|
* SPDX-License-Identifier: BUSL-1.1
|
2023-03-14 13:18:55 +00:00
|
|
|
*/
|
|
|
|
|
2022-09-15 08:43:17 +00:00
|
|
|
export default function (EventTarget, P = Promise) {
|
|
|
|
const handler = function (e) {
|
2020-03-19 10:28:21 +00:00
|
|
|
// e is undefined on the opening call
|
|
|
|
if (typeof e === 'undefined' || e.key === this.configuration.key) {
|
|
|
|
if (this.readyState === 1) {
|
|
|
|
const res = this.source(this.configuration);
|
2022-09-15 08:43:17 +00:00
|
|
|
P.resolve(res).then((data) => {
|
2020-03-19 10:28:21 +00:00
|
|
|
this.configuration.cursor++;
|
|
|
|
this._currentEvent = { type: 'message', data: data };
|
|
|
|
this.dispatchEvent({ type: 'message', data: data });
|
|
|
|
});
|
|
|
|
}
|
2019-02-21 10:36:15 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
return class extends EventTarget {
|
|
|
|
constructor(cb, configuration) {
|
|
|
|
super(...arguments);
|
2020-03-19 10:28:21 +00:00
|
|
|
this.readyState = 2;
|
|
|
|
this.target = configuration.target || window;
|
|
|
|
this.name = 'storage';
|
2019-02-21 10:36:15 +00:00
|
|
|
this.source = cb;
|
|
|
|
this.handler = handler.bind(this);
|
|
|
|
this.configuration = configuration;
|
|
|
|
this.configuration.cursor = 1;
|
2019-06-20 08:35:30 +00:00
|
|
|
this.open();
|
2019-02-21 10:36:15 +00:00
|
|
|
}
|
|
|
|
dispatchEvent() {
|
|
|
|
if (this.readyState === 1) {
|
|
|
|
return super.dispatchEvent(...arguments);
|
|
|
|
}
|
|
|
|
}
|
|
|
|
close() {
|
2020-03-19 10:28:21 +00:00
|
|
|
this.target.removeEventListener(this.name, this.handler);
|
2019-02-21 10:36:15 +00:00
|
|
|
this.readyState = 2;
|
|
|
|
}
|
|
|
|
getCurrentEvent() {
|
2020-03-19 10:28:21 +00:00
|
|
|
return this._currentEvent;
|
|
|
|
}
|
|
|
|
open() {
|
|
|
|
const state = this.readyState;
|
|
|
|
this.readyState = 1;
|
|
|
|
if (state !== 1) {
|
|
|
|
this.target.addEventListener(this.name, this.handler);
|
|
|
|
this.handler();
|
|
|
|
}
|
2019-02-21 10:36:15 +00:00
|
|
|
}
|
|
|
|
};
|
|
|
|
}
|