var _a, _b;
const safeParse = (text, reviver) => {
    try {
        return JSON.parse(text, reviver);
        // eslint-disable-next-line no-empty
    }
    catch (e) { }
};
/**
 * @see https://github.com/DnDBeyond/game-log/blob/main/packages/game-log-components/src/components/GameLogContextProvider/GameLogContextProvider.tsx#L184-L190
 */
const isMessage = (x) => !!x &&
    typeof x === 'object' &&
    'entityId' in x &&
    'entityType' in x &&
    'persist' in x &&
    'messageScope' in x &&
    'messageTarget' in x &&
    'data' in x;
const isProd = process.env.NODE_ENV === 'production' &&
    location.host === 'www.dndbeyond.com';
const postMessage = (message) => {
    window.parent.postMessage(message, isProd ? location.origin : '*');
    if (process.env.NODE_ENV === 'development') {
        console.log(`posting to feywild with message:\n${JSON.stringify(JSON.parse(message), null, 2)}`);
    }
};
/**
 * the character sheet loads in Feywild as an iframe with `?view=vtt`
 */
const urlSearchParams = new URLSearchParams(location.search);
export const isVttView = urlSearchParams.get('view') === 'vtt';
export const messageBrokerFacade = {
    gameId: (_a = urlSearchParams.get('gameId')) !== null && _a !== void 0 ? _a : '0',
    userId: (_b = urlSearchParams.get('userId')) !== null && _b !== void 0 ? _b : '0',
    source: '',
    connectUrl: '',
    getMessagesUrl: '',
    fetchHistory: () => Promise.resolve(),
    subscribe: (callback) => {
        const onMessage = ({ data, origin }) => {
            if ((isProd && origin !== location.origin) || typeof data !== 'string') {
                return;
            }
            const message = safeParse(data);
            if (!isMessage(message)) {
                return;
            }
            callback(message);
        };
        window.addEventListener('message', onMessage);
        return () => window.removeEventListener('message', onMessage);
    },
    dispatch: (partial) => postMessage(JSON.stringify(partial)),
};
//# sourceMappingURL=vttView.js.map