const workspaceServicePortPlans = new Map();
const pendingWorkspaceServicePortPlans = new Map();
export async function ensureWorkspaceServicePortPlan(options) {
    const existingPlan = workspaceServicePortPlans.get(options.workspaceId);
    if (existingPlan) {
        return new Map(existingPlan);
    }
    let pendingPlan = pendingWorkspaceServicePortPlans.get(options.workspaceId);
    if (!pendingPlan) {
        pendingPlan = createPendingWorkspaceServicePortPlan({
            workspaceId: options.workspaceId,
            services: options.services,
            allocatePort: options.allocatePort,
        });
        pendingWorkspaceServicePortPlans.set(options.workspaceId, pendingPlan);
    }
    return new Map(await pendingPlan);
}
export function requirePlannedWorkspaceServicePort(plan, scriptName) {
    const port = plan.get(scriptName);
    if (port === undefined) {
        throw new Error(`Service '${scriptName}' is missing from workspace service port plan`);
    }
    return port;
}
async function createPendingWorkspaceServicePortPlan(options) {
    try {
        const plan = await buildWorkspaceServicePortPlan({
            services: options.services,
            allocatePort: options.allocatePort,
        });
        workspaceServicePortPlans.set(options.workspaceId, plan);
        return plan;
    }
    finally {
        pendingWorkspaceServicePortPlans.delete(options.workspaceId);
    }
}
async function buildWorkspaceServicePortPlan(options) {
    const plan = new Map();
    for (const service of options.services) {
        plan.set(service.scriptName, await resolveServicePort(service, options.allocatePort));
    }
    return plan;
}
export async function refreshWorkspaceServicePort(options) {
    const plan = workspaceServicePortPlans.get(options.workspaceId) ?? new Map();
    const port = await resolveServicePort(options.service, options.allocatePort);
    plan.set(options.service.scriptName, port);
    workspaceServicePortPlans.set(options.workspaceId, plan);
    return port;
}
async function resolveServicePort(service, allocatePort) {
    if (service.port !== undefined) {
        return service.port;
    }
    return await allocatePort();
}
//# sourceMappingURL=workspace-service-port-registry.js.map