//#region src/browser/providers/extension-ws-acquire.ts
const DEFAULT_PORT = 19820;
const DEFAULT_HOST = "127.0.0.1";
const DEFAULT_CONNECTION_TIMEOUT = 3e4;
const DEFAULT_COMMAND_TIMEOUT = 3e4;
let mutexTail = Promise.resolve();
function withExclusive(fn) {
	const prev = mutexTail;
	let unlock;
	mutexTail = new Promise((resolve) => {
		unlock = resolve;
	});
	return prev.then(() => fn()).finally(unlock);
}
let state = null;
function getExtensionBrowserServerSnapshot() {
	if (!state) return {
		active: false,
		refCount: 0,
		key: null
	};
	return {
		active: true,
		refCount: state.refCount,
		key: state.key
	};
}
function getExtensionBrowserProvider() {
	return state?.provider ?? null;
}
/** Shut down the shared listener regardless of remaining ref counts (settings UI stop). */
async function forceShutdownExtensionBrowserServer() {
	return withExclusive(async () => {
		if (!state) return false;
		await state.provider.shutdown();
		state = null;
		return true;
	});
}
function normalizeConfig(config) {
	return {
		port: config?.port ?? DEFAULT_PORT,
		host: config?.host ?? DEFAULT_HOST,
		connectionTimeout: config?.connectionTimeout ?? DEFAULT_CONNECTION_TIMEOUT,
		commandTimeout: config?.commandTimeout ?? DEFAULT_COMMAND_TIMEOUT
	};
}
function serverKey(c) {
	return `${c.host}:${c.port}`;
}
/**
* Increment ref count and return the shared provider plus a one-shot release.
* First acquire starts the listener; further acquires reuse it (same host:port).
*/
function acquireExtensionBrowserServer(config) {
	return withExclusive(async () => {
		const full = normalizeConfig(config);
		const key = serverKey(full);
		if (state && state.key !== key) throw new Error(`Chrome extension bridge is already listening on ${state.key}; stop it before using ${key}.`);
		if (!state) {
			const { ExtensionBrowserProvider } = await import("./extension.js");
			const provider = new ExtensionBrowserProvider(full);
			await provider.start();
			state = {
				key,
				provider,
				refCount: 0
			};
		}
		state.refCount++;
		let released = false;
		const release = async () => {
			await withExclusive(async () => {
				if (released || !state) return;
				released = true;
				state.refCount--;
				if (state.refCount <= 0) {
					await state.provider.shutdown();
					state = null;
				}
			});
		};
		return {
			provider: state.provider,
			release
		};
	});
}
//#endregion
export { acquireExtensionBrowserServer, forceShutdownExtensionBrowserServer, getExtensionBrowserProvider, getExtensionBrowserServerSnapshot };

//# sourceMappingURL=extension-ws-acquire.js.map