UNPKG

7.88 kBJavaScriptView Raw
1"use strict";
2// Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3// SPDX-License-Identifier: Apache-2.0
4var __assign = (this && this.__assign) || function () {
5 __assign = Object.assign || function(t) {
6 for (var s, i = 1, n = arguments.length; i < n; i++) {
7 s = arguments[i];
8 for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p))
9 t[p] = s[p];
10 }
11 return t;
12 };
13 return __assign.apply(this, arguments);
14};
15var __read = (this && this.__read) || function (o, n) {
16 var m = typeof Symbol === "function" && o[Symbol.iterator];
17 if (!m) return o;
18 var i = m.call(o), r, ar = [], e;
19 try {
20 while ((n === void 0 || n-- > 0) && !(r = i.next()).done) ar.push(r.value);
21 }
22 catch (error) { e = { error: error }; }
23 finally {
24 try {
25 if (r && !r.done && (m = i["return"])) m.call(i);
26 }
27 finally { if (e) throw e.error; }
28 }
29 return ar;
30};
31var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) {
32 if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) {
33 if (ar || !(i in from)) {
34 if (!ar) ar = Array.prototype.slice.call(from, 0, i);
35 ar[i] = from[i];
36 }
37 }
38 return to.concat(ar || Array.prototype.slice.call(from));
39};
40Object.defineProperty(exports, "__esModule", { value: true });
41exports.Hub = exports.HubClass = void 0;
42var Logger_1 = require("./Logger");
43var logger = new Logger_1.ConsoleLogger('Hub');
44var AMPLIFY_SYMBOL = (typeof Symbol !== 'undefined' && typeof Symbol.for === 'function'
45 ? Symbol.for('amplify_default')
46 : '@@amplify_default');
47function isLegacyCallback(callback) {
48 return callback.onHubCapsule !== undefined;
49}
50var HubClass = /** @class */ (function () {
51 function HubClass(name) {
52 this.listeners = [];
53 this.patterns = [];
54 this.protectedChannels = [
55 'core',
56 'auth',
57 'api',
58 'analytics',
59 'interactions',
60 'pubsub',
61 'storage',
62 'ui',
63 'xr',
64 ];
65 this.name = name;
66 }
67 /**
68 * Used internally to remove a Hub listener.
69 *
70 * @remarks
71 * This private method is for internal use only. Instead of calling Hub.remove, call the result of Hub.listen.
72 */
73 HubClass.prototype._remove = function (channel, listener) {
74 if (channel instanceof RegExp) {
75 var pattern_1 = this.patterns.find(function (_a) {
76 var pattern = _a.pattern;
77 return pattern.source === channel.source;
78 });
79 if (!pattern_1) {
80 logger.warn("No listeners for ".concat(channel));
81 return;
82 }
83 this.patterns = __spreadArray([], __read(this.patterns.filter(function (x) { return x !== pattern_1; })), false);
84 }
85 else {
86 var holder = this.listeners[channel];
87 if (!holder) {
88 logger.warn("No listeners for ".concat(channel));
89 return;
90 }
91 this.listeners[channel] = __spreadArray([], __read(holder.filter(function (_a) {
92 var callback = _a.callback;
93 return callback !== listener;
94 })), false);
95 }
96 };
97 /**
98 * @deprecated Instead of calling Hub.remove, call the result of Hub.listen.
99 */
100 HubClass.prototype.remove = function (channel, listener) {
101 this._remove(channel, listener);
102 };
103 /**
104 * Used to send a Hub event.
105 *
106 * @param channel - The channel on which the event will be broadcast
107 * @param payload - The HubPayload
108 * @param source - The source of the event; defaults to ''
109 * @param ampSymbol - Symbol used to determine if the event is dispatched internally on a protected channel
110 *
111 */
112 HubClass.prototype.dispatch = function (channel, payload, source, ampSymbol) {
113 if (source === void 0) { source = ''; }
114 if (this.protectedChannels.indexOf(channel) > -1) {
115 var hasAccess = ampSymbol === AMPLIFY_SYMBOL;
116 if (!hasAccess) {
117 logger.warn("WARNING: ".concat(channel, " is protected and dispatching on it can have unintended consequences"));
118 }
119 }
120 var capsule = {
121 channel: channel,
122 payload: __assign({}, payload),
123 source: source,
124 patternInfo: [],
125 };
126 try {
127 this._toListeners(capsule);
128 }
129 catch (e) {
130 logger.error(e);
131 }
132 };
133 /**
134 * Used to listen for Hub events.
135 *
136 * @param channel - The channel on which to listen
137 * @param callback - The callback to execute when an event is received on the specified channel
138 * @param listenerName - The name of the listener; defaults to 'noname'
139 * @returns A function which can be called to cancel the listener.
140 *
141 */
142 HubClass.prototype.listen = function (channel, callback, listenerName) {
143 var _this = this;
144 if (listenerName === void 0) { listenerName = 'noname'; }
145 var cb;
146 // Check for legacy onHubCapsule callback for backwards compatability
147 if (isLegacyCallback(callback)) {
148 logger.warn("WARNING onHubCapsule is Deprecated. Please pass in a callback.");
149 cb = callback.onHubCapsule.bind(callback);
150 }
151 else if (typeof callback !== 'function') {
152 throw new Error('No callback supplied to Hub');
153 }
154 else {
155 cb = callback;
156 }
157 if (channel instanceof RegExp) {
158 this.patterns.push({
159 pattern: channel,
160 callback: cb,
161 });
162 }
163 else {
164 var holder = this.listeners[channel];
165 if (!holder) {
166 holder = [];
167 this.listeners[channel] = holder;
168 }
169 holder.push({
170 name: listenerName,
171 callback: cb,
172 });
173 }
174 return function () {
175 _this._remove(channel, cb);
176 };
177 };
178 HubClass.prototype._toListeners = function (capsule) {
179 var channel = capsule.channel, payload = capsule.payload;
180 var holder = this.listeners[channel];
181 if (holder) {
182 holder.forEach(function (listener) {
183 logger.debug("Dispatching to ".concat(channel, " with "), payload);
184 try {
185 listener.callback(capsule);
186 }
187 catch (e) {
188 logger.error(e);
189 }
190 });
191 }
192 if (this.patterns.length > 0) {
193 if (!payload.message) {
194 logger.warn("Cannot perform pattern matching without a message key");
195 return;
196 }
197 var payloadStr_1 = payload.message;
198 this.patterns.forEach(function (pattern) {
199 var match = payloadStr_1.match(pattern.pattern);
200 if (match) {
201 var _a = __read(match), groups = _a.slice(1);
202 var dispatchingCapsule = __assign(__assign({}, capsule), { patternInfo: groups });
203 try {
204 pattern.callback(dispatchingCapsule);
205 }
206 catch (e) {
207 logger.error(e);
208 }
209 }
210 });
211 }
212 };
213 return HubClass;
214}());
215exports.HubClass = HubClass;
216/*We export a __default__ instance of HubClass to use it as a
217pseudo Singleton for the main messaging bus, however you can still create
218your own instance of HubClass() for a separate "private bus" of events.*/
219exports.Hub = new HubClass('__default__');