import { ok } from "../../../is.js";
function mergeHeaders(...items) {
    const headers = new Headers(items[0]);
    for (let index = 1; index < items.length; index += 1) {
        const item = items[index];
        if (!item)
            continue;
        const next = new Headers(item);
        next.forEach((value, key) => {
            headers.set(key, value);
        });
    }
    return headers;
}
export class FetchStore {
    type;
    fetch;
    body;
    init;
    constructor({ type, body, fetch, ...init }) {
        this.type = type;
        this.body = body;
        this.fetch = fetch;
        this.init = init;
    }
    with(options) {
        return new FetchStore({
            type: this.type,
            body: this.body,
            fetch: this.fetch,
            ...options
        });
    }
    async post(type, value, init) {
        const response = await this.fetch(type, {
            ...this.init,
            ...init,
            method: "post",
            body: this.body?.(value) ?? value,
            headers: mergeHeaders(this.init.headers, init?.headers)
        });
        ok(response.ok);
        return response.headers.get("Location");
    }
    async put(url, value, init) {
        const response = await this.fetch(url, {
            ...this.init,
            ...init,
            method: "put",
            body: this.body?.(value) ?? value,
            headers: mergeHeaders(this.init.headers, init?.headers)
        });
        ok(response.ok);
    }
    async patch(url, value, init) {
        const response = await this.fetch(url, {
            ...init,
            method: "patch",
            body: this.body?.(value) ?? value,
            headers: mergeHeaders(this.init.headers, init?.headers)
        });
        ok(response.ok);
        return response[this.type]();
    }
    async delete(url, init) {
        const response = await this.fetch(url, {
            ...this.init,
            ...init,
            method: "delete",
            headers: mergeHeaders(this.init.headers, init?.headers)
        });
        ok(response.ok);
    }
    async get(urlOrType, init) {
        const response = await this.fetch(urlOrType || "/", {
            ...this.init,
            ...init,
            method: "get",
            headers: mergeHeaders(this.init.headers, init?.headers)
        });
        ok(response.ok);
        return response[this.type]();
    }
    async head(url, init) {
        const response = await this.fetch(url, {
            ...this.init,
            ...init,
            method: "head",
            headers: mergeHeaders(this.init.headers, init?.headers)
        });
        ok(response.ok);
        return response.headers;
    }
}
//# sourceMappingURL=fetch-store.js.map