import Random from '../../primitives/Random.js';
import * as Utils from '../../primitives/utils.js';
import { WalletError } from '../WalletError.js';
import { InvokableWalletBase } from './InvokableWalletBase.js';
/**
 * Facilitates wallet operations over cross-document messaging.
 */
export default class XDMSubstrate extends InvokableWalletBase {
    domain;
    constructor(domain = '*') {
        super();
        if (typeof globalThis.window !== 'object') {
            throw new TypeError('The XDM substrate requires a global window object.');
        }
        if (typeof globalThis.window.postMessage !== 'function') {
            throw new TypeError('The window object does not seem to support postMessage calls.');
        }
        this.domain = domain;
    }
    async invoke(call, args) {
        return await new Promise((resolve, reject) => {
            const id = Utils.toBase64(Random(12));
            const listener = (e) => {
                if (e.data.type !== 'CWI' ||
                    !e.isTrusted ||
                    e.data.id !== id ||
                    e.data.isInvocation === true) {
                    return;
                }
                if (typeof window.removeEventListener === 'function') {
                    window.removeEventListener('message', listener);
                }
                if (e.data.status === 'error') {
                    const err = new WalletError(e.data.description, e.data.code);
                    reject(err);
                }
                else {
                    resolve(e.data.result);
                }
            };
            window.addEventListener('message', listener);
            window.parent.postMessage({
                type: 'CWI',
                isInvocation: true,
                id,
                call,
                args
            }, this.domain);
        });
    }
}
//# sourceMappingURL=XDM.js.map