import { Inspector } from "./index.mjs";
import { CreateBuiltinFunction, CreateDataProperty, DefinePropertyOrThrow, Descriptor, OrdinaryObjectCreate, surroundingAgent, ThrowCompletion, skipDebugger, Value, } from '#self';
const consoleMethods = [
    'log',
    'debug',
    'info',
    'error',
    'warning',
    'dir',
    'dirxml',
    'table',
    'trace',
    'clear',
    'startGroup',
    'startGroupCollapsed',
    'endGroup',
    'assert',
    'profile',
    'profileEnd',
    'count',
    'timeEnd',
];
export function createConsole(realm, defaultBehaviour) {
    realm.scope(() => {
        const console = OrdinaryObjectCreate(realm.Intrinsics['%Object.prototype%']);
        skipDebugger(DefinePropertyOrThrow(realm.GlobalObject, Value('console'), Descriptor({
            Configurable: Value.true,
            Enumerable: Value.false,
            Writable: Value.true,
            Value: console,
        })));
        consoleMethods.forEach((method) => {
            const f = CreateBuiltinFunction(function* Console(args) {
                if (surroundingAgent.debugger_isPreviewing) {
                    return Value.undefined;
                }
                let completion;
                if (defaultBehaviour[method]) {
                    completion = defaultBehaviour[method](args);
                }
                else if (defaultBehaviour.default) {
                    completion = defaultBehaviour.default(method, args);
                }
                if (completion) {
                    if (typeof completion === 'object' && 'next' in completion) {
                        completion = yield* completion;
                    }
                    // Do not use Q(host) here. A host may return something invalid like ReturnCompletion.
                    if (completion instanceof ThrowCompletion) {
                        return completion;
                    }
                }
                if (realm.HostDefined.attachingInspector instanceof Inspector) {
                    realm.HostDefined.attachingInspector.console(realm, method, args);
                }
                return Value.undefined;
            }, 1, Value(method), []);
            skipDebugger(CreateDataProperty(console, Value(method), f));
        });
    });
}
//# sourceMappingURL=utils.mjs.map