create-eliza
Version:
Initialize an Eliza project
1,526 lines (1,503 loc) • 85.5 kB
JavaScript
import { createRequire } from 'module';
const require = createRequire(import.meta.url);
import {
FormData,
fetch_blob_default,
formDataToBlob
} from "./chunk-ZK4M7HGI.js";
import {
execa
} from "./chunk-HKIJL32E.js";
import {
require_main
} from "./chunk-4CPNXENB.js";
import {
logger
} from "./chunk-2ORHBMCI.js";
import {
require_src
} from "./chunk-JWMTR3QA.js";
import {
__commonJS,
__require,
__toESM
} from "./chunk-WCMDOJQK.js";
// ../../node_modules/agent-base/dist/helpers.js
var require_helpers = __commonJS({
"../../node_modules/agent-base/dist/helpers.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.req = exports.json = exports.toBuffer = void 0;
var http3 = __importStar(__require("http"));
var https2 = __importStar(__require("https"));
async function toBuffer(stream) {
let length = 0;
const chunks = [];
for await (const chunk of stream) {
length += chunk.length;
chunks.push(chunk);
}
return Buffer.concat(chunks, length);
}
exports.toBuffer = toBuffer;
async function json(stream) {
const buf = await toBuffer(stream);
const str = buf.toString("utf8");
try {
return JSON.parse(str);
} catch (_err) {
const err = _err;
err.message += ` (input: ${str})`;
throw err;
}
}
exports.json = json;
function req(url, opts = {}) {
const href = typeof url === "string" ? url : url.href;
const req2 = (href.startsWith("https:") ? https2 : http3).request(url, opts);
const promise = new Promise((resolve, reject) => {
req2.once("response", resolve).once("error", reject).end();
});
req2.then = promise.then.bind(promise);
return req2;
}
exports.req = req;
}
});
// ../../node_modules/agent-base/dist/index.js
var require_dist = __commonJS({
"../../node_modules/agent-base/dist/index.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __exportStar = exports && exports.__exportStar || function(m, exports2) {
for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports2, p)) __createBinding(exports2, m, p);
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.Agent = void 0;
var net = __importStar(__require("net"));
var http3 = __importStar(__require("http"));
var https_1 = __require("https");
__exportStar(require_helpers(), exports);
var INTERNAL = Symbol("AgentBaseInternalState");
var Agent = class extends http3.Agent {
constructor(opts) {
super(opts);
this[INTERNAL] = {};
}
/**
* Determine whether this is an `http` or `https` request.
*/
isSecureEndpoint(options) {
if (options) {
if (typeof options.secureEndpoint === "boolean") {
return options.secureEndpoint;
}
if (typeof options.protocol === "string") {
return options.protocol === "https:";
}
}
const { stack } = new Error();
if (typeof stack !== "string")
return false;
return stack.split("\n").some((l) => l.indexOf("(https.js:") !== -1 || l.indexOf("node:https:") !== -1);
}
// In order to support async signatures in `connect()` and Node's native
// connection pooling in `http.Agent`, the array of sockets for each origin
// has to be updated synchronously. This is so the length of the array is
// accurate when `addRequest()` is next called. We achieve this by creating a
// fake socket and adding it to `sockets[origin]` and incrementing
// `totalSocketCount`.
incrementSockets(name) {
if (this.maxSockets === Infinity && this.maxTotalSockets === Infinity) {
return null;
}
if (!this.sockets[name]) {
this.sockets[name] = [];
}
const fakeSocket = new net.Socket({ writable: false });
this.sockets[name].push(fakeSocket);
this.totalSocketCount++;
return fakeSocket;
}
decrementSockets(name, socket) {
if (!this.sockets[name] || socket === null) {
return;
}
const sockets = this.sockets[name];
const index = sockets.indexOf(socket);
if (index !== -1) {
sockets.splice(index, 1);
this.totalSocketCount--;
if (sockets.length === 0) {
delete this.sockets[name];
}
}
}
// In order to properly update the socket pool, we need to call `getName()` on
// the core `https.Agent` if it is a secureEndpoint.
getName(options) {
const secureEndpoint = typeof options.secureEndpoint === "boolean" ? options.secureEndpoint : this.isSecureEndpoint(options);
if (secureEndpoint) {
return https_1.Agent.prototype.getName.call(this, options);
}
return super.getName(options);
}
createSocket(req, options, cb) {
const connectOpts = {
...options,
secureEndpoint: this.isSecureEndpoint(options)
};
const name = this.getName(connectOpts);
const fakeSocket = this.incrementSockets(name);
Promise.resolve().then(() => this.connect(req, connectOpts)).then((socket) => {
this.decrementSockets(name, fakeSocket);
if (socket instanceof http3.Agent) {
try {
return socket.addRequest(req, connectOpts);
} catch (err) {
return cb(err);
}
}
this[INTERNAL].currentSocket = socket;
super.createSocket(req, options, cb);
}, (err) => {
this.decrementSockets(name, fakeSocket);
cb(err);
});
}
createConnection() {
const socket = this[INTERNAL].currentSocket;
this[INTERNAL].currentSocket = void 0;
if (!socket) {
throw new Error("No socket was returned in the `connect()` function");
}
return socket;
}
get defaultPort() {
return this[INTERNAL].defaultPort ?? (this.protocol === "https:" ? 443 : 80);
}
set defaultPort(v) {
if (this[INTERNAL]) {
this[INTERNAL].defaultPort = v;
}
}
get protocol() {
return this[INTERNAL].protocol ?? (this.isSecureEndpoint() ? "https:" : "http:");
}
set protocol(v) {
if (this[INTERNAL]) {
this[INTERNAL].protocol = v;
}
}
};
exports.Agent = Agent;
}
});
// ../../node_modules/https-proxy-agent/dist/parse-proxy-response.js
var require_parse_proxy_response = __commonJS({
"../../node_modules/https-proxy-agent/dist/parse-proxy-response.js"(exports) {
"use strict";
var __importDefault = exports && exports.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.parseProxyResponse = void 0;
var debug_1 = __importDefault(require_src());
var debug = (0, debug_1.default)("https-proxy-agent:parse-proxy-response");
function parseProxyResponse(socket) {
return new Promise((resolve, reject) => {
let buffersLength = 0;
const buffers = [];
function read() {
const b = socket.read();
if (b)
ondata(b);
else
socket.once("readable", read);
}
function cleanup() {
socket.removeListener("end", onend);
socket.removeListener("error", onerror);
socket.removeListener("readable", read);
}
function onend() {
cleanup();
debug("onend");
reject(new Error("Proxy connection ended before receiving CONNECT response"));
}
function onerror(err) {
cleanup();
debug("onerror %o", err);
reject(err);
}
function ondata(b) {
buffers.push(b);
buffersLength += b.length;
const buffered = Buffer.concat(buffers, buffersLength);
const endOfHeaders = buffered.indexOf("\r\n\r\n");
if (endOfHeaders === -1) {
debug("have not received end of HTTP headers yet...");
read();
return;
}
const headerParts = buffered.toString("ascii").split("\r\n");
const firstLine = headerParts.shift();
if (!firstLine) {
socket.destroy();
return reject(new Error("No header received from proxy CONNECT response"));
}
const firstLineParts = firstLine.split(" ");
const statusCode = +firstLineParts[1];
const statusText = firstLineParts.slice(2).join(" ");
const headers = {};
for (const header of headerParts) {
if (!header)
continue;
const firstColon = header.indexOf(":");
if (firstColon === -1) {
socket.destroy();
return reject(new Error(`Invalid header from proxy CONNECT response: "${header}"`));
}
const key = header.slice(0, firstColon).toLowerCase();
const value = header.slice(firstColon + 1).trimStart();
const current = headers[key];
if (typeof current === "string") {
headers[key] = [current, value];
} else if (Array.isArray(current)) {
current.push(value);
} else {
headers[key] = value;
}
}
debug("got proxy server response: %o %o", firstLine, headers);
cleanup();
resolve({
connect: {
statusCode,
statusText,
headers
},
buffered
});
}
socket.on("error", onerror);
socket.on("end", onend);
read();
});
}
exports.parseProxyResponse = parseProxyResponse;
}
});
// ../../node_modules/https-proxy-agent/dist/index.js
var require_dist2 = __commonJS({
"../../node_modules/https-proxy-agent/dist/index.js"(exports) {
"use strict";
var __createBinding = exports && exports.__createBinding || (Object.create ? function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
var desc = Object.getOwnPropertyDescriptor(m, k);
if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
desc = { enumerable: true, get: function() {
return m[k];
} };
}
Object.defineProperty(o, k2, desc);
} : function(o, m, k, k2) {
if (k2 === void 0) k2 = k;
o[k2] = m[k];
});
var __setModuleDefault = exports && exports.__setModuleDefault || (Object.create ? function(o, v) {
Object.defineProperty(o, "default", { enumerable: true, value: v });
} : function(o, v) {
o["default"] = v;
});
var __importStar = exports && exports.__importStar || function(mod) {
if (mod && mod.__esModule) return mod;
var result = {};
if (mod != null) {
for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
}
__setModuleDefault(result, mod);
return result;
};
var __importDefault = exports && exports.__importDefault || function(mod) {
return mod && mod.__esModule ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.HttpsProxyAgent = void 0;
var net = __importStar(__require("net"));
var tls = __importStar(__require("tls"));
var assert_1 = __importDefault(__require("assert"));
var debug_1 = __importDefault(require_src());
var agent_base_1 = require_dist();
var parse_proxy_response_1 = require_parse_proxy_response();
var debug = (0, debug_1.default)("https-proxy-agent");
var HttpsProxyAgent2 = class extends agent_base_1.Agent {
get secureProxy() {
return isHTTPS(this.proxy.protocol);
}
constructor(proxy, opts) {
super(opts);
this.options = { path: void 0 };
this.proxy = typeof proxy === "string" ? new URL(proxy) : proxy;
this.proxyHeaders = opts?.headers ?? {};
debug("Creating new HttpsProxyAgent instance: %o", this.proxy.href);
const host = (this.proxy.hostname || this.proxy.host).replace(/^\[|\]$/g, "");
const port = this.proxy.port ? parseInt(this.proxy.port, 10) : this.secureProxy ? 443 : 80;
this.connectOpts = {
// Attempt to negotiate http/1.1 for proxy servers that support http/2
ALPNProtocols: ["http/1.1"],
...opts ? omit(opts, "headers") : null,
host,
port
};
}
/**
* Called when the node-core HTTP client library is creating a
* new HTTP request.
*/
async connect(req, opts) {
const { proxy, secureProxy } = this;
if (!opts.host) {
throw new TypeError('No "host" provided');
}
let socket;
if (secureProxy) {
debug("Creating `tls.Socket`: %o", this.connectOpts);
socket = tls.connect(this.connectOpts);
} else {
debug("Creating `net.Socket`: %o", this.connectOpts);
socket = net.connect(this.connectOpts);
}
const headers = typeof this.proxyHeaders === "function" ? this.proxyHeaders() : { ...this.proxyHeaders };
const host = net.isIPv6(opts.host) ? `[${opts.host}]` : opts.host;
let payload = `CONNECT ${host}:${opts.port} HTTP/1.1\r
`;
if (proxy.username || proxy.password) {
const auth = `${decodeURIComponent(proxy.username)}:${decodeURIComponent(proxy.password)}`;
headers["Proxy-Authorization"] = `Basic ${Buffer.from(auth).toString("base64")}`;
}
headers.Host = `${host}:${opts.port}`;
if (!headers["Proxy-Connection"]) {
headers["Proxy-Connection"] = this.keepAlive ? "Keep-Alive" : "close";
}
for (const name of Object.keys(headers)) {
payload += `${name}: ${headers[name]}\r
`;
}
const proxyResponsePromise = (0, parse_proxy_response_1.parseProxyResponse)(socket);
socket.write(`${payload}\r
`);
const { connect, buffered } = await proxyResponsePromise;
req.emit("proxyConnect", connect);
this.emit("proxyConnect", connect, req);
if (connect.statusCode === 200) {
req.once("socket", resume);
if (opts.secureEndpoint) {
debug("Upgrading socket connection to TLS");
const servername = opts.servername || opts.host;
return tls.connect({
...omit(opts, "host", "path", "port"),
socket,
servername: net.isIP(servername) ? void 0 : servername
});
}
return socket;
}
socket.destroy();
const fakeSocket = new net.Socket({ writable: false });
fakeSocket.readable = true;
req.once("socket", (s) => {
debug("Replaying proxy buffer for failed request");
(0, assert_1.default)(s.listenerCount("data") > 0);
s.push(buffered);
s.push(null);
});
return fakeSocket;
}
};
HttpsProxyAgent2.protocols = ["http", "https"];
exports.HttpsProxyAgent = HttpsProxyAgent2;
function resume(socket) {
socket.resume();
}
function isHTTPS(protocol) {
return typeof protocol === "string" ? /^https:?$/i.test(protocol) : false;
}
function omit(obj, ...keys) {
const ret = {};
let key;
for (key in obj) {
if (!keys.includes(key)) {
ret[key] = obj[key];
}
}
return ret;
}
}
});
// src/utils/registry/index.ts
import { promises as fs2 } from "node:fs";
import { existsSync } from "node:fs";
import os2 from "node:os";
import path2 from "node:path";
var import_dotenv = __toESM(require_main(), 1);
var import_https_proxy_agent = __toESM(require_dist2(), 1);
// ../../node_modules/node-fetch/src/index.js
import http2 from "node:http";
import https from "node:https";
import zlib from "node:zlib";
import Stream2, { PassThrough as PassThrough2, pipeline as pump } from "node:stream";
import { Buffer as Buffer3 } from "node:buffer";
// ../../node_modules/data-uri-to-buffer/dist/index.js
function dataUriToBuffer(uri) {
if (!/^data:/i.test(uri)) {
throw new TypeError('`uri` does not appear to be a Data URI (must begin with "data:")');
}
uri = uri.replace(/\r?\n/g, "");
const firstComma = uri.indexOf(",");
if (firstComma === -1 || firstComma <= 4) {
throw new TypeError("malformed data: URI");
}
const meta = uri.substring(5, firstComma).split(";");
let charset = "";
let base64 = false;
const type = meta[0] || "text/plain";
let typeFull = type;
for (let i = 1; i < meta.length; i++) {
if (meta[i] === "base64") {
base64 = true;
} else if (meta[i]) {
typeFull += `;${meta[i]}`;
if (meta[i].indexOf("charset=") === 0) {
charset = meta[i].substring(8);
}
}
}
if (!meta[0] && !charset.length) {
typeFull += ";charset=US-ASCII";
charset = "US-ASCII";
}
const encoding = base64 ? "base64" : "ascii";
const data = unescape(uri.substring(firstComma + 1));
const buffer = Buffer.from(data, encoding);
buffer.type = type;
buffer.typeFull = typeFull;
buffer.charset = charset;
return buffer;
}
var dist_default = dataUriToBuffer;
// ../../node_modules/node-fetch/src/body.js
import Stream, { PassThrough } from "node:stream";
import { types, deprecate, promisify } from "node:util";
import { Buffer as Buffer2 } from "node:buffer";
// ../../node_modules/node-fetch/src/errors/base.js
var FetchBaseError = class extends Error {
constructor(message, type) {
super(message);
Error.captureStackTrace(this, this.constructor);
this.type = type;
}
get name() {
return this.constructor.name;
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
};
// ../../node_modules/node-fetch/src/errors/fetch-error.js
var FetchError = class extends FetchBaseError {
/**
* @param {string} message - Error message for human
* @param {string} [type] - Error type for machine
* @param {SystemError} [systemError] - For Node.js system error
*/
constructor(message, type, systemError) {
super(message, type);
if (systemError) {
this.code = this.errno = systemError.code;
this.erroredSysCall = systemError.syscall;
}
}
};
// ../../node_modules/node-fetch/src/utils/is.js
var NAME = Symbol.toStringTag;
var isURLSearchParameters = (object) => {
return typeof object === "object" && typeof object.append === "function" && typeof object.delete === "function" && typeof object.get === "function" && typeof object.getAll === "function" && typeof object.has === "function" && typeof object.set === "function" && typeof object.sort === "function" && object[NAME] === "URLSearchParams";
};
var isBlob = (object) => {
return object && typeof object === "object" && typeof object.arrayBuffer === "function" && typeof object.type === "string" && typeof object.stream === "function" && typeof object.constructor === "function" && /^(Blob|File)$/.test(object[NAME]);
};
var isAbortSignal = (object) => {
return typeof object === "object" && (object[NAME] === "AbortSignal" || object[NAME] === "EventTarget");
};
var isDomainOrSubdomain = (destination, original) => {
const orig = new URL(original).hostname;
const dest = new URL(destination).hostname;
return orig === dest || orig.endsWith(`.${dest}`);
};
var isSameProtocol = (destination, original) => {
const orig = new URL(original).protocol;
const dest = new URL(destination).protocol;
return orig === dest;
};
// ../../node_modules/node-fetch/src/body.js
var pipeline = promisify(Stream.pipeline);
var INTERNALS = Symbol("Body internals");
var Body = class {
constructor(body, {
size = 0
} = {}) {
let boundary = null;
if (body === null) {
body = null;
} else if (isURLSearchParameters(body)) {
body = Buffer2.from(body.toString());
} else if (isBlob(body)) {
} else if (Buffer2.isBuffer(body)) {
} else if (types.isAnyArrayBuffer(body)) {
body = Buffer2.from(body);
} else if (ArrayBuffer.isView(body)) {
body = Buffer2.from(body.buffer, body.byteOffset, body.byteLength);
} else if (body instanceof Stream) {
} else if (body instanceof FormData) {
body = formDataToBlob(body);
boundary = body.type.split("=")[1];
} else {
body = Buffer2.from(String(body));
}
let stream = body;
if (Buffer2.isBuffer(body)) {
stream = Stream.Readable.from(body);
} else if (isBlob(body)) {
stream = Stream.Readable.from(body.stream());
}
this[INTERNALS] = {
body,
stream,
boundary,
disturbed: false,
error: null
};
this.size = size;
if (body instanceof Stream) {
body.on("error", (error_) => {
const error = error_ instanceof FetchBaseError ? error_ : new FetchError(`Invalid response body while trying to fetch ${this.url}: ${error_.message}`, "system", error_);
this[INTERNALS].error = error;
});
}
}
get body() {
return this[INTERNALS].stream;
}
get bodyUsed() {
return this[INTERNALS].disturbed;
}
/**
* Decode response as ArrayBuffer
*
* @return Promise
*/
async arrayBuffer() {
const { buffer, byteOffset, byteLength } = await consumeBody(this);
return buffer.slice(byteOffset, byteOffset + byteLength);
}
async formData() {
const ct = this.headers.get("content-type");
if (ct.startsWith("application/x-www-form-urlencoded")) {
const formData = new FormData();
const parameters = new URLSearchParams(await this.text());
for (const [name, value] of parameters) {
formData.append(name, value);
}
return formData;
}
const { toFormData } = await import("./multipart-parser-T46PDUIC.js");
return toFormData(this.body, ct);
}
/**
* Return raw response as Blob
*
* @return Promise
*/
async blob() {
const ct = this.headers && this.headers.get("content-type") || this[INTERNALS].body && this[INTERNALS].body.type || "";
const buf = await this.arrayBuffer();
return new fetch_blob_default([buf], {
type: ct
});
}
/**
* Decode response as json
*
* @return Promise
*/
async json() {
const text = await this.text();
return JSON.parse(text);
}
/**
* Decode response as text
*
* @return Promise
*/
async text() {
const buffer = await consumeBody(this);
return new TextDecoder().decode(buffer);
}
/**
* Decode response as buffer (non-spec api)
*
* @return Promise
*/
buffer() {
return consumeBody(this);
}
};
Body.prototype.buffer = deprecate(Body.prototype.buffer, "Please use 'response.arrayBuffer()' instead of 'response.buffer()'", "node-fetch#buffer");
Object.defineProperties(Body.prototype, {
body: { enumerable: true },
bodyUsed: { enumerable: true },
arrayBuffer: { enumerable: true },
blob: { enumerable: true },
json: { enumerable: true },
text: { enumerable: true },
data: { get: deprecate(
() => {
},
"data doesn't exist, use json(), text(), arrayBuffer(), or body instead",
"https://github.com/node-fetch/node-fetch/issues/1000 (response)"
) }
});
async function consumeBody(data) {
if (data[INTERNALS].disturbed) {
throw new TypeError(`body used already for: ${data.url}`);
}
data[INTERNALS].disturbed = true;
if (data[INTERNALS].error) {
throw data[INTERNALS].error;
}
const { body } = data;
if (body === null) {
return Buffer2.alloc(0);
}
if (!(body instanceof Stream)) {
return Buffer2.alloc(0);
}
const accum = [];
let accumBytes = 0;
try {
for await (const chunk of body) {
if (data.size > 0 && accumBytes + chunk.length > data.size) {
const error = new FetchError(`content size at ${data.url} over limit: ${data.size}`, "max-size");
body.destroy(error);
throw error;
}
accumBytes += chunk.length;
accum.push(chunk);
}
} catch (error) {
const error_ = error instanceof FetchBaseError ? error : new FetchError(`Invalid response body while trying to fetch ${data.url}: ${error.message}`, "system", error);
throw error_;
}
if (body.readableEnded === true || body._readableState.ended === true) {
try {
if (accum.every((c) => typeof c === "string")) {
return Buffer2.from(accum.join(""));
}
return Buffer2.concat(accum, accumBytes);
} catch (error) {
throw new FetchError(`Could not create Buffer from response body for ${data.url}: ${error.message}`, "system", error);
}
} else {
throw new FetchError(`Premature close of server response while trying to fetch ${data.url}`);
}
}
var clone = (instance, highWaterMark) => {
let p1;
let p2;
let { body } = instance[INTERNALS];
if (instance.bodyUsed) {
throw new Error("cannot clone body after it is used");
}
if (body instanceof Stream && typeof body.getBoundary !== "function") {
p1 = new PassThrough({ highWaterMark });
p2 = new PassThrough({ highWaterMark });
body.pipe(p1);
body.pipe(p2);
instance[INTERNALS].stream = p1;
body = p2;
}
return body;
};
var getNonSpecFormDataBoundary = deprecate(
(body) => body.getBoundary(),
"form-data doesn't follow the spec and requires special treatment. Use alternative package",
"https://github.com/node-fetch/node-fetch/issues/1167"
);
var extractContentType = (body, request) => {
if (body === null) {
return null;
}
if (typeof body === "string") {
return "text/plain;charset=UTF-8";
}
if (isURLSearchParameters(body)) {
return "application/x-www-form-urlencoded;charset=UTF-8";
}
if (isBlob(body)) {
return body.type || null;
}
if (Buffer2.isBuffer(body) || types.isAnyArrayBuffer(body) || ArrayBuffer.isView(body)) {
return null;
}
if (body instanceof FormData) {
return `multipart/form-data; boundary=${request[INTERNALS].boundary}`;
}
if (body && typeof body.getBoundary === "function") {
return `multipart/form-data;boundary=${getNonSpecFormDataBoundary(body)}`;
}
if (body instanceof Stream) {
return null;
}
return "text/plain;charset=UTF-8";
};
var getTotalBytes = (request) => {
const { body } = request[INTERNALS];
if (body === null) {
return 0;
}
if (isBlob(body)) {
return body.size;
}
if (Buffer2.isBuffer(body)) {
return body.length;
}
if (body && typeof body.getLengthSync === "function") {
return body.hasKnownLength && body.hasKnownLength() ? body.getLengthSync() : null;
}
return null;
};
var writeToStream = async (dest, { body }) => {
if (body === null) {
dest.end();
} else {
await pipeline(body, dest);
}
};
// ../../node_modules/node-fetch/src/headers.js
import { types as types2 } from "node:util";
import http from "node:http";
var validateHeaderName = typeof http.validateHeaderName === "function" ? http.validateHeaderName : (name) => {
if (!/^[\^`\-\w!#$%&'*+.|~]+$/.test(name)) {
const error = new TypeError(`Header name must be a valid HTTP token [${name}]`);
Object.defineProperty(error, "code", { value: "ERR_INVALID_HTTP_TOKEN" });
throw error;
}
};
var validateHeaderValue = typeof http.validateHeaderValue === "function" ? http.validateHeaderValue : (name, value) => {
if (/[^\t\u0020-\u007E\u0080-\u00FF]/.test(value)) {
const error = new TypeError(`Invalid character in header content ["${name}"]`);
Object.defineProperty(error, "code", { value: "ERR_INVALID_CHAR" });
throw error;
}
};
var Headers = class _Headers extends URLSearchParams {
/**
* Headers class
*
* @constructor
* @param {HeadersInit} [init] - Response headers
*/
constructor(init) {
let result = [];
if (init instanceof _Headers) {
const raw = init.raw();
for (const [name, values] of Object.entries(raw)) {
result.push(...values.map((value) => [name, value]));
}
} else if (init == null) {
} else if (typeof init === "object" && !types2.isBoxedPrimitive(init)) {
const method = init[Symbol.iterator];
if (method == null) {
result.push(...Object.entries(init));
} else {
if (typeof method !== "function") {
throw new TypeError("Header pairs must be iterable");
}
result = [...init].map((pair) => {
if (typeof pair !== "object" || types2.isBoxedPrimitive(pair)) {
throw new TypeError("Each header pair must be an iterable object");
}
return [...pair];
}).map((pair) => {
if (pair.length !== 2) {
throw new TypeError("Each header pair must be a name/value tuple");
}
return [...pair];
});
}
} else {
throw new TypeError("Failed to construct 'Headers': The provided value is not of type '(sequence<sequence<ByteString>> or record<ByteString, ByteString>)");
}
result = result.length > 0 ? result.map(([name, value]) => {
validateHeaderName(name);
validateHeaderValue(name, String(value));
return [String(name).toLowerCase(), String(value)];
}) : void 0;
super(result);
return new Proxy(this, {
get(target, p, receiver) {
switch (p) {
case "append":
case "set":
return (name, value) => {
validateHeaderName(name);
validateHeaderValue(name, String(value));
return URLSearchParams.prototype[p].call(
target,
String(name).toLowerCase(),
String(value)
);
};
case "delete":
case "has":
case "getAll":
return (name) => {
validateHeaderName(name);
return URLSearchParams.prototype[p].call(
target,
String(name).toLowerCase()
);
};
case "keys":
return () => {
target.sort();
return new Set(URLSearchParams.prototype.keys.call(target)).keys();
};
default:
return Reflect.get(target, p, receiver);
}
}
});
}
get [Symbol.toStringTag]() {
return this.constructor.name;
}
toString() {
return Object.prototype.toString.call(this);
}
get(name) {
const values = this.getAll(name);
if (values.length === 0) {
return null;
}
let value = values.join(", ");
if (/^content-encoding$/i.test(name)) {
value = value.toLowerCase();
}
return value;
}
forEach(callback, thisArg = void 0) {
for (const name of this.keys()) {
Reflect.apply(callback, thisArg, [this.get(name), name, this]);
}
}
*values() {
for (const name of this.keys()) {
yield this.get(name);
}
}
/**
* @type {() => IterableIterator<[string, string]>}
*/
*entries() {
for (const name of this.keys()) {
yield [name, this.get(name)];
}
}
[Symbol.iterator]() {
return this.entries();
}
/**
* Node-fetch non-spec method
* returning all headers and their values as array
* @returns {Record<string, string[]>}
*/
raw() {
return [...this.keys()].reduce((result, key) => {
result[key] = this.getAll(key);
return result;
}, {});
}
/**
* For better console.log(headers) and also to convert Headers into Node.js Request compatible format
*/
[Symbol.for("nodejs.util.inspect.custom")]() {
return [...this.keys()].reduce((result, key) => {
const values = this.getAll(key);
if (key === "host") {
result[key] = values[0];
} else {
result[key] = values.length > 1 ? values : values[0];
}
return result;
}, {});
}
};
Object.defineProperties(
Headers.prototype,
["get", "entries", "forEach", "values"].reduce((result, property) => {
result[property] = { enumerable: true };
return result;
}, {})
);
function fromRawHeaders(headers = []) {
return new Headers(
headers.reduce((result, value, index, array) => {
if (index % 2 === 0) {
result.push(array.slice(index, index + 2));
}
return result;
}, []).filter(([name, value]) => {
try {
validateHeaderName(name);
validateHeaderValue(name, String(value));
return true;
} catch {
return false;
}
})
);
}
// ../../node_modules/node-fetch/src/utils/is-redirect.js
var redirectStatus = /* @__PURE__ */ new Set([301, 302, 303, 307, 308]);
var isRedirect = (code) => {
return redirectStatus.has(code);
};
// ../../node_modules/node-fetch/src/response.js
var INTERNALS2 = Symbol("Response internals");
var Response = class _Response extends Body {
constructor(body = null, options = {}) {
super(body, options);
const status = options.status != null ? options.status : 200;
const headers = new Headers(options.headers);
if (body !== null && !headers.has("Content-Type")) {
const contentType = extractContentType(body, this);
if (contentType) {
headers.append("Content-Type", contentType);
}
}
this[INTERNALS2] = {
type: "default",
url: options.url,
status,
statusText: options.statusText || "",
headers,
counter: options.counter,
highWaterMark: options.highWaterMark
};
}
get type() {
return this[INTERNALS2].type;
}
get url() {
return this[INTERNALS2].url || "";
}
get status() {
return this[INTERNALS2].status;
}
/**
* Convenience property representing if the request ended normally
*/
get ok() {
return this[INTERNALS2].status >= 200 && this[INTERNALS2].status < 300;
}
get redirected() {
return this[INTERNALS2].counter > 0;
}
get statusText() {
return this[INTERNALS2].statusText;
}
get headers() {
return this[INTERNALS2].headers;
}
get highWaterMark() {
return this[INTERNALS2].highWaterMark;
}
/**
* Clone this response
*
* @return Response
*/
clone() {
return new _Response(clone(this, this.highWaterMark), {
type: this.type,
url: this.url,
status: this.status,
statusText: this.statusText,
headers: this.headers,
ok: this.ok,
redirected: this.redirected,
size: this.size,
highWaterMark: this.highWaterMark
});
}
/**
* @param {string} url The URL that the new response is to originate from.
* @param {number} status An optional status code for the response (e.g., 302.)
* @returns {Response} A Response object.
*/
static redirect(url, status = 302) {
if (!isRedirect(status)) {
throw new RangeError('Failed to execute "redirect" on "response": Invalid status code');
}
return new _Response(null, {
headers: {
location: new URL(url).toString()
},
status
});
}
static error() {
const response = new _Response(null, { status: 0, statusText: "" });
response[INTERNALS2].type = "error";
return response;
}
static json(data = void 0, init = {}) {
const body = JSON.stringify(data);
if (body === void 0) {
throw new TypeError("data is not JSON serializable");
}
const headers = new Headers(init && init.headers);
if (!headers.has("content-type")) {
headers.set("content-type", "application/json");
}
return new _Response(body, {
...init,
headers
});
}
get [Symbol.toStringTag]() {
return "Response";
}
};
Object.defineProperties(Response.prototype, {
type: { enumerable: true },
url: { enumerable: true },
status: { enumerable: true },
ok: { enumerable: true },
redirected: { enumerable: true },
statusText: { enumerable: true },
headers: { enumerable: true },
clone: { enumerable: true }
});
// ../../node_modules/node-fetch/src/request.js
import { format as formatUrl } from "node:url";
import { deprecate as deprecate2 } from "node:util";
// ../../node_modules/node-fetch/src/utils/get-search.js
var getSearch = (parsedURL) => {
if (parsedURL.search) {
return parsedURL.search;
}
const lastOffset = parsedURL.href.length - 1;
const hash = parsedURL.hash || (parsedURL.href[lastOffset] === "#" ? "#" : "");
return parsedURL.href[lastOffset - hash.length] === "?" ? "?" : "";
};
// ../../node_modules/node-fetch/src/utils/referrer.js
import { isIP } from "node:net";
function stripURLForUseAsAReferrer(url, originOnly = false) {
if (url == null) {
return "no-referrer";
}
url = new URL(url);
if (/^(about|blob|data):$/.test(url.protocol)) {
return "no-referrer";
}
url.username = "";
url.password = "";
url.hash = "";
if (originOnly) {
url.pathname = "";
url.search = "";
}
return url;
}
var ReferrerPolicy = /* @__PURE__ */ new Set([
"",
"no-referrer",
"no-referrer-when-downgrade",
"same-origin",
"origin",
"strict-origin",
"origin-when-cross-origin",
"strict-origin-when-cross-origin",
"unsafe-url"
]);
var DEFAULT_REFERRER_POLICY = "strict-origin-when-cross-origin";
function validateReferrerPolicy(referrerPolicy) {
if (!ReferrerPolicy.has(referrerPolicy)) {
throw new TypeError(`Invalid referrerPolicy: ${referrerPolicy}`);
}
return referrerPolicy;
}
function isOriginPotentiallyTrustworthy(url) {
if (/^(http|ws)s:$/.test(url.protocol)) {
return true;
}
const hostIp = url.host.replace(/(^\[)|(]$)/g, "");
const hostIPVersion = isIP(hostIp);
if (hostIPVersion === 4 && /^127\./.test(hostIp)) {
return true;
}
if (hostIPVersion === 6 && /^(((0+:){7})|(::(0+:){0,6}))0*1$/.test(hostIp)) {
return true;
}
if (url.host === "localhost" || url.host.endsWith(".localhost")) {
return false;
}
if (url.protocol === "file:") {
return true;
}
return false;
}
function isUrlPotentiallyTrustworthy(url) {
if (/^about:(blank|srcdoc)$/.test(url)) {
return true;
}
if (url.protocol === "data:") {
return true;
}
if (/^(blob|filesystem):$/.test(url.protocol)) {
return true;
}
return isOriginPotentiallyTrustworthy(url);
}
function determineRequestsReferrer(request, { referrerURLCallback, referrerOriginCallback } = {}) {
if (request.referrer === "no-referrer" || request.referrerPolicy === "") {
return null;
}
const policy = request.referrerPolicy;
if (request.referrer === "about:client") {
return "no-referrer";
}
const referrerSource = request.referrer;
let referrerURL = stripURLForUseAsAReferrer(referrerSource);
let referrerOrigin = stripURLForUseAsAReferrer(referrerSource, true);
if (referrerURL.toString().length > 4096) {
referrerURL = referrerOrigin;
}
if (referrerURLCallback) {
referrerURL = referrerURLCallback(referrerURL);
}
if (referrerOriginCallback) {
referrerOrigin = referrerOriginCallback(referrerOrigin);
}
const currentURL = new URL(request.url);
switch (policy) {
case "no-referrer":
return "no-referrer";
case "origin":
return referrerOrigin;
case "unsafe-url":
return referrerURL;
case "strict-origin":
if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
return "no-referrer";
}
return referrerOrigin.toString();
case "strict-origin-when-cross-origin":
if (referrerURL.origin === currentURL.origin) {
return referrerURL;
}
if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
return "no-referrer";
}
return referrerOrigin;
case "same-origin":
if (referrerURL.origin === currentURL.origin) {
return referrerURL;
}
return "no-referrer";
case "origin-when-cross-origin":
if (referrerURL.origin === currentURL.origin) {
return referrerURL;
}
return referrerOrigin;
case "no-referrer-when-downgrade":
if (isUrlPotentiallyTrustworthy(referrerURL) && !isUrlPotentiallyTrustworthy(currentURL)) {
return "no-referrer";
}
return referrerURL;
default:
throw new TypeError(`Invalid referrerPolicy: ${policy}`);
}
}
function parseReferrerPolicyFromHeader(headers) {
const policyTokens = (headers.get("referrer-policy") || "").split(/[,\s]+/);
let policy = "";
for (const token of policyTokens) {
if (token && ReferrerPolicy.has(token)) {
policy = token;
}
}
return policy;
}
// ../../node_modules/node-fetch/src/request.js
var INTERNALS3 = Symbol("Request internals");
var isRequest = (object) => {
return typeof object === "object" && typeof object[INTERNALS3] === "object";
};
var doBadDataWarn = deprecate2(
() => {
},
".data is not a valid RequestInit property, use .body instead",
"https://github.com/node-fetch/node-fetch/issues/1000 (request)"
);
var Request = class _Request extends Body {
constructor(input, init = {}) {
let parsedURL;
if (isRequest(input)) {
parsedURL = new URL(input.url);
} else {
parsedURL = new URL(input);
input = {};
}
if (parsedURL.username !== "" || parsedURL.password !== "") {
throw new TypeError(`${parsedURL} is an url with embedded credentials.`);
}
let method = init.method || input.method || "GET";
if (/^(delete|get|head|options|post|put)$/i.test(method)) {
method = method.toUpperCase();
}
if (!isRequest(init) && "data" in init) {
doBadDataWarn();
}
if ((init.body != null || isRequest(input) && input.body !== null) && (method === "GET" || method === "HEAD")) {
throw new TypeError("Request with GET/HEAD method cannot have body");
}
const inputBody = init.body ? init.body : isRequest(input) && input.body !== null ? clone(input) : null;
super(inputBody, {
size: init.size || input.size || 0
});
const headers = new Headers(init.headers || input.headers || {});
if (inputBody !== null && !headers.has("Content-Type")) {
const contentType = extractContentType(inputBody, this);
if (contentType) {
headers.set("Content-Type", contentType);
}
}
let signal = isRequest(input) ? input.signal : null;
if ("signal" in init) {
signal = init.signal;
}
if (signal != null && !isAbortSignal(signal)) {
throw new TypeError("Expected signal to be an instanceof AbortSignal or EventTarget");
}
let referrer = init.referrer == null ? input.referrer : init.referrer;
if (referrer === "") {
referrer = "no-referrer";
} else if (referrer) {
const parsedReferrer = new URL(referrer);
referrer = /^about:(\/\/)?client$/.test(parsedReferrer) ? "client" : parsedReferrer;
} else {
referrer = void 0;
}
this[INTERNALS3] = {
method,
redirect: init.redirect || input.redirect || "follow",
headers,
parsedURL,
signal,
referrer
};
this.follow = init.follow === void 0 ? input.follow === void 0 ? 20 : input.follow : init.follow;
this.compress = init.compress === void 0 ? input.compress === void 0 ? true : input.compress : init.compress;
this.counter = init.counter || input.counter || 0;
this.agent = init.agent || input.agent;
this.highWaterMark = init.highWaterMark || input.highWaterMark || 16384;
this.insecureHTTPParser = init.insecureHTTPParser || input.insecureHTTPParser || false;
this.referrerPolicy = init.referrerPolicy || input.referrerPolicy || "";
}
/** @returns {string} */
get method() {
return this[INTERNALS3].method;
}
/** @returns {string} */
get url() {
return formatUrl(this[INTERNALS3].parsedURL);
}
/** @returns {Headers} */
get headers() {
return this[INTERNALS3].headers;
}
get redirect() {
return this[INTERNALS3].redirect;
}
/** @returns {AbortSignal} */
get signal() {
return this[INTERNALS3].signal;
}
// https://fetch.spec.whatwg.org/#dom-request-referrer
get referrer() {
if (this[INTERNALS3].referrer === "no-referrer") {
return "";
}
if (this[INTERNALS3].referrer === "client") {
return "about:client";
}
if (this[INTERNALS3].referrer) {
return this[INTERNALS3].referrer.toString();
}
return void 0;
}
get referrerPolicy() {
return this[INTERNALS3].referrerPolicy;
}
set referrerPolicy(referrerPolicy) {
this[INTERNALS3].referrerPolicy = validateReferrerPolicy(referrerPolicy);
}
/**
* Clone this request
*
* @return Request
*/
clone() {
return new _Request(this);
}
get [Symbol.toStringTag]() {
return "Request";
}
};
Object.defineProperties(Request.prototype, {
method: { enumerable: true },
url: { enumerable: true },
headers: { enumerable: true },
redirect: { enumerable: true },
clone: { enumerable: true },
signal: { enumerable: true },
referrer: { enumerable: true },
referrerPolicy: { enumerable: true }
});
var getNodeRequestOptions = (request) => {
const { parsedURL } = request[INTERNALS3];
const headers = new Headers(request[INTERNALS3].headers);
if (!headers.has("Accept")) {
headers.set("Accept", "*/*");
}
let contentLengthValue = null;
if (request.body === null && /^(post|put)$/i.test(request.method)) {
contentLengthValue = "0";
}
if (request.body !== null) {
const totalBytes = getTotalBytes(request);
if (typeof totalBytes === "number" && !Number.isNaN(totalBytes)) {
contentLengthValue = String(totalBytes);
}
}
if (contentLengthValue) {
headers.set("Content-Length", contentLengthValue);
}
if (request.referrerPolicy === "") {
request.referrerPolicy = DEFAULT_REFERRER_POLICY;
}
if (request.referrer && request.referrer !== "no-referrer") {
request[INTERNALS3].referrer = determineRequestsReferrer(request);
} else {
request[INTERNALS3].referrer = "no-referrer";
}
if (request[INTERNALS3].referrer instanceof URL) {
headers.set("Referer", request.referrer);
}
if (!headers.has("User-Agent")) {
headers.set("User-Agent", "node-fetch");
}
if (request.compress && !headers.has("Accept-Encoding")) {
headers.set("Accept-Encoding", "gzip, deflate, br");
}
let { agent: agent2 } = request;
if (typeof agent2 === "function") {
agent2 = agent2(parsedURL);
}
const search = getSearch(parsedURL);
const options = {
// Overwrite search to retain trailing ? (issue #776)
path: parsedURL.pathname + search,
// The following options are not expressed in the URL
method: request.method,
headers: headers[Symbol.for("nodejs.util.inspect.custom")](),
insecureHTTPParser: request.insecureHTTPParser,
agent: agent2
};
return {
/** @type {URL} */
parsedURL,
options
};
};
// ../../node_modules/node-fetch/src/errors/abort-error.js
var AbortError = class extends FetchBaseError {
constructor(message, type = "aborted") {
super(message, type);
}
};
// ../../node_modules/node-fetch/src/index.js
var supportedSchemas = /* @__PURE__ */ new Set(["data:", "http:", "https:"]);
async function fetch(url, options_) {
return new Promise((resolve, reject) => {
const request = new Request(url, options_);
const { parsedURL, options } = getNodeRequestOptions(request);
if (!supportedSchemas.has(parsedURL.protocol)) {
throw new TypeError(`node-fetch cannot load ${url