-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEventTrain.js
More file actions
1379 lines (1127 loc) · 51 KB
/
EventTrain.js
File metadata and controls
1379 lines (1127 loc) · 51 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @param win
* @param doc
* @param domRef
*/
const EventTrain = (function (
win,
doc,
undefined
) {
const EVENT_SOURCE_IFRAME = 'IFRAME';
const EVENT_SOURCE_PORTAL = 'PORTAL';
const EVENT_SOURCE_PARENT = 'PARENT';
const EVENT_STATUS_LOADING = 'LOADING';
const EVENT_STATUS_FAILED = 'FAILED';
const EVENT_STATUS_IDLE = 'IDLE';
const DOM_EXCEPTION_SAME_ORIGIN = 'SecurityError';
const CODE_DOM_EXCEPTION_SAME_ORIGIN = 18;
const LogLevel = {
TRACE: 'trace',
ERROR: 'error',
WARN: 'warn',
LOG: 'log',
ALL: 'all',
}
const Exposed_Targets = {
publish: 'publish',
publishStatus: 'publishStatus',
subscribe: 'subscribe',
subscribeStatus: 'subscribeStatus',
unsubscribe: 'unsubscribe',
unsubscribeStatus: 'unsubscribeStatus',
unsubscribeAll: 'unsubscribeAll',
registerIFrameSelectors: 'registerIFrameSelectors',
registerPublicEvents: 'registerPublicEvents',
registerPrivateEvents: 'registerPrivateEvents',
getRegisteredIframeSelectors: 'getRegisteredIframeSelectors',
activities: 'activities',
createWagonInstance: 'createWagonInstance'
}
const wagons = [];
const $console = {
_: (level, target, ...data) => {
if (target && level) {
const targetedLevel = logging.inspectLogLevelByTarget(target);
if (targetedLevel && targetedLevel.includes(LogLevel.ALL)) {
console[LogLevel.ALL === level ? LogLevel.LOG : level](...data);
} else if (targetedLevel && targetedLevel.includes(level)) {
console[level](...data);
}
}
},
log: (target, ...data) => {
$console._(LogLevel.LOG, target, data);
},
error: (target, data) => {
$console._(LogLevel.ERROR, target, ...data);
},
warn: (target, ...data) => {
$console._(LogLevel.WARN, target, ...data);
},
trace: (target, ...data) => {
$console._(LogLevel.TRACE, target, ...data);
},
all: (target, ...data) => {
$console._(LogLevel.ALL, target, ...data);
},
groupCollapsed: (target, level, ...data) => {
console.groupCollapsed(data && data[0] ? data[0] : '');
$console._(level, target, ...data);
},
groupEnd: () => {
console.groupEnd();
},
};
const $utils = {
isIframe: () => {
return window.location !== window.parent.location;
},
convertToArray: (items) => {
if (items) {
if (Array.isArray(items)) return items;
else return [items];
}
return [];
},
createSet: (existingArray, newArray) => {
return new Set(
[
...Array.from(existingArray),
...$utils.convertToArray(newArray),
].filter((e) => e)
);
},
/***
* generate timestamp in specific format
* @return (string}
*/
getTimestamp: () => {
return new Date().toLocaleString();
},
now: () => {
return new Date().getTime();
},
hash: (name) => {
return (
btoa(Math.random().toString(36)).slice(-7, -2) +
btoa((+new Date()).toString(36)).slice(-7, -2) +
btoa(name).slice(-7, -2)
);
},
};
const activityTracker = (() => {
const tracker = [];
const post = (activityInfo) => {
const now = $utils.now()
tracker.push({timestamp: now, ...activityInfo});
};
return {
post,
showAll: () => {
return tracker.sort((former, later) => former.timestamp - later.timestamp
);
},
}
})();
/**
* LOG level can be defined for each internal function ?? just for troubleshooting purpose
* @type {{inspectLogLevelByTarget: (function(*)), inspectLogLevel: (function(): ()), changeLogLevel: changeLogLevel}}
*/
const logging = (() => {
const logLevelByTargets = {};
const inspectLogLevel = () => logLevelByTargets;
const inspectLogLevelByTarget = (target) => {
return logLevelByTargets[target] ?? undefined;
};
const changeLogLevel = (amendLogLevelByTarget) => {
Object.assign(logLevelByTargets, amendLogLevelByTarget);
};
const exposedTargetsLogLevel = {
[Exposed_Targets.publish]: [],
[Exposed_Targets.publishStatus]: [],
[Exposed_Targets.subscribe]: [],
[Exposed_Targets.subscribeStatus]: [],
[Exposed_Targets.unsubscribe]: [],
[Exposed_Targets.unsubscribeStatus]: [],
[Exposed_Targets.unsubscribeAll]: [],
[Exposed_Targets.registerIFrameSelectors]: [],
[Exposed_Targets.registerPublicEvents]: [],
[Exposed_Targets.registerPrivateEvents]: [],
[Exposed_Targets.getRegisteredIframeSelectors]: [],
[Exposed_Targets.activities]: [],
[Exposed_Targets.createWagonInstance]: [LogLevel.ERROR, LogLevel.WARN],
}
changeLogLevel(exposedTargetsLogLevel);
return {
changeLogLevel,
inspectLogLevel,
inspectLogLevelByTarget,
}
})();
const subscribers = (() => {
const targetedName = 'subscribers';
logging.changeLogLevel({[targetedName]: [LogLevel.ERROR, LogLevel.WARN]});
let subscribersCollection = []; // track all subscriptions
const assign = (updatedCollection) => {
subscribersCollection = updatedCollection;
};
const clone = () => subscribersCollection.slice();
const filter = (expression) => {
return subscribersCollection.filter((subscriber) =>
expression(subscriber.eventName)
);
};
/**
* common pattern to push to subscribers list to avoid redundancy and mistakes
* @param eventName
* @param callBack
*/
const push = (eventName, callBack) => {
subscribersCollection.push({
eventName,
callBack,
});
};
/**
* Find matched subscribers using event name
* @param eventName
* @return {(function(): void)|*|*[]}
*/
const fetchByEventName = (eventName) => {
let matchedSubscribers = null;
const callbackCollection = [];
try {
// Todo wildcard match
$console.all(
targetedName,
`all subscribers : ${subscribersCollection}`
);
matchedSubscribers = filter((subscribedEventName) => subscribedEventName === eventName
);
if (matchedSubscribers && Array.isArray(matchedSubscribers) && matchedSubscribers.length > 0) {
matchedSubscribers.forEach((subscriber) => {
callbackCollection.push(subscriber.callBack);
});
}
// Todo condition check for wildcards
$console.log(targetedName, `callback function count for $(eventName} : ${callbackCollection.length}`);
return callbackCollection;
} catch (e) {
return () => {
$console.error(targetedName, 'ERROR finding matched subscribed callbacks :');
};
}
};
/**
* It'Il execute all the matched events using data from event
* @param event
*/
const executing = (event) => {
$console.log(targetedName, 'executing all callbacks ', event);
// Todo proper check based on event/payload structure
if (event?.data?.detail) {
$console.all(
targetedName,
'pushing details at event level from event.data',
event
);
event.detail = event?.data?.detail;
}
if (event?.detail) {
const {eventName} = event?.detail;
// Todo :: extensive check for Private, Public and default event register
/** private event shall be based on dom ref ?? */
const eventNames = eventsInventory.check(eventName, 'callback');
eventNames.forEach((_eventName) => {
fetchByEventName(_eventName)?.forEach((callBack) => {
$console.log(
targetedName,
`exe callbacks by event name : ${_eventName}`
);
callBack(event);
});
});
}
};
return {
push,
assign,
clone,
filter,
executing,
}
})();
// ToDo probably merge returned object with passed params
const processors = (() => {
const targetedName = 'processors';
logging.changeLogLevel({[targetedName]: [LogLevel.ERROR, LogLevel.WARN]});
const Processor_Targets = {
default: 'default',
publish: 'publish',
publishStatus: 'publishStatus',
subscribe: 'subscribe',
subscribeStatus: 'subscribeStatus',
unsubscribe: 'unsubscribe',
unsubscribeStatus: 'unsubscribeStatus',
unsubscribeAll: 'unsubscribe All',
};
const Processor_Targets_Defs = {
[Processor_Targets.default]: undefined,
[Processor_Targets.publish]: undefined,
[Processor_Targets.publishStatus]: undefined,
[Processor_Targets.subscribe]: undefined,
[Processor_Targets.subscribeStatus]: undefined,
[Processor_Targets.unsubscribe]: undefined,
[Processor_Targets.unsubscribeStatus]: undefined,
[Processor_Targets.unsubscribeAll]: undefined,
};
/**
* will execute in the very beginning of each exposed function. like LOG tracing or some condition check
* @type {{"[Exposed_Targets.default]": *, [Exposed_Targets.publish]": *, [Exposed_Targets.publishStatus]": *, "[Exposed_Targets.unsubscribeAll]": *, "[Exposed_Targets.unsubscribeStatus]": *, "[Exposed_Targets.unsubscribe]": *, "[Exposed_Targets.subscribe]": *, "[Exposed_Targets.subscribeStatus]": *,}}
*/
const preProcessors = {...Processor_Targets_Defs};
/**
* will execute at the end of each exposed function. like LOG tracing or some condition check
* @type {{"[Exposed_Targets.default]": *, [Exposed_Targets.publish]": *, [Exposed_Targets.publishStatus]": *, "[Exposed_Targets.unsubscribeAll]": *, "[Exposed_Targets.unsubscribeStatus]": *, "[Exposed_Targets.unsubscribe]": *, "[Exposed_Targets.subscribe]": *, "[Exposed_Targets.subscribeStatus]": *,}}
*/
const postProcessors = {...Processor_Targets_Defs};
const getProcessorTargets = () => Processor_Targets;
const isOverridingProcessor = (existingProcessors, newProcessors) => {
const newProcessorsTargets = Object.keys(newProcessors);
const definedExistingProcessors = Object.keys(existingProcessors).filter(
(target) =>
existingProcessors[target] && newProcessorsTargets.includes(target)
)
return definedExistingProcessors && definedExistingProcessors.length > 0;
};
const executePreProcessor = (target, ...args) => {
$console.log(targetedName, `${targetedName} Executing Pre processor for [${target}]`);
$console.all(targetedName, `Pre processor args passed for ${target} : `, {...args});
return preProcessors[target]
? preProcessors[target](...args)
: preProcessors[Exposed_Targets.default]
? preProcessors[Exposed_Targets.default](...args)
: [...args];
};
const executePostProcessor = (target, ...args) => {
$console.log(targetedName, `${targetedName} Executing Post processor for [${target}]`);
$console.all(targetedName, `Post processor args passed for ${target} : `, {...args});
return postProcessors[target]
? postProcessors[target](...args)
: postProcessors[Exposed_Targets.default]
? postProcessors[Exposed_Targets.default](...args)
: [...args];
};
const addPreProcessors = (_preProcessors) => {
$console.all(targetedName, 'adding pre processor');
const isPreProcessorOverriding = isOverridingProcessor(preProcessors, _preProcessors);
if (isPreProcessorOverriding)
$console.warn(targetedName, 'be careful while overriding the pre processors');
Object.assign(preProcessors, _preProcessors);
};
const addPostProcessors = (_postProcessors) => {
$console.all(targetedName, 'adding post processor');
const isPostProcessorOverriding = isOverridingProcessor(postProcessors, _postProcessors);
if (isPostProcessorOverriding)
$console.warn(targetedName, 'be careful while overriding the post processors');
Object.assign(postProcessors, _postProcessors);
};
return {
getProcessorTargets,
executePreProcessor,
executePostProcessor,
addPreProcessors,
addPostProcessors,
};
})();
// ToDo => pattern check =› iFrame-Selectors
// region{scope}-appname{,appType}-section-iFramed
const iframeInventory = (() => {
const targetedName = 'iframeInventory';
logging.changeLogLevel({[targetedName]: [LogLevel.ERROR, LogLevel.WARN]});
let selectors = [];
const assign = (updatedCollection) => {
selectors = updatedCollection;
};
const clone = () => selectors.slice();
const merge = (addCollection) => {
return [...clone(), $utils.convertToArray(addCollection)];
};
const fetch = () => [...selectors];
const registerSelectors = (addOnSelectors) => {
$console.log(targetedName, 'registering frame selectors :', addOnSelectors);
activityTracker.post({
iframeSelectors: addOnSelectors,
invokedBy: targetedName,
source: EVENT_SOURCE_PORTAL,
});
assign(Array.from($utils.create.Set(merge(addOnSelectors))));
$console.all(targetedNarne, 'registered iframe selectors : ', fetch());
};
registerSelectors([
'global-micro-page-iFramed',
'global-macro-page-Framed',
]);
return {
fetch,
registerSelectors,
}
// EOC for iframeInventory
})();
// Todo => pattern && Dupe =› eventName
// region/ apname/section/action/
const eventsInventory = (() => {
const targetedName = 'eventsInventory';
logging.changeLogLevel({[targetedName]: [LogLevel.ERROR, LogLevel.WARN]});
const delimiter = ['/', '-', '.'] // ToDo use delimiter to validate the pattern
// scope{,region}/appname{,appType}/section/action/
const defaultEventNames = [
'global/web/error/generic',
'global/web/error/404',
'global/web/resource/unavailable',
'global/system/service/unavailable',
'global/system/access/unauthorized',
'global/system/access/denied',
'global/system/status/offline',
'global/system/status/online',
'global/module/load-status/init',
'global/module/load-status/success',
'global/module/load-status/error',
'global/system/event/init',
'global/system/iframe/init',
];
let defaultRegister = [];
let publicRegister = []; // exposed event by MFE, global scoped
let privateRegister = []; // specific for MFE, local scoped // ToDo bind them to Dom Ref MFE-ID
const obfuscatedRegister = {};
const hashingEventName = (events) => {
const unHashedEventNames = events.filter(
(_eventName) => !obfuscatedRegister[_eventName]);
unHashedEventNames.forEach((_eventName) => {
obfuscatedRegister[_eventName] = $utils.hash(_eventName);
});
};
const findHash = (eventName) => {
if (privateRegister.includes(eventName)) {
if (obfuscatedRegister[eventName]) return obfuscatedRegister[eventName]
$console.error(targetedName, 'not allowed to use private register out of apps scope -', eventName);
throw new Error(`globalAccessFault: event is not allowed the access outside it's scope : ${eventName}`);
return eventName
}
};
const findEventName = (hash) => {
const eventName = Object.keys(obfuscatedRegister).find(
(key) => obfuscatedRegister[key] === hash
);
if (eventName && privateRegister[eventName]) return eventName;
return hash;
}
const presentInOtherRegister = (newEvents, register) => {
const inOtherRegister = newEvents.filter((_eventName) =>
register.includes(_eventName)
);
return inOtherRegister && inOtherRegister.length > 0;
}
const fetchDefault = () => defaultRegister;
const fetchPublic = () => publicRegister;
const fetchPrivate = () => privateRegister;
const fetchEnlisted = () => [...fetchDefault(), ...fetchPublic()];
const enlistDefault = (defaultEvents) => {
defaultRegister = Array.from($utils.createSet(fetchDefault(), defaultEvents));
};
const enlistPublic = (publicEvents) => {
if (presentInOtherRegister(publicEvents, fetchPrivate())) {
throw new Error(`globalAccessFault: Multiple events aren't allowed to register`);
}
publicRegister = Array.from($utils.createSet(fetchPublic(), publicEvents));
$console.all(targetedName, 'public events enlisted', publicRegister);
};
const enlistPrivate = (privateEvents) => {
if (presentInOtherRegister(privateEvents, fetchPublic())) {
throw new Error(`globalAccessFault: Multiple events aren't allowed to register`);
}
privateRegister = Array.from($utils.createSet(fetchPrivate(), privateEvents));
hashingEventName(privateEvents);
$console.all(targetedName, 'private events enlisted');
}
// Todo :: check for private event
const isEventEnlisted = (eventName) => {
// Todo special check based on caller of subscriber for private
const isEnlisted =
fetchDefault().includes(eventName) ||
fetchPublic().includes(eventName) ||
fetchPrivate().includes(eventName);
$console.all(targetedName, `is event (${eventName}) enlisted :`, isEnlisted);
return isEnlisted;
}
/**
* Throw ERROR is Event Name not found in register
* @param eventName
* @param action
* @param publishStatus
*/
const check = (eventName, action, publishStatus) => {
const matchedEventNames = [];
if (isEventEnlisted(eventName)) {
if (publishStatus && typeof publishStatus === 'function') {
// ToDo => remove from here catch and publish status as part of preprocessor
publishStatus(eventName, EVENT_STATUS_FAILED);
$console.error(targetedName, `${action ? `${action}` : ''} event: %c${eventName}%c failed`, 'font-weight:bold;', 'font-weight:unset;');
throw new Error(`globalAccessFault: ${action ? `${action}` : ''} event not recognised`);
} else {
$console.log(targetedName, `${action ? `${action}` : ''} event: %c$(eventName)%c failed`, 'font-weight:bold;', 'font-weight:unset;');
return matchedEventNames;
}
}
/** 1. ToDo => event name mapping from hash */
/** 2. ToDo =› check for wildcard operation */
matchedEventNames.push(eventName);
$console.log(targetedName, 'inventory check successful');
$console.all(targetedName, 'all the matched event by inventor check:', matchedEventNames);
return matchedEventNames;
};
enlistDefault(defaultEventNames);
return {
fetchPublic,
fetchEnlisted,
enlistPublic,
enlistPrivate,
check,
isEventEnlisted,
findHash,
findEventName,
}
// EOC for Event Inventory
})();
const eventUtils = (() => {
const targetedName = "eventUtils";
logging.changeLogLevel({[targetedName]: [LogLevel.ERROR, LogLevel.WARN]});
/**
* Process to check if evenData passed as Function
*
then call function and return data from response
* @param eventData
* @return (*}
*/
const collectData = (eventData) => {
$console.all(targetedName, 'check to see if event Data passed as callback function or JS pbject');
let _eventData; // ToDo => check for promises as well
if (typeof eventData === 'function') {
_eventData = eventData();
} else _eventData = eventData;
return _eventData;
}
const createSyntheticEvent = (eventName, payload, timeStamp = $utils.getTimestamp(), eventSource = EVENT_SOURCE_PORTAL) => {
$console.all(targetedName, `creating synthetic event for ${eventName}`);
return new CustomEvent(eventName, {
bubbles: true, // bubbling to allow an event from a child element, to support an ancestor catching it (optionally, with data)
detail: {
eventName,
eventSource,
timeStamp,
payload: payload,
}
});
}
const createEventDetails = (source, eventDetails) => {
return {
detail: {
eventName: eventDetails?.eventName,
eventSource: source,
timeStamp: eventDetails?.timeStamp,
payload: eventDetails?.payload,
},
}
}
const dispatchingSyntheticOrPostingMessage = (elementRef, syntheticEvent, eventSource) => {
try {
elementRef.dispatchEvent(syntheticEvent);
$console.all(targetedName, `Event was dispatched`, syntheticEvent);
$console.log(targetedName, `Dispatched event => `, syntheticEvent?.eventName ?? '');
} catch (error) {
const {code, name} = error;
$console.warn(targetedName, `ERROR in Dispatching, Posting it !!`);
if (
CODE_DOM_EXCEPTION_SAME_ORIGIN === code ||
DOM_EXCEPTION_SAME_ORIGIN === name
) {
const eventDetails = syntheticEvent?.detail;
if (
eventDetails?.eventName &&
eventDetails?.eventName !== eventsInventory.findHash(eventDetails?.eventName)
)
throw new Error("globalAccessFault: We can't post private event to or from Iframe");
const forwardEventDetails = createEventDetails(eventSource, eventDetails);
elementRef.postMessage(forwardEventDetails, '*');
// Todo Need to adapt origin dynamically
$console.all(targetedName, `Event was posted :`, syntheticEvent);
$console.log(targetedName, `Posted event =>:`, syntheticEvent?.eventName ?? '');
}
}
};
return {
collectData,
createSyntheticEvent,
dispatchingSyntheticOrPostingMessage,
}
// EOC for Event Utils
})();
const iframeEventHandler = (() => {
const targetedName = 'iframeEventHandler';
logging.changeLogLevel({[targetedName]: [LogLevel.ERROR, LogLevel.WARN]});
const forwardingToParent = (syntheticEvent) => {
$console.all(targetedName, `Dispatch(ing) from Iframe to Parent :`, syntheticEvent);
activityTracker.post({
...syntheticEvent?.detail,
invokedBy: targetedName,
source: EVENT_SOURCE_IFRAME,
target: EVENT_SOURCE_PARENT,
});
eventUtils.dispatchingSyntheticOrPostingMessage(window.parent, syntheticEvent, EVENT_SOURCE_IFRAME);
$console.all(targetedName, `Dispatch(ed) from Iframe to Parent`, syntheticEvent);
};
const forwardingToIframe = (syntheticEvent) => {
$console.all(targetedName, `Dispatch(ing) to Iframe from Parent :`, syntheticEvent);
const iframes = document.querySelectorAll(iframeInventory.fetch().join(','));
if (iframes.length === 0)
$console.warn(targetedName, 'no matching frames found, follow guidelines for frame selectors pattern to use existing or register new selectors');
iframes.forEach(function (iframeElement) {
activityTracker.post({
...syntheticEvent?.detail,
invokedBy: targetedName,
source: EVENT_SOURCE_PARENT,
target: iframeElement.className
});
eventUtils.dispatchingSyntheticOrPostingMessage(iframeElement.contentWindow, syntheticEvent, EVENT_SOURCE_PARENT);
});
$console.all(targetedName, `Dispatch(ed) to Iframe from Parent`, syntheticEvent);
};
/**
* This helps to pass event between Iframe and parent in both directions
* @param syntheticEvent
*/
const forwardingToIframeOrParent = (syntheticEvent) => {
$console.groupCollapsed(targetedName, LogLevel.LOG, 'Event Forwarding', syntheticEvent);
if ($utils.isIframe()) {
$console.log(targetedName, `Forwarding from Iframe to Parent :`);
$console.groupEnd();
forwardingToParent(syntheticEvent);
} else {
$console.log(targetedName, `Forwarding from Parent to Iframe:`);
$console.groupEnd();
forwardingToIframe(syntheticEvent);
}
};
/**
* This helps to listen posted message event in both direction from Parent to frame and vice versa.
* Once event recognised at Parent or Iframe then matched registered subscribers get notified by executing all callbacks
*/
const addingMessageEventListener = () => {
$console.log(targetedName, 'adding message listener');
window.addEventListener('message', (event) => {
$console.all(targetedName, 'listening message event and executing all subscribers : ', event);
// Todo Source check as well
/**
* ToDo ?? should call publish internally instead of looking for callback
* Risk could be trapping into Infinite loop, if not handled properly
*/
subscribers.executing(event);
});
};
const forwardPublicEventsInventory = (source, publicEvents = undefined) => {
$console.log(targetedName, 'iframe event register forwarding', source);
const syntheticEvent = eventUtils.createSyntheticEvent('global/system/iframe/init', {
publicEvents: publicEvents ?? eventsInventory.fetchPublic(),
});
$console.all(targetedName, 'frame register forwarding event :', syntheticEvent);
activityTracker.post({...syntheticEvent?.detail, invokedBy: targetedName, source,});
forwardingToIframeOrParent(syntheticEvent);
};
return {
forwardingToIframeOrParent,
addingMessageEventListener,
forwardPublicEventsInventory,
}
// EOC for iframeEventHandler
})();
const iframeHandshaking = (() => {
const targetedName = 'iframeHandshaking';
logging.changeLogLevel({[targetedName]: [LogLevel.WARN, LogLevel.LOG]});
/**
* subscribe to Frame Init event
* @param source
* @param forwardPublicEventsInventory
* @private
*/
const subscribeIframeInitEvent = (source, forwardPublicEventsInventory = false) => {
$console.all(targetedName, 'subscribed frame init by : ', source);
exposed.subscribe('global/system/iframe/init', (event) => {
$console.log(targetedName, `${source} init subscribers executing`, event);
if (event?.detail &&
Object.prototype.hasOwnProperty.call(event?.detail, 'payload')) {
$console.all(targetedName, `${source} init event has payload :`, event?.detail?.payload);
const {publicEvents} = event?.detail?.payload;
activityTracker.post({...event?.detail, invokedBy: targetedName, source});
if (publicEvents) eventsInventory.enlistPublic(publicEvents);
$console.all(targetedName, `${source} init subscriber added public events to it's train`);
}
$console.log(targetedName, 'check to forward Iframe init event :', forwardPublicEventsInventory);
if (forwardPublicEventsInventory)
iframeEventHandler.forwardPublicEventsInventory(EVENT_SOURCE_PARENT);
});
};
/**
* Method to notify parent that Iframe train has loaded and parent acknowledges
* Iframe post message with its Public Events and Parent registers Iframe public events in its register
* and Parent acknowledges to Iframe by sending its Public events as well to Iframe
* @private
*/
const registerIframeTrainToParentTrain = () => {
if ($utils.isIframe()) {
$console.log(targetedName, 'frame registers to parent');
iframeEventHandler.forwardPublicEventsInventory(EVENT_SOURCE_IFRAME);
} else {
$console.log(targetedName, 'parent creating subscribes to register iframe');
subscribeIframeInitEvent(EVENT_SOURCE_PARENT, true);
}
};
return {
registerIframeTrainToParentTrain,
};
// EOC for iframeHandShaking
})();
const exposed = {
/**
* Event publish
* @param (string} eventName
* @param (object} eventData - configuration object with optional details
* @param storeEventData, default is true to save the value in Latent data-store to be used by later subscribed event
* @return no return value defined
* @throws an ERROR if no event registry name/key is found
*/
publish: (eventName, eventData = 0, storeEventData = true) => {
$console.log(Exposed_Targets.publish, 'synthetic publishing : ', eventName);
const [preProcessedEventName, preProcessedEventData] = processors.executePreProcessor(Exposed_Targets.publish, eventName, eventData);
$console.log(Exposed_Targets.publish, 'publish Loading status');
/** 1. publish Status for In-Progress*/
exposed.publishStatus(preProcessedEventName, EVENT_STATUS_LOADING);
$console.log(Exposed_Targets.publish, 'publish verification : ', preProcessedEventName);
/** 2. verify event, throw ERROR if not found */
const eventNames = eventsInventory.check(preProcessedEventName, 'published', exposed.publishStatus);
/** 3, create event timestamp */
const timeStamp = $utils.getTimestamp();
$console.log(Exposed_Targets.publish, 'check to for function or JS object ', preProcessedEventData);
/** 4. use eventData or call () to get eventData */
const _eventData = eventUtils.collectData(preProcessedEventData);
/** 5. create, dispatch and forward synthetic event for all matched events */
eventNames.forEach((_eventName) => {
/** 5.1 create synthetic event */
const syntheticEvent = eventUtils.createSyntheticEvent(
eventsInventory.findHash(_eventName),
_eventData,
timeStamp
);
/** 5.2. dispatch global event */
activityTracker.post({
...syntheticEvent?.detail,
invokedBy: Exposed_Targets.publish,
source: EVENT_SOURCE_PORTAL,
target: EVENT_SOURCE_PORTAL
});
eventUtils.dispatchingSyntheticOrPostingMessage(window.document, syntheticEvent);
// Todo event only bubble is we dispatch event using Dom Ref
/** 5.3. forward event to or from iframe */
iframeEventHandler.forwardingToIframeOrParent(syntheticEvent);
});
/** 6, publish Status for completion */
// publishStatus(eventName,EVENT_STATUS_IDLE);
$console.log(Exposed_Targets.publish, 'publish Idle status');
processors.executePostProcessor(Exposed_Targets.publish,
{eventName, preProcessedEventName},
{eventData, preProcessedEventData}
);
$console.log(Exposed_Targets.publish, 'synthetic published');
},
publishStatus: (eventName, status) => {
$console.log(Exposed_Targets.publishStatus, 'publish event($(eventName}) status :', status);
const [preProcessedEventName, preProcessedStatus] = processors.executePreProcessor(
Exposed_Targets.publishStatus,
eventName,
status
);
const statusEventName = `${preProcessedEventName}/status`.toString();
$console.log(Exposed_Targets.publishStatus, 'publish status verification :', statusEventName);
/**1. verify event, throw ERROR if not found */
const statusEventNames = eventsInventory.check(statusEventName, 'status-published');
/** 2. create, dispatch and forward Synthetic status event for all matched eventNames*/
statusEventNames.forEach((_statusEventName) => {
/** 2.1 create synthetic event*/
const syntheticEvent = eventUtils.createSyntheticEvent(
eventsInventory.findHash(_statusEventName),
{
status: preProcessedStatus,
}
);
/** 2.2 dispatch synthetic event*/
activityTracker.post({
...syntheticEvent?.detail,
invokedBy: Exposed_Targets.publishStatus,
source: EVENT_SOURCE_PORTAL,
target: EVENT_SOURCE_PORTAL,
});
eventUtils.dispatchingSyntheticOrPostingMessage(
window.document,
syntheticEvent
);
/** 2.3 forward to or from iframe*/
iframeEventHandler.forwardingToIframeOrParent(syntheticEvent);
});
processors.executePostProcessor(Exposed_Targets.publishStatus, {eventName, preProcessedEventName}, {
status,
preProcessedStatus
});
$console.log(Exposed_Targets.publishStatus, 'published status');
},
/**
* Event subscription
* @param (string} eventName
* @param (function} callBack - callback invoked when event is published
* @param lastPublishedData
* @throws an ERROR if event inventory check fails (eventsInventory.check}
*/
subscribe: (eventName, callBack, lastPublishedData = false) => {
$console.log(Exposed_Targets.subscribe, 'subscribing event: ', eventName);
const [preProcessedEventName, preProcessedCallback] = processors.executePreProcessor(
Exposed_Targets.subscribe,
eventName,
callBack
);
$console.log(Exposed_Targets.subscribe, 'subscribing event verification: ', preProcessedEventName);
/**1. verify event, throw ERROR if not found */
const eventNames = eventsInventory.check(preProcessedEventName, 'subscribed', exposed.publishStatus);
/** 2. subscribe for all matched events */
eventNames.forEach((_eventName) => {
const hash = eventsInventory.findHash(_eventName);
activityTracker.post({
event: hash,
invokedBy: Exposed_Targets.subscribe,
source: EVENT_SOURCE_PORTAL,
target: EVENT_SOURCE_PORTAL,
});
/** 2.1 add callback to subscribers' list */
subscribers.push(hash, preProcessedCallback);
$console.log(Exposed_Targets.subscribe, `subscribers added for : ${_eventName}`);