@roots/bud-client
Version:
Client scripts for @roots/bud
69 lines (68 loc) • 2.06 kB
JavaScript
export const injectEvents = (eventSource) => {
/**
* EventSource wrapper
*
* @remarks
* wraps EventSource in a function to allow for
* mocking in tests
*/
return class Events extends eventSource {
/**
* Singleton constructor
*
*/
static make(options) {
if (typeof window.bud.hmr[options.name] === `undefined`)
Object.assign(window.bud.hmr, {
[options.name]: new Events(options),
});
return window.bud.hmr[options.name];
}
/**
* Class constructor
*
* @remarks
* Singleton interface, so this is private.
*
*/
constructor(options) {
super(options.path);
this.options = options;
/**
* Registered listeners
*/
this.listeners = new Set();
/**
* EventSource `onmessage` handler
*/
this.onmessage = async function (payload) {
if (!payload?.data || payload.data == `\uD83D\uDC93`) {
return;
}
try {
const data = JSON.parse(payload.data);
if (!data)
return;
await Promise.all([...this.listeners].map(async (listener) => {
return await listener(data);
}));
}
catch (ex) { }
};
/**
* EventSource `onopen` handler
*/
this.onopen = function () { };
this.onopen = this.onopen.bind(this);
this.onmessage = this.onmessage.bind(this);
this.addListener = this.addListener.bind(this);
}
/**
* EventSource `addMessageListener` handler
*/
addListener(listener) {
this.listeners.add(listener);
return this;
}
};
};