"use strict";
var __webpack_require__ = {};
(()=>{
    __webpack_require__.n = (module)=>{
        var getter = module && module.__esModule ? ()=>module['default'] : ()=>module;
        __webpack_require__.d(getter, {
            a: getter
        });
        return getter;
    };
})();
(()=>{
    __webpack_require__.d = (exports1, definition)=>{
        for(var key in definition)if (__webpack_require__.o(definition, key) && !__webpack_require__.o(exports1, key)) Object.defineProperty(exports1, key, {
            enumerable: true,
            get: definition[key]
        });
    };
})();
(()=>{
    __webpack_require__.o = (obj, prop)=>Object.prototype.hasOwnProperty.call(obj, prop);
})();
(()=>{
    __webpack_require__.r = (exports1)=>{
        if ('undefined' != typeof Symbol && Symbol.toStringTag) Object.defineProperty(exports1, Symbol.toStringTag, {
            value: 'Module'
        });
        Object.defineProperty(exports1, '__esModule', {
            value: true
        });
    };
})();
var __webpack_exports__ = {};
__webpack_require__.r(__webpack_exports__);
__webpack_require__.d(__webpack_exports__, {
    playgroundForAgentFactory: ()=>playgroundForAgentFactory,
    playgroundForAgent: ()=>playgroundForAgent
});
const external_node_child_process_namespaceObject = require("node:child_process");
const constants_namespaceObject = require("@midscene/shared/constants");
const external_cors_namespaceObject = require("cors");
var external_cors_default = /*#__PURE__*/ __webpack_require__.n(external_cors_namespaceObject);
const external_server_js_namespaceObject = require("./server.js");
var external_server_js_default = /*#__PURE__*/ __webpack_require__.n(external_server_js_namespaceObject);
const LOOPBACK_HOSTS = new Set([
    'localhost',
    '127.0.0.1',
    '::1',
    '[::1]'
]);
function isLoopbackOrigin(origin) {
    if (!origin) return true;
    try {
        const url = new URL(origin);
        return LOOPBACK_HOSTS.has(url.hostname);
    } catch  {
        return false;
    }
}
function createDefaultCorsOptions() {
    return {
        origin (origin, callback) {
            callback(null, isLoopbackOrigin(origin));
        },
        credentials: true
    };
}
function createPlaygroundLauncher(agentOrFactory) {
    return {
        async launch (options = {}) {
            const { port = constants_namespaceObject.PLAYGROUND_SERVER_PORT, openBrowser = true, browserCommand, verbose = true, id, enableCors = false, staticPath, configureServer, corsOptions = createDefaultCorsOptions() } = options;
            if ('function' != typeof agentOrFactory && !agentOrFactory.interface) throw new Error('Agent must have an interface property');
            if (verbose) {
                console.log('🚀 Starting Midscene Playground...');
                if ('function' == typeof agentOrFactory) console.log('📱 Agent: factory');
                else {
                    console.log(`📱 Agent: ${agentOrFactory.constructor.name}`);
                    console.log(`🖥️ Page: ${agentOrFactory.interface.constructor.name}`);
                }
                console.log(`🌐 Port: ${port}`);
                if (staticPath) console.log(`📁 Static path: ${staticPath}`);
                if (enableCors) console.log('🔓 CORS enabled');
            }
            const server = new (external_server_js_default())(agentOrFactory, staticPath, id);
            if (enableCors) server.app.use(external_cors_default()(corsOptions));
            if (configureServer) await configureServer(server);
            const launchedServer = await server.launch(port);
            if (verbose) console.log(`✅ Playground server started on port ${port}`);
            const url = `http://127.0.0.1:${port}`;
            if (openBrowser) await openInBrowser(url, browserCommand, verbose);
            return {
                server: launchedServer,
                port,
                host: '127.0.0.1',
                close: async ()=>{
                    if (verbose) console.log('🛑 Shutting down Midscene Playground...');
                    try {
                        await launchedServer.close();
                        if (verbose) console.log('✅ Playground shutdown complete');
                    } catch (error) {
                        if (verbose) console.error('❌ Error during playground shutdown:', error);
                        throw error;
                    }
                }
            };
        }
    };
}
function playgroundForAgent(agent) {
    return createPlaygroundLauncher(agent);
}
function playgroundForAgentFactory(agentFactory) {
    return createPlaygroundLauncher(agentFactory);
}
async function openInBrowser(url, customCommand, verbose = true) {
    return new Promise((resolve, reject)=>{
        let command;
        let args;
        if (customCommand) {
            command = customCommand;
            args = [
                url
            ];
        } else switch(process.platform){
            case 'darwin':
                command = 'open';
                args = [
                    url
                ];
                break;
            case 'win32':
                command = 'start';
                args = [
                    '',
                    url
                ];
                break;
            default:
                command = 'xdg-open';
                args = [
                    url
                ];
                break;
        }
        if (verbose) console.log(`🌐 Opening browser: ${command} ${args.join(' ')}`);
        const child = (0, external_node_child_process_namespaceObject.spawn)(command, args, {
            detached: true,
            stdio: 'ignore'
        });
        child.on('error', (error)=>{
            if (verbose) {
                console.warn('⚠️  Failed to open browser automatically:', error.message);
                console.log(`🌐 Please open manually: ${url}`);
            }
            resolve();
        });
        child.on('close', ()=>{
            resolve();
        });
        child.unref();
    });
}
exports.playgroundForAgent = __webpack_exports__.playgroundForAgent;
exports.playgroundForAgentFactory = __webpack_exports__.playgroundForAgentFactory;
for(var __rspack_i in __webpack_exports__)if (-1 === [
    "playgroundForAgent",
    "playgroundForAgentFactory"
].indexOf(__rspack_i)) exports[__rspack_i] = __webpack_exports__[__rspack_i];
Object.defineProperty(exports, '__esModule', {
    value: true
});

//# sourceMappingURL=launcher.js.map