import { Resource } from "../resource.js";
import { memoize } from "../util/memoize.js";
import { withExponentialBackoff } from "../util/retry.js";
import { CloudflareApiError } from "./api-error.js";
import { extractCloudflareResult } from "./api-response.js";
import {} from "./api.js";
export const WorkerSubdomain = Resource("cloudflare::WorkerSubdomain", async function (_id, props) {
    if (this.phase === "delete") {
        return this.destroy();
    }
    return {};
});
export async function disableWorkerSubdomain(api, scriptName) {
    await extractCloudflareResult(`disable subdomain for "${scriptName}"`, api.post(`/accounts/${api.accountId}/workers/scripts/${scriptName}/subdomain`, {
        enabled: false,
    })).catch((error) => {
        if (error.status === 404) {
            return;
        }
        throw error;
    });
}
export async function enableWorkerSubdomain(api, scriptName, previewsEnabled = true) {
    await withExponentialBackoff(() => extractCloudflareResult(`enable subdomain for "${scriptName}"`, api.post(`/accounts/${api.accountId}/workers/scripts/${scriptName}/subdomain`, {
        enabled: true,
        previews_enabled: previewsEnabled,
    })), (error) => error instanceof CloudflareApiError && error.status === 404, 20, 1000);
}
export async function computeWorkerDevDomain(api, scriptName) {
    return `${scriptName}.${await getAccountSubdomain(api)}.workers.dev`;
}
export async function getWorkerSubdomain(api, scriptName) {
    return await extractCloudflareResult(`get subdomain for "${scriptName}"`, api.get(`/accounts/${api.accountId}/workers/scripts/${scriptName}/subdomain`)).catch((error) => {
        if (error.status === 404) {
            return { enabled: false, previews_enabled: false };
        }
        throw error;
    });
}
export const getAccountSubdomain = memoize(async (api) => {
    const result = await extractCloudflareResult(`get subdomain for account ${api.accountId}`, api.get(`/accounts/${api.accountId}/workers/subdomain`));
    return result.subdomain;
}, (api) => api.accountId);
export async function createWorkerUrl(api, scriptName, previewVersionId) {
    const subdomain = await getAccountSubdomain(api);
    const base = `${subdomain}.workers.dev`;
    let url;
    if (previewVersionId) {
        url = `https://${previewVersionId.substring(0, 8)}-${scriptName}.${base}`;
    }
    else {
        url = `https://${scriptName}.${base}`;
    }
    return url;
}
//# sourceMappingURL=worker-subdomain.js.map