json-crdt-repo
Version:
JSON CRDT server and syncing local-first browser client
46 lines (45 loc) • 1.27 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.pubsub = exports.PubSubBC = exports.PubSubM = void 0;
const rxjs_1 = require("rxjs");
class PubSubM {
constructor() {
this.bus$ = new rxjs_1.Subject();
}
pub(msg) {
this.bus$.next(msg);
}
end() {
this.bus$.complete();
}
}
exports.PubSubM = PubSubM;
class PubSubBC extends PubSubM {
constructor(bus) {
super();
this.bus = bus;
const ch = (this.ch = new BroadcastChannel(bus));
ch.onmessage = (e) => this.bus$.next(e.data);
}
pub(msg) {
this.ch.postMessage(msg);
super.pub(msg);
}
end() {
this.ch.close();
super.end();
}
}
exports.PubSubBC = PubSubBC;
/** Cache of global in-memory pubsub instances. */
const memoryCache = {};
/**
* Creates new cross-tab pubsub broadcast channel. Own messages are also received.
*
* @param bus The name of the broadcast bus, where messages will be published.
* @returns A PubSub instance that publishes messages to the specified bus.
*/
const pubsub = (bus) => typeof BroadcastChannel !== 'undefined'
? new PubSubBC(bus)
: memoryCache[bus] || (memoryCache[bus] = new PubSubM());
exports.pubsub = pubsub;