@adobe-commerce/event-bus 1.0.0-alpha1

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.
package/.eslintrc.js ADDED
@@ -0,0 +1,5 @@
1
+ const baseConfig = require('@adobe/elsie/config/eslint');
2
+
3
+ module.exports = {
4
+ ...baseConfig,
5
+ };
package/package.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "name": "@adobe-commerce/event-bus",
3
+ "version": "1.0.0-alpha1",
4
+ "license": "SEE LICENSE IN LICENSE.md",
5
+ "description": "An event bus for storefront packages to communicate in the browser",
6
+ "engines": {
7
+ "node": ">=16"
8
+ },
9
+ "main": "src/index.ts",
10
+ "scripts": {
11
+ "lint": "eslint",
12
+ "test": "jest",
13
+ "test:ci": "jest --config jest.config.js --passWithNoTests --coverage",
14
+ "build": " "
15
+ },
16
+ "dependencies": {
17
+ "@adobe/event-bus": "file:../../packages/event-bus"
18
+ }
19
+ }
@@ -0,0 +1,17 @@
1
+ export interface Events {
2
+ authenticated: boolean;
3
+ locale: string;
4
+ 'cart/data': Cart | null;
5
+ }
6
+
7
+ // Cart Domain
8
+ export interface Cart {
9
+ id: string;
10
+ totalQuantity: number;
11
+ items: Array<{
12
+ uid: string;
13
+ quantity: number;
14
+ sku: string;
15
+ name: string;
16
+ }>;
17
+ }
package/src/index.ts ADDED
@@ -0,0 +1,133 @@
1
+ import { Events } from './events-catalog';
2
+
3
+ export * from './events-catalog';
4
+
5
+ const hash = Date.now().toString(36).substring(2);
6
+
7
+ /**
8
+ * The `events` class provides static methods for event handling.
9
+ * It allows subscribing to events, emitting events, and enabling or disabling event logging.
10
+ *
11
+ * @class
12
+ * @extends {Events}
13
+ *
14
+ * @property {Function} on - Subscribes to an event.
15
+ * @property {Function} emit - Emits an event.
16
+ * @property {Function} enableLogger - Enables or disables event logging.
17
+ * @property {Function} lastPayload - Returns the last payload of the event.
18
+ */
19
+ export class events {
20
+ static _identifier = hash;
21
+
22
+ static _logger: BroadcastChannel | null = null;
23
+
24
+ static _lastEvent: { [key: string]: { payload: any } } = {};
25
+
26
+ /**
27
+ * Returns the last payload of the event.
28
+ * @param event – The event to get the last payload from.
29
+ * @returns – The last payload of the event.
30
+ */
31
+ static lastPayload(event: string) {
32
+ return this._lastEvent[event]?.payload;
33
+ }
34
+
35
+ /**
36
+ * Subscribes to an event.
37
+ * @param event - The event to subscribe to.
38
+ * @param handler - The event handler.
39
+ * @param options - Optional configuration for the event handler.
40
+ */
41
+ static on<K extends keyof Events>(
42
+ event: K,
43
+ handler: (payload: Events[K]) => void,
44
+ options?: { eager?: boolean }
45
+ ) {
46
+ if (typeof BroadcastChannel === 'undefined') {
47
+ return;
48
+ }
49
+
50
+ const subscriber = new BroadcastChannel('ElsieSDK/EventBus');
51
+
52
+ if (options?.eager) {
53
+ const lastEvent = this._lastEvent[event];
54
+
55
+ if (lastEvent) {
56
+ handler(lastEvent.payload);
57
+ }
58
+ }
59
+
60
+ subscriber.addEventListener('message', ({ data }) => {
61
+ // ignore events from other instances (only if identifier is set)
62
+ if (this._identifier && this._identifier !== data.identifier) return;
63
+
64
+ if (data.event === event) {
65
+ handler(data.payload);
66
+ }
67
+ });
68
+
69
+ // NOTE: disabled as it causes loading issues with "bfcache"
70
+ // unsubscribe if leaving page
71
+ // window.addEventListener('beforeunload', () => {
72
+ // subscriber.close();
73
+ // });
74
+
75
+ return {
76
+ off() {
77
+ subscriber.close();
78
+ },
79
+ };
80
+ }
81
+ /**
82
+ * Emits an event.
83
+ * @param event - The event to emit.
84
+ * @param payload - The event payload.
85
+ */
86
+
87
+ static emit<K extends keyof Events>(event: K, payload: Events[K]) {
88
+ if (typeof BroadcastChannel === 'undefined') {
89
+ return;
90
+ }
91
+
92
+ const publisher = new BroadcastChannel('ElsieSDK/EventBus');
93
+
94
+ publisher.postMessage({ event, identifier: this._identifier, payload });
95
+
96
+ this._lastEvent[event] = {
97
+ payload,
98
+ };
99
+
100
+ publisher.close();
101
+ }
102
+ /**
103
+ * Enables or disables event logging.
104
+ * @param enabled - Whether to enable or disable event logging.
105
+ */
106
+ static enableLogger(enabled: boolean) {
107
+ if (typeof BroadcastChannel === 'undefined') {
108
+ return;
109
+ }
110
+
111
+ // reset logger
112
+ this._logger?.close();
113
+ this._logger = null;
114
+
115
+ if (enabled === false) return;
116
+
117
+ // create new logger
118
+ this._logger = new BroadcastChannel('ElsieSDK/EventBus');
119
+
120
+ this._logger.addEventListener('message', ({ data }) => {
121
+ if (this._identifier && this._identifier !== data.identifier) return;
122
+ console.group(`📡 Event (${data.identifier}) ➡ ${data.event}`);
123
+ console.log(data.payload);
124
+ console.groupEnd();
125
+ });
126
+
127
+ // NOTE: disabled as it causes loading issues with "bfcache"
128
+ // unsubscribe if leaving page
129
+ // window.addEventListener('beforeunload', () => {
130
+ // this._logger?.close();
131
+ // });
132
+ }
133
+ }