"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const Functional_1 = require("../../../../../Class/Functional");
const _ids_1 = require("../../../../_ids");
class Fetch extends Functional_1.Functional {
    constructor(system) {
        super({
            i: ['url', 'opt'],
            o: ['response'],
        }, {}, system, _ids_1.ID_FETCH);
        this._fetch_index = 0;
    }
    f({ url, opt }, done) {
        const { api: { http: { fetch }, }, } = this.__system;
        const i = ++this._fetch_index;
        try {
            fetch(url, opt)
                .then((response) => {
                if (i !== this._fetch_index) {
                    // request is outdated
                    return;
                }
                return response.text().then((text) => {
                    if (i !== this._fetch_index) {
                        // request is outdated
                        return;
                    }
                    done({
                        response: {
                            status: response.status,
                            body: text,
                        },
                    });
                });
            })
                .catch((err) => {
                if (i !== this._fetch_index) {
                    // request is outdated
                    return;
                }
                if (err.message.toLowerCase() ===
                    "failed to execute 'fetch' on 'window': request with get/head method cannot have body.") {
                    done(undefined, 'request with GET/HEAD method cannot have body');
                    return;
                }
                done(undefined, err.message.toLowerCase());
            });
        }
        catch (err) {
            // console.log(err)
            done(undefined, 'malformed');
        }
    }
}
exports.default = Fetch;
//# sourceMappingURL=index.js.map