import { Headers } from 'headers.js';
async function fetch(input, init = {}) {
let url;
if (typeof input === 'string') {
url = input;
} else if (input instanceof Request) {
url = input.url;
init = {
method: input.method,
headers: input.headers,
body: input.body,
...init
};
} else {
throw new TypeError('First argument must be a URL string or Request object');
}
const method = (init.method || 'GET').toUpperCase();
const headers = init.headers ? Object.fromEntries(
Object.entries(init.headers).map(([k, v]) => [k.toLowerCase(), String(v)])
) : null;
const body = init.body ? String(init.body) : null;
const timeout_ms = init.timeout_ms ? Math.floor(init.timeout_ms) : null;
try {
return await sendHttpRequest(method, url, headers, body, timeout_ms);
} catch (error) {
throw new Error('fetch error: ' + error.message);
}
}
class Request {
#method;
#url;
#headers;
#body;
constructor(input, init = {}) {
if (typeof input === 'string') {
this.#url = input;
} else if (input instanceof Request) {
this.#url = input.url;
this.#method = input.method;
this.#headers = {...input.headers};
this.#body = input.body;
} else {
throw new TypeError('First argument must be a URL string or Request object');
}
this.#method = (init.method || this.#method || 'GET').toUpperCase();
this.#headers = init.headers || this.#headers || {};
this.#body = init.body !== undefined ? init.body : this.#body;
}
get method() { return this.#method; }
get url() { return this.#url; }
get headers() { return this.#headers; }
get body() { return this.#body; }
clone() {
return new Request(this.#url, {
method: this.#method,
headers: {...this.#headers},
body: this.#body
});
}
}
export { fetch, Request, Headers };