1 import { getSecondLevelDomain } from '@proton/shared/lib/helpers/url';
3 import type { CrossStorageMessage, ResponseMessage } from './interface';
4 import { getTestKeyValue, setTestKeyValue } from './support';
6 const createHost = <Message, MessageResponse>(handler: (message: Message) => Promise<MessageResponse>) => {
7 const isEmbedded = window.location !== window.parent.location;
8 const hostSecondLevelDomain = getSecondLevelDomain(window.location.hostname);
11 throw new Error('Window not embedded');
14 const postMessage = (message: CrossStorageMessage, origin: string) => {
15 return window.parent.postMessage(message, origin);
18 postMessage({ type: 'init', payload: { value: getTestKeyValue(window) } }, '*');
20 const reply = (origin: string, payload: ResponseMessage<MessageResponse>) => {
21 postMessage(payload, origin);
24 window.addEventListener('message', (event: MessageEvent<CrossStorageMessage>) => {
25 const { source, data, origin } = event;
27 source !== window.parent ||
28 getSecondLevelDomain(new URL(origin).hostname) !== hostSecondLevelDomain ||
29 data?.type !== 'message'
35 reply(origin, { id: data.id, type: 'response', status: 'success', payload: response });
48 export const initMainHost = () => {
49 setTestKeyValue(window);
52 export default createHost;