"use strict";
exports.ids = [
    "324"
];
exports.modules = {
    "./webpack/dev-server/index.ts" (__unused_rspack_module, __webpack_exports__, __webpack_require__) {
        __webpack_require__.d(__webpack_exports__, {
            devServer: ()=>dev_server_devServer
        });
        var external_fs_ = __webpack_require__("fs");
        var external_fs_default = /*#__PURE__*/ __webpack_require__.n(external_fs_);
        var external_path_ = __webpack_require__("path");
        var external_stream_ = __webpack_require__("stream");
        var core_ = __webpack_require__("@rspack/core");
        var dev_server_ = __webpack_require__("@rspack/dev-server");
        var external_webpack_merge_ = __webpack_require__("webpack-merge");
        var messages = __webpack_require__("./webpack/dev-server/messages.ts");
        var external_crypto_ = __webpack_require__("crypto");
        var external_net_ = __webpack_require__("net");
        var shared_utils = __webpack_require__("./webpack/plugin-browsers/browsers-lib/shared-utils.ts");
        function _define_property(obj, key, value) {
            if (key in obj) Object.defineProperty(obj, key, {
                value: value,
                enumerable: true,
                configurable: true,
                writable: true
            });
            else obj[key] = value;
            return obj;
        }
        class PortManager {
            async allocatePorts(_browser, _projectPath, requestedPort) {
                try {
                    const isValidRequested = 'number' == typeof requestedPort && requestedPort > 0 && requestedPort < 65536;
                    const base = isValidRequested ? requestedPort : this.basePort;
                    const port = await (0, shared_utils.aY)(base);
                    const webSocketPort = await (0, shared_utils.aY)(port + 1);
                    const instanceId = external_crypto_.randomBytes(8).toString('hex');
                    this.currentInstance = {
                        instanceId,
                        port,
                        webSocketPort
                    };
                    return {
                        port,
                        webSocketPort,
                        instanceId
                    };
                } catch (error) {
                    throw error;
                }
            }
            getCurrentInstance() {
                return this.currentInstance;
            }
            async updateExtensionId(extensionId) {
                if (this.currentInstance) this.currentInstance.extensionId = extensionId;
            }
            async terminateCurrentInstance() {
                this.currentInstance = null;
            }
            getPortInfo(allocation) {
                return `Port: ${allocation.port}, WebSocket: ${allocation.webSocketPort}, Instance: ${allocation.instanceId.slice(0, 8)}`;
            }
            async isPortInUse(port) {
                return new Promise((resolve)=>{
                    const server = external_net_.createServer();
                    server.once('error', ()=>resolve(true));
                    server.once('listening', ()=>{
                        server.close(()=>resolve(false));
                    });
                    server.listen(port, '127.0.0.1');
                });
            }
            async getRunningInstances() {
                return this.currentInstance ? [
                    this.currentInstance
                ] : [];
            }
            async getStats() {
                return {
                    total: this.currentInstance ? 1 : 0,
                    running: this.currentInstance ? 1 : 0,
                    terminated: 0,
                    error: 0
                };
            }
            constructor(_browser, _projectPath, basePort = 8080){
                _define_property(this, "basePort", void 0);
                _define_property(this, "currentInstance", null);
                this.basePort = basePort;
            }
        }
        function hasDependency(projectPath, dependency) {
            const findNearestPackageJsonDirectory = (startPath)=>{
                let currentDirectory = startPath;
                const maxDepth = 4;
                for(let i = 0; i < maxDepth; i++){
                    const candidate = external_path_.join(currentDirectory, 'package.json');
                    if (external_fs_.existsSync(candidate)) return currentDirectory;
                    const parentDirectory = external_path_.dirname(currentDirectory);
                    if (parentDirectory === currentDirectory) break;
                    currentDirectory = parentDirectory;
                }
            };
            const packageJsonDirectory = findNearestPackageJsonDirectory(projectPath);
            if (!packageJsonDirectory) return false;
            const packageJsonPath = external_path_.join(packageJsonDirectory, 'package.json');
            if (!external_fs_.existsSync(packageJsonPath)) return false;
            const packageJson = JSON.parse(external_fs_.readFileSync(packageJsonPath, 'utf8'));
            const dependencies = packageJson.dependencies || {};
            const devDependencies = packageJson.devDependencies || {};
            return !!dependencies[dependency] || !!devDependencies[dependency];
        }
        function isUsingJSFramework(projectPath) {
            const frameworks = [
                'react',
                'vue',
                '@angular/core',
                'svelte',
                'solid-js',
                'preact'
            ];
            return frameworks.some((fw)=>hasDependency(projectPath, fw));
        }
        var config_loader = __webpack_require__("./webpack/webpack-lib/config-loader.ts");
        var resolve_config = __webpack_require__("./webpack/feature-special-folders/folder-extensions/resolve-config.ts");
        var get_data = __webpack_require__("./webpack/feature-special-folders/get-data.ts");
        var sanitize = __webpack_require__("./webpack/webpack-lib/sanitize.ts");
        var compiler_hooks = __webpack_require__("./webpack/dev-server/compiler-hooks.ts");
        function parseMilliseconds(value) {
            if ('number' == typeof value) return Number.isFinite(value) && value > 0 ? value : null;
            if ('string' == typeof value) {
                const parsed = parseInt(value, 10);
                return !Number.isNaN(parsed) && parsed > 0 ? parsed : null;
            }
            return null;
        }
        function setupAutoExit(autoExitMsRaw, forceKillMsRaw, onCleanup) {
            let autoExitTimer = null;
            let forceKillTimer = null;
            const autoExitMs = parseMilliseconds(autoExitMsRaw);
            if (null === autoExitMs) return ()=>{};
            try {
                console.log(messages.o6(autoExitMs));
            } catch  {}
            autoExitTimer = setTimeout(async ()=>{
                try {
                    console.log(messages.tJ(autoExitMs));
                } catch  {}
                await onCleanup();
            }, autoExitMs);
            const parsedForceKillMs = parseMilliseconds(forceKillMsRaw);
            const forceKillMs = null !== parsedForceKillMs && parsedForceKillMs > 0 ? parsedForceKillMs : autoExitMs + 4000;
            forceKillTimer = setTimeout(()=>{
                try {
                    console.log(messages.Df(forceKillMs));
                } catch  {}
                process.exit(0);
            }, forceKillMs);
            function cancelAutoExitTimers() {
                if (null !== autoExitTimer) {
                    clearTimeout(autoExitTimer);
                    autoExitTimer = null;
                }
                if (null !== forceKillTimer) {
                    clearTimeout(forceKillTimer);
                    forceKillTimer = null;
                }
            }
            return cancelAutoExitTimers;
        }
        function closeAll(devServer, portManager) {
            return devServer.stop().then(async ()=>{
                await portManager.terminateCurrentInstance();
                setTimeout(()=>process.exit(), 500);
            }).catch(async (error)=>{
                console.log(messages.VL(error));
                await portManager.terminateCurrentInstance();
                setTimeout(()=>process.exit(1), 500);
            });
        }
        function setupCleanupHandlers(devServer, portManager) {
            const cleanup = async ()=>{
                try {
                    await closeAll(devServer, portManager);
                } catch (error) {
                    console.error('[Extension.js Runner] Error during cleanup.', error);
                    process.exit(1);
                }
            };
            process.on('uncaughtException', async (error)=>{
                console.error('[Extension.js Runner] Uncaught exception.', error);
                await cleanup();
            });
            process.on('unhandledRejection', async (reason, promise)=>{
                console.error('[Extension.js Runner] Unhandled rejection.', promise, reason);
                await cleanup();
            });
            const cancelAutoExit = setupAutoExit(process.env.EXTENSION_AUTO_EXIT_MS, process.env.EXTENSION_FORCE_KILL_MS, cleanup);
            const cancelAndCleanup = async ()=>{
                try {
                    cancelAutoExit();
                } catch  {}
                await cleanup();
            };
            process.on('ERROR', cancelAndCleanup);
            process.on('SIGINT', cancelAndCleanup);
            process.on('SIGTERM', cancelAndCleanup);
            process.on('SIGHUP', cancelAndCleanup);
            return cancelAutoExit;
        }
        var plugin_playwright = __webpack_require__("./webpack/plugin-playwright/index.ts");
        var webpack_config = __webpack_require__("./webpack/webpack-config.ts");
        function shouldWriteAssetToDisk(filePath) {
            return !/(?:^|[/\\])manifest\.json$/i.test(filePath);
        }
        function isSamePath(left, right) {
            return external_path_.resolve(left) === external_path_.resolve(right);
        }
        function isManifestTempPath(filePath) {
            const base = external_path_.basename(filePath);
            return base.startsWith('.manifest.') && base.endsWith('.tmp');
        }
        function createDiscardWriteStream() {
            const stream = new external_stream_.Writable({
                write (_chunk, _encoding, callback) {
                    callback();
                }
            });
            stream.on('finish', ()=>{
                stream.emit('close');
            });
            process.nextTick(()=>{
                stream.emit('open', 0);
            });
            return stream;
        }
        const guardedManifestDiskWritePaths = new Set();
        let isManifestDiskWriteGuardInstalled = false;
        function hasGuardedManifestDiskPath(filePath) {
            if ('string' != typeof filePath) return false;
            const resolvedPath = external_path_.resolve(filePath);
            for (const guardedPath of guardedManifestDiskWritePaths)if (isSamePath(guardedPath, resolvedPath)) return true;
            return false;
        }
        function suppressManifestOutputWrites(compiler, manifestOutputPath) {
            const outputFileSystem = compiler?.outputFileSystem;
            if (!outputFileSystem || outputFileSystem.__extensionjsManifestWriteGuard) return;
            const isManifestPath = (filePath)=>'string' == typeof filePath && isSamePath(filePath, manifestOutputPath);
            if ('function' == typeof outputFileSystem.writeFile) {
                const originalWriteFile = outputFileSystem.writeFile.bind(outputFileSystem);
                outputFileSystem.writeFile = (filePath, ...args)=>{
                    if (isManifestPath(filePath)) {
                        const callback = args[args.length - 1];
                        if ('function' == typeof callback) callback(null);
                        return;
                    }
                    return originalWriteFile(filePath, ...args);
                };
            }
            if ('function' == typeof outputFileSystem.writeFileSync) {
                const originalWriteFileSync = outputFileSystem.writeFileSync.bind(outputFileSystem);
                outputFileSystem.writeFileSync = (filePath, ...args)=>{
                    if (isManifestPath(filePath)) return;
                    return originalWriteFileSync(filePath, ...args);
                };
            }
            if ('function' == typeof outputFileSystem.createWriteStream) {
                const originalCreateWriteStream = outputFileSystem.createWriteStream.bind(outputFileSystem);
                outputFileSystem.createWriteStream = (filePath, ...args)=>{
                    if (isManifestPath(filePath)) {
                        const stream = createDiscardWriteStream();
                        stream.path = filePath;
                        return stream;
                    }
                    return originalCreateWriteStream(filePath, ...args);
                };
            }
            if ('function' == typeof outputFileSystem?.promises?.writeFile) {
                const originalPromiseWriteFile = outputFileSystem.promises.writeFile.bind(outputFileSystem.promises);
                outputFileSystem.promises.writeFile = async (filePath, ...args)=>{
                    if (isManifestPath(filePath)) return;
                    return originalPromiseWriteFile(filePath, ...args);
                };
            }
            outputFileSystem.__extensionjsManifestWriteGuard = true;
        }
        function installManifestDiskWriteGuard(manifestOutputPath) {
            const guardKey = external_path_.resolve(manifestOutputPath);
            guardedManifestDiskWritePaths.add(guardKey);
            if (isManifestDiskWriteGuardInstalled) return;
            const guardedFs = external_fs_default();
            const isManifestPath = (filePath)=>hasGuardedManifestDiskPath(filePath);
            const allowManifestRename = (fromPath, toPath)=>'string' == typeof fromPath && 'string' == typeof toPath && isManifestPath(toPath) && isManifestTempPath(fromPath);
            const originalWriteFile = guardedFs.writeFile.bind(guardedFs);
            guardedFs.writeFile = (filePath, ...args)=>{
                if (isManifestPath(filePath)) {
                    const callback = args[args.length - 1];
                    if ('function' == typeof callback) callback(null);
                    return;
                }
                return originalWriteFile(filePath, ...args);
            };
            const originalWriteFileSync = guardedFs.writeFileSync.bind(guardedFs);
            guardedFs.writeFileSync = (filePath, ...args)=>{
                if (isManifestPath(filePath)) return;
                return originalWriteFileSync(filePath, ...args);
            };
            const originalCreateWriteStream = guardedFs.createWriteStream.bind(guardedFs);
            guardedFs.createWriteStream = (filePath, ...args)=>{
                if (isManifestPath(filePath)) {
                    const stream = createDiscardWriteStream();
                    stream.path = String(filePath);
                    return stream;
                }
                return originalCreateWriteStream(filePath, ...args);
            };
            const originalOpen = guardedFs.open.bind(guardedFs);
            guardedFs.open = (pathLike, flags, ...args)=>{
                const nextPath = isManifestPath(pathLike) ? '/dev/null' : pathLike;
                return originalOpen(nextPath, flags, ...args);
            };
            const originalOpenSync = guardedFs.openSync.bind(guardedFs);
            guardedFs.openSync = (pathLike, flags, ...args)=>{
                const nextPath = isManifestPath(pathLike) ? '/dev/null' : pathLike;
                return originalOpenSync(nextPath, flags, ...args);
            };
            const originalRename = guardedFs.rename.bind(guardedFs);
            guardedFs.rename = (oldPath, newPath, callback)=>{
                if (isManifestPath(newPath) && !allowManifestRename(oldPath, newPath)) {
                    if ('function' == typeof callback) callback(null);
                    return;
                }
                return originalRename(oldPath, newPath, callback);
            };
            const originalRenameSync = guardedFs.renameSync.bind(guardedFs);
            guardedFs.renameSync = (oldPath, newPath)=>{
                if (isManifestPath(newPath) && !allowManifestRename(oldPath, newPath)) return;
                return originalRenameSync(oldPath, newPath);
            };
            if (guardedFs.promises?.writeFile) {
                const originalPromiseWriteFile = guardedFs.promises.writeFile.bind(guardedFs.promises);
                guardedFs.promises.writeFile = async (filePath, ...args)=>{
                    if (isManifestPath(filePath)) return;
                    return originalPromiseWriteFile(filePath, ...args);
                };
            }
            isManifestDiskWriteGuardInstalled = true;
        }
        async function dev_server_devServer(projectStructure, devOptions) {
            process.env.EXTENSION_BROWSER_LAUNCH_ENABLED = devOptions.noBrowser ? '0' : '1';
            const { manifestPath, packageJsonPath } = projectStructure;
            external_path_.dirname(manifestPath);
            const packageJsonDir = external_path_.dirname(packageJsonPath);
            const commandConfig = await (0, config_loader.eY)(packageJsonDir, 'dev');
            const browserConfig = await (0, config_loader.xY)(packageJsonDir, devOptions.browser);
            const portManager = new PortManager(devOptions.browser, packageJsonDir, 8080);
            const desiredPort = 'string' == typeof devOptions.port ? parseInt(devOptions.port, 10) : devOptions.port;
            const portAllocation = await portManager.allocatePorts(devOptions.browser, packageJsonDir, desiredPort);
            const currentInstance = portManager.getCurrentInstance();
            if (!currentInstance) throw new Error('Failed to create instance');
            const port = portAllocation.port;
            const devServerHost = '127.0.0.1';
            const devServerWebSocketURL = {
                protocol: 'ws',
                hostname: devServerHost,
                port
            };
            const safeBrowserConfig = (0, sanitize.a)(browserConfig);
            const safeCommandConfig = (0, sanitize.a)(commandConfig);
            const safeDevOptions = (0, sanitize.a)(devOptions);
            const specialFoldersData = (0, get_data.H)(packageJsonDir);
            const mergedExtensionsConfig = safeDevOptions.extensions ?? safeCommandConfig.extensions ?? safeBrowserConfig.extensions ?? specialFoldersData.extensions;
            const resolvedExtensionsConfig = await (0, resolve_config.R)({
                projectRoot: packageJsonDir,
                browser: devOptions.browser,
                config: mergedExtensionsConfig
            });
            const baseConfig = (0, webpack_config["default"])(projectStructure, {
                ...safeBrowserConfig,
                ...safeCommandConfig,
                ...safeDevOptions,
                extensions: resolvedExtensionsConfig,
                browser: devOptions.browser,
                mode: 'development',
                instanceId: currentInstance.instanceId,
                port: portAllocation.port,
                output: {
                    clean: false,
                    path: external_path_.join(packageJsonDir, 'dist', devOptions.browser)
                }
            });
            const customWebpackConfig = await (0, config_loader.Tu)(packageJsonDir);
            const finalConfig = customWebpackConfig(baseConfig);
            const compilerConfig = (0, external_webpack_merge_.merge)(finalConfig, {});
            compilerConfig.devServer = {
                ...compilerConfig.devServer || {},
                host: devServerHost,
                port,
                client: {
                    ...(compilerConfig.devServer || {}).client || {},
                    webSocketURL: {
                        ...((compilerConfig.devServer || {}).client || {}).webSocketURL || {},
                        ...devServerWebSocketURL
                    }
                }
            };
            const compiler = (0, core_.rspack)(compilerConfig);
            const manifestOutputPath = external_path_.join(packageJsonDir, 'dist', devOptions.browser, 'manifest.json');
            installManifestDiskWriteGuard(manifestOutputPath);
            suppressManifestOutputWrites(compiler, manifestOutputPath);
            const metadata = (0, plugin_playwright.Ih)({
                packageJsonDir,
                browser: String(devOptions.browser || 'chromium'),
                command: 'dev',
                distPath: external_path_.join(packageJsonDir, 'dist', String(devOptions.browser || 'chromium')),
                manifestPath,
                port
            });
            (0, compiler_hooks.NP)(compiler);
            if (devOptions.noBrowser) (0, compiler_hooks.y1)({
                compiler,
                browser: String(devOptions.browser || 'chromium'),
                manifestPath,
                readyPath: metadata.readyPath
            });
            if (void 0 !== devOptions.port && devOptions.port !== port) console.log(messages.aO(devOptions.port, port));
            const serverConfig = {
                host: devServerHost,
                allowedHosts: 'all',
                static: {
                    directory: external_path_.join(packageJsonDir, 'public'),
                    watch: false
                },
                compress: false,
                devMiddleware: {
                    writeToDisk: shouldWriteAssetToDisk,
                    stats: false
                },
                watchFiles: {
                    paths: [
                        external_path_.join(packageJsonDir, 'public', '**/*'),
                        ...isUsingJSFramework(packageJsonDir) ? [] : [
                            external_path_.join(packageJsonDir, '**/*.html')
                        ]
                    ],
                    options: {
                        ignored: [
                            external_path_.join(packageJsonDir, 'dist', '**/*')
                        ],
                        ignoreInitial: true,
                        usePolling: true,
                        interval: 1000
                    }
                },
                client: {
                    logging: 'none',
                    progress: false,
                    overlay: false,
                    webSocketURL: devServerWebSocketURL
                },
                headers: {
                    'Access-Control-Allow-Origin': '*'
                },
                port,
                hot: 'only',
                liveReload: true
            };
            const devServer = new dev_server_.RspackDevServer(serverConfig, compiler);
            const START_TIMEOUT_MS = parseInt(String(process.env.EXTENSION_START_TIMEOUT_MS || '30000'), 10);
            let startTimeout;
            try {
                startTimeout = setTimeout(()=>{
                    console.error(messages.UF(START_TIMEOUT_MS));
                }, START_TIMEOUT_MS);
                await devServer.start();
                if (startTimeout) clearTimeout(startTimeout);
            } catch (error) {
                if (startTimeout) clearTimeout(startTimeout);
                metadata.writeError('dev_server_start_failed', error instanceof Error ? error.message : String(error));
                console.log(messages.VL(error));
                process.exit(1);
            }
            setupCleanupHandlers(devServer, portManager);
        }
    }
};
