diff --git a/agents/codex.ts b/agents/codex.ts index 14676a4..3f2186f 100644 --- a/agents/codex.ts +++ b/agents/codex.ts @@ -62,7 +62,9 @@ ${mcpServerSections.join("\n\n")} `.trim() + "\n" ); - log.info(`» Codex config written to ${configPath} (shell: ${bash === "enabled" ? "enabled" : "disabled"})`); + log.info( + `» Codex config written to ${configPath} (shell: ${bash === "enabled" ? "enabled" : "disabled"})` + ); return codexDir; } diff --git a/entry b/entry index 6409ab0..bee291b 100755 --- a/entry +++ b/entry @@ -235,7 +235,7 @@ var require_file_command = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); exports.prepareKeyValueMessage = exports.issueFileCommand = void 0; var crypto2 = __importStar(__require("crypto")); - var fs4 = __importStar(__require("fs")); + var fs5 = __importStar(__require("fs")); var os2 = __importStar(__require("os")); var utils_1 = require_utils(); function issueFileCommand(command, message) { @@ -243,10 +243,10 @@ var require_file_command = __commonJS({ if (!filePath) { throw new Error(`Unable to find environment variable for file command ${command}`); } - if (!fs4.existsSync(filePath)) { + if (!fs5.existsSync(filePath)) { throw new Error(`Missing file at path: ${filePath}`); } - fs4.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os2.EOL}`, { + fs5.appendFileSync(filePath, `${(0, utils_1.toCommandValue)(message)}${os2.EOL}`, { encoding: "utf8" }); } @@ -451,7 +451,7 @@ var require_tunnel = __commonJS({ connectOptions.headers = connectOptions.headers || {}; connectOptions.headers["Proxy-Authorization"] = "Basic " + new Buffer(connectOptions.proxyAuth).toString("base64"); } - debug("making CONNECT request"); + debug2("making CONNECT request"); var connectReq = self2.request(connectOptions); connectReq.useChunkedEncodingByDefault = false; connectReq.once("response", onResponse); @@ -471,7 +471,7 @@ var require_tunnel = __commonJS({ connectReq.removeAllListeners(); socket.removeAllListeners(); if (res.statusCode !== 200) { - debug( + debug2( "tunneling socket could not be established, statusCode=%d", res.statusCode ); @@ -483,7 +483,7 @@ var require_tunnel = __commonJS({ return; } if (head.length > 0) { - debug("got illegal response body from proxy"); + debug2("got illegal response body from proxy"); socket.destroy(); var error50 = new Error("got illegal response body from proxy"); error50.code = "ECONNRESET"; @@ -491,13 +491,13 @@ var require_tunnel = __commonJS({ self2.removeSocket(placeholder); return; } - debug("tunneling connection has established"); + debug2("tunneling connection has established"); self2.sockets[self2.sockets.indexOf(placeholder)] = socket; return cb(socket); } function onError(cause) { connectReq.removeAllListeners(); - debug( + debug2( "tunneling socket could not be established, cause=%s\n", cause.message, cause.stack @@ -559,9 +559,9 @@ var require_tunnel = __commonJS({ } return target; } - var debug; + var debug2; if (process.env.NODE_DEBUG && /\btunnel\b/.test(process.env.NODE_DEBUG)) { - debug = function() { + debug2 = function() { var args3 = Array.prototype.slice.call(arguments); if (typeof args3[0] === "string") { args3[0] = "TUNNEL: " + args3[0]; @@ -571,10 +571,10 @@ var require_tunnel = __commonJS({ console.error.apply(console, args3); }; } else { - debug = function() { + debug2 = function() { }; } - exports.debug = debug; + exports.debug = debug2; } }); @@ -1049,14 +1049,14 @@ var require_util = __commonJS({ } const port = url4.port != null ? url4.port : url4.protocol === "https:" ? 443 : 80; let origin = url4.origin != null ? url4.origin : `${url4.protocol}//${url4.hostname}:${port}`; - let path3 = url4.path != null ? url4.path : `${url4.pathname || ""}${url4.search || ""}`; + let path4 = url4.path != null ? url4.path : `${url4.pathname || ""}${url4.search || ""}`; if (origin.endsWith("/")) { origin = origin.substring(0, origin.length - 1); } - if (path3 && !path3.startsWith("/")) { - path3 = `/${path3}`; + if (path4 && !path4.startsWith("/")) { + path4 = `/${path4}`; } - url4 = new URL(origin + path3); + url4 = new URL(origin + path4); } return url4; } @@ -2670,20 +2670,20 @@ var require_parseParams = __commonJS({ var require_basename = __commonJS({ "node_modules/.pnpm/@fastify+busboy@2.1.1/node_modules/@fastify/busboy/lib/utils/basename.js"(exports, module) { "use strict"; - module.exports = function basename(path3) { - if (typeof path3 !== "string") { + module.exports = function basename2(path4) { + if (typeof path4 !== "string") { return ""; } - for (var i = path3.length - 1; i >= 0; --i) { - switch (path3.charCodeAt(i)) { + for (var i = path4.length - 1; i >= 0; --i) { + switch (path4.charCodeAt(i)) { case 47: // '/' case 92: - path3 = path3.slice(i + 1); - return path3 === ".." || path3 === "." ? "" : path3; + path4 = path4.slice(i + 1); + return path4 === ".." || path4 === "." ? "" : path4; } } - return path3 === ".." || path3 === "." ? "" : path3; + return path4 === ".." || path4 === "." ? "" : path4; }; } }); @@ -2697,7 +2697,7 @@ var require_multipart = __commonJS({ var Dicer = require_Dicer(); var parseParams = require_parseParams(); var decodeText = require_decodeText(); - var basename = require_basename(); + var basename2 = require_basename(); var getLimit = require_getLimit(); var RE_BOUNDARY = /^boundary$/i; var RE_FIELD = /^form-data$/i; @@ -2814,7 +2814,7 @@ var require_multipart = __commonJS({ } else if (RE_FILENAME.test(parsed2[i][0])) { filename = parsed2[i][1]; if (!preservePath) { - filename = basename(filename); + filename = basename2(filename); } } } @@ -5713,7 +5713,7 @@ var require_request = __commonJS({ } var Request2 = class _Request { constructor(origin, { - path: path3, + path: path4, method, body, headers, @@ -5727,11 +5727,11 @@ var require_request = __commonJS({ throwOnError, expectContinue }, handler2) { - if (typeof path3 !== "string") { + if (typeof path4 !== "string") { throw new InvalidArgumentError("path must be a string"); - } else if (path3[0] !== "/" && !(path3.startsWith("http://") || path3.startsWith("https://")) && method !== "CONNECT") { + } else if (path4[0] !== "/" && !(path4.startsWith("http://") || path4.startsWith("https://")) && method !== "CONNECT") { throw new InvalidArgumentError("path must be an absolute URL or start with a slash"); - } else if (invalidPathRegex.exec(path3) !== null) { + } else if (invalidPathRegex.exec(path4) !== null) { throw new InvalidArgumentError("invalid request path"); } if (typeof method !== "string") { @@ -5794,7 +5794,7 @@ var require_request = __commonJS({ this.completed = false; this.aborted = false; this.upgrade = upgrade || null; - this.path = query2 ? util3.buildURL(path3, query2) : path3; + this.path = query2 ? util3.buildURL(path4, query2) : path4; this.origin = origin; this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent; this.blocking = blocking == null ? false : blocking; @@ -6802,9 +6802,9 @@ var require_RedirectHandler = __commonJS({ return this.handler.onHeaders(statusCode, headers, resume, statusText); } const { origin, pathname, search: search2 } = util3.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))); - const path3 = search2 ? `${pathname}${search2}` : pathname; + const path4 = search2 ? `${pathname}${search2}` : pathname; this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin); - this.opts.path = path3; + this.opts.path = path4; this.opts.origin = origin; this.opts.maxRedirections = 0; this.opts.query = null; @@ -8029,7 +8029,7 @@ var require_client = __commonJS({ if (client[kRunning] > 0 && util3.bodyLength(request2.body) !== 0 && (util3.isStream(request2.body) || util3.isAsyncIterable(request2.body))) { return; } - if (!request2.aborted && write(client, request2)) { + if (!request2.aborted && write2(client, request2)) { client[kPendingIdx]++; } else { client[kQueue].splice(client[kPendingIdx], 1); @@ -8039,12 +8039,12 @@ var require_client = __commonJS({ function shouldSendContentLength(method) { return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT"; } - function write(client, request2) { + function write2(client, request2) { if (client[kHTTPConnVersion] === "h2") { writeH2(client, client[kHTTP2Session], request2); return; } - const { body, method, path: path3, host, upgrade, headers, blocking, reset } = request2; + const { body, method, path: path4, host, upgrade, headers, blocking, reset } = request2; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH"; if (body && typeof body.read === "function") { body.read(0); @@ -8094,7 +8094,7 @@ var require_client = __commonJS({ if (blocking) { socket[kBlocking] = true; } - let header = `${method} ${path3} HTTP/1.1\r + let header = `${method} ${path4} HTTP/1.1\r `; if (typeof host === "string") { header += `host: ${host}\r @@ -8157,7 +8157,7 @@ upgrade: ${upgrade}\r return true; } function writeH2(client, session, request2) { - const { body, method, path: path3, host, upgrade, expectContinue, signal, headers: reqHeaders } = request2; + const { body, method, path: path4, host, upgrade, expectContinue, signal, headers: reqHeaders } = request2; let headers; if (typeof reqHeaders === "string") headers = Request2[kHTTP2CopyHeaders](reqHeaders.trim()); else headers = reqHeaders; @@ -8200,7 +8200,7 @@ upgrade: ${upgrade}\r }); return true; } - headers[HTTP2_HEADER_PATH] = path3; + headers[HTTP2_HEADER_PATH] = path4; headers[HTTP2_HEADER_SCHEME] = "https"; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH"; if (body && typeof body.read === "function") { @@ -10440,20 +10440,20 @@ var require_mock_utils = __commonJS({ } return true; } - function safeUrl(path3) { - if (typeof path3 !== "string") { - return path3; + function safeUrl(path4) { + if (typeof path4 !== "string") { + return path4; } - const pathSegments = path3.split("?"); + const pathSegments = path4.split("?"); if (pathSegments.length !== 2) { - return path3; + return path4; } const qp = new URLSearchParams(pathSegments.pop()); qp.sort(); return [...pathSegments, qp.toString()].join("?"); } - function matchKey(mockDispatch2, { path: path3, method, body, headers }) { - const pathMatch = matchValue(mockDispatch2.path, path3); + function matchKey(mockDispatch2, { path: path4, method, body, headers }) { + const pathMatch = matchValue(mockDispatch2.path, path4); const methodMatch = matchValue(mockDispatch2.method, method); const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true; const headersMatch = matchHeaders(mockDispatch2, headers); @@ -10471,7 +10471,7 @@ var require_mock_utils = __commonJS({ function getMockDispatch(mockDispatches, key) { const basePath = key.query ? buildURL(key.path, key.query) : key.path; const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath; - let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path3 }) => matchValue(safeUrl(path3), resolvedPath)); + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path4 }) => matchValue(safeUrl(path4), resolvedPath)); if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`); } @@ -10508,9 +10508,9 @@ var require_mock_utils = __commonJS({ } } function buildKey(opts) { - const { path: path3, method, body, headers, query: query2 } = opts; + const { path: path4, method, body, headers, query: query2 } = opts; return { - path: path3, + path: path4, method, body, headers, @@ -10959,10 +10959,10 @@ var require_pending_interceptors_formatter = __commonJS({ } format(pendingInterceptors) { const withPrettyHeaders = pendingInterceptors.map( - ({ method, path: path3, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + ({ method, path: path4, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ Method: method, Origin: origin, - Path: path3, + Path: path4, "Status code": statusCode, Persistent: persist ? "\u2705" : "\u274C", Invocations: timesInvoked, @@ -15582,8 +15582,8 @@ var require_util6 = __commonJS({ } } } - function validateCookiePath(path3) { - for (const char of path3) { + function validateCookiePath(path4) { + for (const char of path4) { const code = char.charCodeAt(0); if (code < 33 || char === ";") { throw new Error("Invalid cookie path"); @@ -17106,9 +17106,9 @@ var require_websocket = __commonJS({ response.socket.ws = this; this[kByteParser] = parser; this[kReadyState] = states.OPEN; - const extensions = response.headersList.get("sec-websocket-extensions"); - if (extensions !== null) { - this.#extensions = extensions; + const extensions2 = response.headersList.get("sec-websocket-extensions"); + if (extensions2 !== null) { + this.#extensions = extensions2; } const protocol = response.headersList.get("sec-websocket-protocol"); if (protocol !== null) { @@ -17263,11 +17263,11 @@ var require_undici = __commonJS({ if (typeof opts.path !== "string") { throw new InvalidArgumentError("invalid opts.path"); } - let path3 = opts.path; + let path4 = opts.path; if (!opts.path.startsWith("/")) { - path3 = `/${path3}`; + path4 = `/${path4}`; } - url4 = new URL(util3.parseOrigin(url4).origin + path3); + url4 = new URL(util3.parseOrigin(url4).origin + path4); } else { if (!opts) { opts = typeof url4 === "object" ? url4 : {}; @@ -18490,7 +18490,7 @@ var require_path_utils = __commonJS({ }; Object.defineProperty(exports, "__esModule", { value: true }); exports.toPlatformPath = exports.toWin32Path = exports.toPosixPath = void 0; - var path3 = __importStar(__require("path")); + var path4 = __importStar(__require("path")); function toPosixPath(pth) { return pth.replace(/[\\]/g, "/"); } @@ -18500,7 +18500,7 @@ var require_path_utils = __commonJS({ } exports.toWin32Path = toWin32Path; function toPlatformPath(pth) { - return pth.replace(/[/\\]/g, path3.sep); + return pth.replace(/[/\\]/g, path4.sep); } exports.toPlatformPath = toPlatformPath; } @@ -18563,12 +18563,12 @@ var require_io_util = __commonJS({ var _a2; Object.defineProperty(exports, "__esModule", { value: true }); exports.getCmdPath = exports.tryGetExecutablePath = exports.isRooted = exports.isDirectory = exports.exists = exports.READONLY = exports.UV_FS_O_EXLOCK = exports.IS_WINDOWS = exports.unlink = exports.symlink = exports.stat = exports.rmdir = exports.rm = exports.rename = exports.readlink = exports.readdir = exports.open = exports.mkdir = exports.lstat = exports.copyFile = exports.chmod = void 0; - var fs4 = __importStar(__require("fs")); - var path3 = __importStar(__require("path")); - _a2 = fs4.promises, exports.chmod = _a2.chmod, exports.copyFile = _a2.copyFile, exports.lstat = _a2.lstat, exports.mkdir = _a2.mkdir, exports.open = _a2.open, exports.readdir = _a2.readdir, exports.readlink = _a2.readlink, exports.rename = _a2.rename, exports.rm = _a2.rm, exports.rmdir = _a2.rmdir, exports.stat = _a2.stat, exports.symlink = _a2.symlink, exports.unlink = _a2.unlink; + var fs5 = __importStar(__require("fs")); + var path4 = __importStar(__require("path")); + _a2 = fs5.promises, exports.chmod = _a2.chmod, exports.copyFile = _a2.copyFile, exports.lstat = _a2.lstat, exports.mkdir = _a2.mkdir, exports.open = _a2.open, exports.readdir = _a2.readdir, exports.readlink = _a2.readlink, exports.rename = _a2.rename, exports.rm = _a2.rm, exports.rmdir = _a2.rmdir, exports.stat = _a2.stat, exports.symlink = _a2.symlink, exports.unlink = _a2.unlink; exports.IS_WINDOWS = process.platform === "win32"; exports.UV_FS_O_EXLOCK = 268435456; - exports.READONLY = fs4.constants.O_RDONLY; + exports.READONLY = fs5.constants.O_RDONLY; function exists(fsPath) { return __awaiter(this, void 0, void 0, function* () { try { @@ -18601,7 +18601,7 @@ var require_io_util = __commonJS({ return p.startsWith("/"); } exports.isRooted = isRooted; - function tryGetExecutablePath(filePath, extensions) { + function tryGetExecutablePath(filePath, extensions2) { return __awaiter(this, void 0, void 0, function* () { let stats = void 0; try { @@ -18613,8 +18613,8 @@ var require_io_util = __commonJS({ } if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { - const upperExt = path3.extname(filePath).toUpperCase(); - if (extensions.some((validExt) => validExt.toUpperCase() === upperExt)) { + const upperExt = path4.extname(filePath).toUpperCase(); + if (extensions2.some((validExt) => validExt.toUpperCase() === upperExt)) { return filePath; } } else { @@ -18624,7 +18624,7 @@ var require_io_util = __commonJS({ } } const originalFilePath = filePath; - for (const extension of extensions) { + for (const extension of extensions2) { filePath = originalFilePath + extension; stats = void 0; try { @@ -18637,11 +18637,11 @@ var require_io_util = __commonJS({ if (stats && stats.isFile()) { if (exports.IS_WINDOWS) { try { - const directory = path3.dirname(filePath); - const upperName = path3.basename(filePath).toUpperCase(); + const directory = path4.dirname(filePath); + const upperName = path4.basename(filePath).toUpperCase(); for (const actualName of yield exports.readdir(directory)) { if (upperName === actualName.toUpperCase()) { - filePath = path3.join(directory, actualName); + filePath = path4.join(directory, actualName); break; } } @@ -18736,7 +18736,7 @@ var require_io = __commonJS({ Object.defineProperty(exports, "__esModule", { value: true }); exports.findInPath = exports.which = exports.mkdirP = exports.rmRF = exports.mv = exports.cp = void 0; var assert_1 = __require("assert"); - var path3 = __importStar(__require("path")); + var path4 = __importStar(__require("path")); var ioUtil = __importStar(require_io_util()); function cp(source, dest, options = {}) { return __awaiter(this, void 0, void 0, function* () { @@ -18745,7 +18745,7 @@ var require_io = __commonJS({ if (destStat && destStat.isFile() && !force) { return; } - const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path3.join(dest, path3.basename(source)) : dest; + const newDest = destStat && destStat.isDirectory() && copySourceDirectory ? path4.join(dest, path4.basename(source)) : dest; if (!(yield ioUtil.exists(source))) { throw new Error(`no such file or directory: ${source}`); } @@ -18757,7 +18757,7 @@ var require_io = __commonJS({ yield cpDirRecursive(source, newDest, 0, force); } } else { - if (path3.relative(source, newDest) === "") { + if (path4.relative(source, newDest) === "") { throw new Error(`'${newDest}' and '${source}' are the same file`); } yield copyFile(source, newDest, force); @@ -18770,7 +18770,7 @@ var require_io = __commonJS({ if (yield ioUtil.exists(dest)) { let destExists = true; if (yield ioUtil.isDirectory(dest)) { - dest = path3.join(dest, path3.basename(source)); + dest = path4.join(dest, path4.basename(source)); destExists = yield ioUtil.exists(dest); } if (destExists) { @@ -18781,7 +18781,7 @@ var require_io = __commonJS({ } } } - yield mkdirP(path3.dirname(dest)); + yield mkdirP(path4.dirname(dest)); yield ioUtil.rename(source, dest); }); } @@ -18842,27 +18842,27 @@ var require_io = __commonJS({ if (!tool2) { throw new Error("parameter 'tool' is required"); } - const extensions = []; + const extensions2 = []; if (ioUtil.IS_WINDOWS && process.env["PATHEXT"]) { - for (const extension of process.env["PATHEXT"].split(path3.delimiter)) { + for (const extension of process.env["PATHEXT"].split(path4.delimiter)) { if (extension) { - extensions.push(extension); + extensions2.push(extension); } } } if (ioUtil.isRooted(tool2)) { - const filePath = yield ioUtil.tryGetExecutablePath(tool2, extensions); + const filePath = yield ioUtil.tryGetExecutablePath(tool2, extensions2); if (filePath) { return [filePath]; } return []; } - if (tool2.includes(path3.sep)) { + if (tool2.includes(path4.sep)) { return []; } const directories = []; if (process.env.PATH) { - for (const p of process.env.PATH.split(path3.delimiter)) { + for (const p of process.env.PATH.split(path4.delimiter)) { if (p) { directories.push(p); } @@ -18870,7 +18870,7 @@ var require_io = __commonJS({ } const matches = []; for (const directory of directories) { - const filePath = yield ioUtil.tryGetExecutablePath(path3.join(directory, tool2), extensions); + const filePath = yield ioUtil.tryGetExecutablePath(path4.join(directory, tool2), extensions2); if (filePath) { matches.push(filePath); } @@ -18986,7 +18986,7 @@ var require_toolrunner = __commonJS({ var os2 = __importStar(__require("os")); var events = __importStar(__require("events")); var child = __importStar(__require("child_process")); - var path3 = __importStar(__require("path")); + var path4 = __importStar(__require("path")); var io = __importStar(require_io()); var ioUtil = __importStar(require_io_util()); var timers_1 = __require("timers"); @@ -19201,7 +19201,7 @@ var require_toolrunner = __commonJS({ exec() { return __awaiter(this, void 0, void 0, function* () { if (!ioUtil.isRooted(this.toolPath) && (this.toolPath.includes("/") || IS_WINDOWS && this.toolPath.includes("\\"))) { - this.toolPath = path3.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); + this.toolPath = path4.resolve(process.cwd(), this.options.cwd || process.cwd(), this.toolPath); } this.toolPath = yield io.which(this.toolPath, true); return new Promise((resolve2, reject) => __awaiter(this, void 0, void 0, function* () { @@ -19701,7 +19701,7 @@ var require_core = __commonJS({ var file_command_1 = require_file_command(); var utils_1 = require_utils(); var os2 = __importStar(__require("os")); - var path3 = __importStar(__require("path")); + var path4 = __importStar(__require("path")); var oidc_utils_1 = require_oidc_utils(); var ExitCode; (function(ExitCode2) { @@ -19729,7 +19729,7 @@ var require_core = __commonJS({ } else { (0, command_1.issueCommand)("add-path", {}, inputPath); } - process.env["PATH"] = `${inputPath}${path3.delimiter}${process.env["PATH"]}`; + process.env["PATH"] = `${inputPath}${path4.delimiter}${process.env["PATH"]}`; } exports.addPath = addPath; function getInput2(name, options) { @@ -19785,10 +19785,10 @@ Support boolean input list: \`true | True | TRUE | false | False | FALSE\``); return process.env["RUNNER_DEBUG"] === "1"; } exports.isDebug = isDebug2; - function debug(message) { + function debug2(message) { (0, command_1.issueCommand)("debug", {}, message); } - exports.debug = debug; + exports.debug = debug2; function error50(message, properties = {}) { (0, command_1.issueCommand)("error", (0, utils_1.toCommandProperties)(properties), message instanceof Error ? message.toString() : message); } @@ -20271,8 +20271,8 @@ var init_parseUtil = __esm({ init_errors(); init_en(); makeIssue = (params) => { - const { data, path: path3, errorMaps, issueData } = params; - const fullPath = [...path3, ...issueData.path || []]; + const { data, path: path4, errorMaps, issueData } = params; + const fullPath = [...path4, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath @@ -20552,11 +20552,11 @@ var init_types = __esm({ init_parseUtil(); init_util(); ParseInputLazyPath = class { - constructor(parent, value2, path3, key) { + constructor(parent, value2, path4, key) { this._cachedPath = []; this.parent = parent; this.data = value2; - this._path = path3; + this._path = path4; this._key = key; } get path() { @@ -24062,10 +24062,10 @@ function mergeDefs(...defs) { function cloneDef(schema2) { return mergeDefs(schema2._zod.def); } -function getElementAtPath(obj, path3) { - if (!path3) +function getElementAtPath(obj, path4) { + if (!path4) return obj; - return path3.reduce((acc, key) => acc?.[key], obj); + return path4.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject(promisesObj) { const keys = Object.keys(promisesObj); @@ -24377,11 +24377,11 @@ function aborted(x, startIndex = 0) { } return false; } -function prefixIssues(path3, issues) { +function prefixIssues(path4, issues) { return issues.map((iss) => { var _a2; (_a2 = iss).path ?? (_a2.path = []); - iss.path.unshift(path3); + iss.path.unshift(path4); return iss; }); } @@ -24623,7 +24623,7 @@ function formatError(error50, mapper = (issue4) => issue4.message) { } function treeifyError(error50, mapper = (issue4) => issue4.message) { const result = { errors: [] }; - const processError = (error51, path3 = []) => { + const processError = (error51, path4 = []) => { var _a2, _b; for (const issue4 of error51.issues) { if (issue4.code === "invalid_union" && issue4.errors.length) { @@ -24633,7 +24633,7 @@ function treeifyError(error50, mapper = (issue4) => issue4.message) { } else if (issue4.code === "invalid_element") { processError({ issues: issue4.issues }, issue4.path); } else { - const fullpath = [...path3, ...issue4.path]; + const fullpath = [...path4, ...issue4.path]; if (fullpath.length === 0) { result.errors.push(mapper(issue4)); continue; @@ -24665,8 +24665,8 @@ function treeifyError(error50, mapper = (issue4) => issue4.message) { } function toDotPath(_path) { const segs = []; - const path3 = _path.map((seg) => typeof seg === "object" ? seg.key : seg); - for (const seg of path3) { + const path4 = _path.map((seg) => typeof seg === "object" ? seg.key : seg); + for (const seg of path4) { if (typeof seg === "number") segs.push(`[${seg}]`); else if (typeof seg === "symbol") @@ -40723,8 +40723,8 @@ var require_utils3 = __commonJS({ } return ind; } - function removeDotSegments(path3) { - let input = path3; + function removeDotSegments(path4) { + let input = path4; const output = []; let nextSlash = -1; let len = 0; @@ -40923,8 +40923,8 @@ var require_schemes = __commonJS({ wsComponent.secure = void 0; } if (wsComponent.resourceName) { - const [path3, query2] = wsComponent.resourceName.split("?"); - wsComponent.path = path3 && path3 !== "/" ? path3 : void 0; + const [path4, query2] = wsComponent.resourceName.split("?"); + wsComponent.path = path4 && path4 !== "/" ? path4 : void 0; wsComponent.query = query2; wsComponent.resourceName = void 0; } @@ -44277,12 +44277,12 @@ var require_dist = __commonJS({ throw new Error(`Unknown format "${name}"`); return f; }; - function addFormats(ajv, list, fs4, exportName) { + function addFormats(ajv, list, fs5, exportName) { var _a2; var _b; (_a2 = (_b = ajv.opts.code).formats) !== null && _a2 !== void 0 ? _a2 : _b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`; for (const f of list) - ajv.addFormat(f, fs4[f]); + ajv.addFormat(f, fs5[f]); } module.exports = exports = formatsPlugin; Object.defineProperty(exports, "__esModule", { value: true }); @@ -44701,7 +44701,7 @@ var require_errors4 = __commonJS({ } }; var kAbortError = Symbol.for("undici.error.UND_ERR_ABORT"); - var AbortError2 = class extends UndiciError { + var AbortError3 = class extends UndiciError { constructor(message) { super(message); this.name = "AbortError"; @@ -44716,7 +44716,7 @@ var require_errors4 = __commonJS({ } }; var kRequestAbortedError = Symbol.for("undici.error.UND_ERR_ABORTED"); - var RequestAbortedError = class extends AbortError2 { + var RequestAbortedError = class extends AbortError3 { constructor(message) { super(message); this.name = "AbortError"; @@ -44949,7 +44949,7 @@ var require_errors4 = __commonJS({ } }; module.exports = { - AbortError: AbortError2, + AbortError: AbortError3, HTTPParserError, UndiciError, HeadersTimeoutError, @@ -45364,14 +45364,14 @@ var require_util10 = __commonJS({ } const port = url4.port != null ? url4.port : url4.protocol === "https:" ? 443 : 80; let origin = url4.origin != null ? url4.origin : `${url4.protocol || ""}//${url4.hostname || ""}:${port}`; - let path3 = url4.path != null ? url4.path : `${url4.pathname || ""}${url4.search || ""}`; + let path4 = url4.path != null ? url4.path : `${url4.pathname || ""}${url4.search || ""}`; if (origin[origin.length - 1] === "/") { origin = origin.slice(0, origin.length - 1); } - if (path3 && path3[0] !== "/") { - path3 = `/${path3}`; + if (path4 && path4[0] !== "/") { + path4 = `/${path4}`; } - return new URL(`${origin}${path3}`); + return new URL(`${origin}${path4}`); } if (!isHttpOrHttpsPrefixed(url4.origin || url4.protocol)) { throw new InvalidArgumentError("Invalid URL protocol: the URL must start with `http:` or `https:`."); @@ -45932,9 +45932,9 @@ var require_diagnostics = __commonJS({ "undici:client:sendHeaders", (evt) => { const { - request: { method, path: path3, origin } + request: { method, path: path4, origin } } = evt; - debugLog("sending request to %s %s%s", method, origin, path3); + debugLog("sending request to %s %s%s", method, origin, path4); } ); } @@ -45948,14 +45948,14 @@ var require_diagnostics = __commonJS({ "undici:request:headers", (evt) => { const { - request: { method, path: path3, origin }, + request: { method, path: path4, origin }, response: { statusCode } } = evt; debugLog( "received response to %s %s%s - HTTP %d", method, origin, - path3, + path4, statusCode ); } @@ -45964,23 +45964,23 @@ var require_diagnostics = __commonJS({ "undici:request:trailers", (evt) => { const { - request: { method, path: path3, origin } + request: { method, path: path4, origin } } = evt; - debugLog("trailers received from %s %s%s", method, origin, path3); + debugLog("trailers received from %s %s%s", method, origin, path4); } ); diagnosticsChannel.subscribe( "undici:request:error", (evt) => { const { - request: { method, path: path3, origin }, + request: { method, path: path4, origin }, error: error50 } = evt; debugLog( "request to %s %s%s errored - %s", method, origin, - path3, + path4, error50.message ); } @@ -46076,7 +46076,7 @@ var require_request3 = __commonJS({ var kHandler = Symbol("handler"); var Request2 = class { constructor(origin, { - path: path3, + path: path4, method, body, headers, @@ -46092,11 +46092,11 @@ var require_request3 = __commonJS({ throwOnError, maxRedirections }, handler2) { - if (typeof path3 !== "string") { + if (typeof path4 !== "string") { throw new InvalidArgumentError("path must be a string"); - } else if (path3[0] !== "/" && !(path3.startsWith("http://") || path3.startsWith("https://")) && method !== "CONNECT") { + } else if (path4[0] !== "/" && !(path4.startsWith("http://") || path4.startsWith("https://")) && method !== "CONNECT") { throw new InvalidArgumentError("path must be an absolute URL or start with a slash"); - } else if (invalidPathRegex.test(path3)) { + } else if (invalidPathRegex.test(path4)) { throw new InvalidArgumentError("invalid request path"); } if (typeof method !== "string") { @@ -46164,7 +46164,7 @@ var require_request3 = __commonJS({ this.completed = false; this.aborted = false; this.upgrade = upgrade || null; - this.path = query2 ? serializePathWithQuery(path3, query2) : path3; + this.path = query2 ? serializePathWithQuery(path4, query2) : path4; this.origin = origin; this.protocol = getProtocolFromUrlString(origin); this.idempotent = idempotent == null ? method === "HEAD" || method === "GET" : idempotent; @@ -50971,7 +50971,7 @@ var require_client_h1 = __commonJS({ return method !== "GET" && method !== "HEAD" && method !== "OPTIONS" && method !== "TRACE" && method !== "CONNECT"; } function writeH1(client, request2) { - const { method, path: path3, host, upgrade, blocking, reset } = request2; + const { method, path: path4, host, upgrade, blocking, reset } = request2; let { body, headers, contentLength } = request2; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH" || method === "QUERY" || method === "PROPFIND" || method === "PROPPATCH"; if (util3.isFormDataLike(body)) { @@ -51037,7 +51037,7 @@ var require_client_h1 = __commonJS({ if (blocking) { socket[kBlocking] = true; } - let header = `${method} ${path3} HTTP/1.1\r + let header = `${method} ${path4} HTTP/1.1\r `; if (typeof host === "string") { header += `host: ${host}\r @@ -51594,7 +51594,7 @@ var require_client_h2 = __commonJS({ function writeH2(client, request2) { const requestTimeout = request2.bodyTimeout ?? client[kBodyTimeout]; const session = client[kHTTP2Session]; - const { method, path: path3, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request2; + const { method, path: path4, host, upgrade, expectContinue, signal, protocol, headers: reqHeaders } = request2; let { body } = request2; if (upgrade) { util3.errorRequest(client, request2, new Error("Upgrade not supported for H2")); @@ -51673,7 +51673,7 @@ var require_client_h2 = __commonJS({ stream.setTimeout(requestTimeout); return true; } - headers[HTTP2_HEADER_PATH] = path3; + headers[HTTP2_HEADER_PATH] = path4; headers[HTTP2_HEADER_SCHEME] = protocol === "http:" ? "http" : "https"; const expectsPayload = method === "PUT" || method === "POST" || method === "PATCH"; if (body && typeof body.read === "function") { @@ -53145,10 +53145,10 @@ var require_proxy_agent2 = __commonJS({ }; const { origin, - path: path3 = "/", + path: path4 = "/", headers = {} } = opts; - opts.path = origin + path3; + opts.path = origin + path4; if (!("host" in headers) && !("Host" in headers)) { const { host } = new URL(origin); headers.host = host; @@ -53883,7 +53883,7 @@ var require_readable2 = __commonJS({ "use strict"; var assert4 = __require("node:assert"); var { Readable } = __require("node:stream"); - var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError: AbortError2 } = require_errors4(); + var { RequestAbortedError, NotSupportedError, InvalidArgumentError, AbortError: AbortError3 } = require_errors4(); var util3 = require_util10(); var { ReadableStreamFrom } = require_util10(); var kConsume = Symbol("kConsume"); @@ -54094,24 +54094,24 @@ var require_readable2 = __commonJS({ } const limit = opts?.limit && Number.isFinite(opts.limit) ? opts.limit : 128 * 1024; if (signal?.aborted) { - return Promise.reject(signal.reason ?? new AbortError2()); + return Promise.reject(signal.reason ?? new AbortError3()); } if (this._readableState.closeEmitted) { return Promise.resolve(null); } return new Promise((resolve2, reject) => { if (this[kContentLength] && this[kContentLength] > limit || this[kBytesRead] > limit) { - this.destroy(new AbortError2()); + this.destroy(new AbortError3()); } if (signal) { const onAbort = () => { - this.destroy(signal.reason ?? new AbortError2()); + this.destroy(signal.reason ?? new AbortError3()); }; signal.addEventListener("abort", onAbort); this.on("close", function() { signal.removeEventListener("abort", onAbort); if (signal.aborted) { - reject(signal.reason ?? new AbortError2()); + reject(signal.reason ?? new AbortError3()); } else { resolve2(null); } @@ -55234,20 +55234,20 @@ var require_mock_utils2 = __commonJS({ } return normalizedQp; } - function safeUrl(path3) { - if (typeof path3 !== "string") { - return path3; + function safeUrl(path4) { + if (typeof path4 !== "string") { + return path4; } - const pathSegments = path3.split("?", 3); + const pathSegments = path4.split("?", 3); if (pathSegments.length !== 2) { - return path3; + return path4; } const qp = new URLSearchParams(pathSegments.pop()); qp.sort(); return [...pathSegments, qp.toString()].join("?"); } - function matchKey(mockDispatch2, { path: path3, method, body, headers }) { - const pathMatch = matchValue(mockDispatch2.path, path3); + function matchKey(mockDispatch2, { path: path4, method, body, headers }) { + const pathMatch = matchValue(mockDispatch2.path, path4); const methodMatch = matchValue(mockDispatch2.method, method); const bodyMatch = typeof mockDispatch2.body !== "undefined" ? matchValue(mockDispatch2.body, body) : true; const headersMatch = matchHeaders(mockDispatch2, headers); @@ -55272,8 +55272,8 @@ var require_mock_utils2 = __commonJS({ const basePath = key.query ? serializePathWithQuery(key.path, key.query) : key.path; const resolvedPath = typeof basePath === "string" ? safeUrl(basePath) : basePath; const resolvedPathWithoutTrailingSlash = removeTrailingSlash(resolvedPath); - let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path3, ignoreTrailingSlash }) => { - return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path3)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path3), resolvedPath); + let matchedMockDispatches = mockDispatches.filter(({ consumed }) => !consumed).filter(({ path: path4, ignoreTrailingSlash }) => { + return ignoreTrailingSlash ? matchValue(removeTrailingSlash(safeUrl(path4)), resolvedPathWithoutTrailingSlash) : matchValue(safeUrl(path4), resolvedPath); }); if (matchedMockDispatches.length === 0) { throw new MockNotMatchedError(`Mock dispatch not matched for path '${resolvedPath}'`); @@ -55311,19 +55311,19 @@ var require_mock_utils2 = __commonJS({ mockDispatches.splice(index, 1); } } - function removeTrailingSlash(path3) { - while (path3.endsWith("/")) { - path3 = path3.slice(0, -1); + function removeTrailingSlash(path4) { + while (path4.endsWith("/")) { + path4 = path4.slice(0, -1); } - if (path3.length === 0) { - path3 = "/"; + if (path4.length === 0) { + path4 = "/"; } - return path3; + return path4; } function buildKey(opts) { - const { path: path3, method, body, headers, query: query2 } = opts; + const { path: path4, method, body, headers, query: query2 } = opts; return { - path: path3, + path: path4, method, body, headers, @@ -55981,10 +55981,10 @@ var require_pending_interceptors_formatter2 = __commonJS({ } format(pendingInterceptors) { const withPrettyHeaders = pendingInterceptors.map( - ({ method, path: path3, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ + ({ method, path: path4, data: { statusCode }, persist, times, timesInvoked, origin }) => ({ Method: method, Origin: origin, - Path: path3, + Path: path4, "Status code": statusCode, Persistent: persist ? PERSISTENT : NOT_PERSISTENT, Invocations: timesInvoked, @@ -56064,9 +56064,9 @@ var require_mock_agent2 = __commonJS({ const acceptNonStandardSearchParameters = this[kMockAgentAcceptsNonStandardSearchParameters]; const dispatchOpts = { ...opts }; if (acceptNonStandardSearchParameters && dispatchOpts.path) { - const [path3, searchParams] = dispatchOpts.path.split("?"); + const [path4, searchParams] = dispatchOpts.path.split("?"); const normalizedSearchParams = normalizeSearchParams(searchParams, acceptNonStandardSearchParameters); - dispatchOpts.path = `${path3}?${normalizedSearchParams}`; + dispatchOpts.path = `${path4}?${normalizedSearchParams}`; } return this[kAgent].dispatch(dispatchOpts, handler2); } @@ -56463,12 +56463,12 @@ var require_snapshot_recorder = __commonJS({ * @return {Promise} - Resolves when snapshots are loaded */ async loadSnapshots(filePath) { - const path3 = filePath || this.#snapshotPath; - if (!path3) { + const path4 = filePath || this.#snapshotPath; + if (!path4) { throw new InvalidArgumentError("Snapshot path is required"); } try { - const data = await readFile(resolve2(path3), "utf8"); + const data = await readFile(resolve2(path4), "utf8"); const parsed2 = JSON.parse(data); if (Array.isArray(parsed2)) { this.#snapshots.clear(); @@ -56482,7 +56482,7 @@ var require_snapshot_recorder = __commonJS({ if (error50.code === "ENOENT") { this.#snapshots.clear(); } else { - throw new UndiciError(`Failed to load snapshots from ${path3}`, { cause: error50 }); + throw new UndiciError(`Failed to load snapshots from ${path4}`, { cause: error50 }); } } } @@ -56493,11 +56493,11 @@ var require_snapshot_recorder = __commonJS({ * @returns {Promise} - Resolves when snapshots are saved */ async saveSnapshots(filePath) { - const path3 = filePath || this.#snapshotPath; - if (!path3) { + const path4 = filePath || this.#snapshotPath; + if (!path4) { throw new InvalidArgumentError("Snapshot path is required"); } - const resolvedPath = resolve2(path3); + const resolvedPath = resolve2(path4); await mkdir(dirname2(resolvedPath), { recursive: true }); const data = Array.from(this.#snapshots.entries()).map(([hash2, snapshot2]) => ({ hash: hash2, @@ -57123,15 +57123,15 @@ var require_redirect_handler = __commonJS({ return; } const { origin, pathname, search: search2 } = util3.parseURL(new URL(this.location, this.opts.origin && new URL(this.opts.path, this.opts.origin))); - const path3 = search2 ? `${pathname}${search2}` : pathname; - const redirectUrlString = `${origin}${path3}`; + const path4 = search2 ? `${pathname}${search2}` : pathname; + const redirectUrlString = `${origin}${path4}`; for (const historyUrl of this.history) { if (historyUrl.toString() === redirectUrlString) { throw new InvalidArgumentError(`Redirect loop detected. Cannot redirect to ${origin}. This typically happens when using a Client or Pool with cross-origin redirects. Use an Agent for cross-origin redirects.`); } } this.opts.headers = cleanRequestHeaders(this.opts.headers, statusCode === 303, this.opts.origin !== origin); - this.opts.path = path3; + this.opts.path = path4; this.opts.origin = origin; this.opts.query = null; } @@ -59071,7 +59071,7 @@ var require_cache3 = __commonJS({ var MemoryCacheStore = require_memory_cache_store(); var CacheRevalidationHandler = require_cache_revalidation_handler(); var { assertCacheStore, assertCacheMethods, makeCacheKey, normalizeHeaders, parseCacheControlHeader } = require_cache2(); - var { AbortError: AbortError2 } = require_errors4(); + var { AbortError: AbortError3 } = require_errors4(); function needsRevalidation(result, cacheControlDirectives) { if (cacheControlDirectives?.["no-cache"]) { return true; @@ -59155,7 +59155,7 @@ var require_cache3 = __commonJS({ return stream.errored; }, abort(reason) { - stream.destroy(reason ?? new AbortError2()); + stream.destroy(reason ?? new AbortError3()); } }; stream.on("error", function(err) { @@ -63522,9 +63522,9 @@ var require_util13 = __commonJS({ } } } - function validateCookiePath(path3) { - for (let i = 0; i < path3.length; ++i) { - const code = path3.charCodeAt(i); + function validateCookiePath(path4) { + for (let i = 0; i < path4.length; ++i) { + const code = path4.charCodeAt(i); if (code < 32 || // exclude CTLs (0-31) code === 127 || // DEL code === 59) { @@ -64312,11 +64312,11 @@ var require_util14 = __commonJS({ function isValidOpcode(opcode) { return isTextBinaryFrame(opcode) || isContinuationFrame(opcode) || isControlFrame(opcode); } - function parseExtensions(extensions) { + function parseExtensions(extensions2) { const position = { position: 0 }; const extensionList = /* @__PURE__ */ new Map(); - while (position.position < extensions.length) { - const pair = collectASequenceOfCodePointsFast(";", extensions, position); + while (position.position < extensions2.length) { + const pair = collectASequenceOfCodePointsFast(";", extensions2, position); const [name, value2 = ""] = pair.split("=", 2); extensionList.set( removeHTTPWhitespace(name, true, false), @@ -64588,10 +64588,10 @@ var require_connection2 = __commonJS({ return; } const secExtension = response.headersList.get("Sec-WebSocket-Extensions"); - let extensions; + let extensions2; if (secExtension !== null) { - extensions = parseExtensions(secExtension); - if (!extensions.has("permessage-deflate")) { + extensions2 = parseExtensions(secExtension); + if (!extensions2.has("permessage-deflate")) { failWebsocketConnection(handler2, 1002, "Sec-WebSocket-Extensions header does not match."); return; } @@ -64608,7 +64608,7 @@ var require_connection2 = __commonJS({ response.socket.on("close", handler2.onSocketClose); response.socket.on("error", handler2.onSocketError); handler2.wasEverConnected = true; - handler2.onConnectionEstablished(response, extensions); + handler2.onConnectionEstablished(response, extensions2); } }); return controller; @@ -64678,9 +64678,9 @@ var require_permessage_deflate = __commonJS({ /** @type {import('node:zlib').InflateRaw} */ #inflate; #options = {}; - constructor(extensions) { - this.#options.serverNoContextTakeover = extensions.has("server_no_context_takeover"); - this.#options.serverMaxWindowBits = extensions.get("server_max_window_bits"); + constructor(extensions2) { + this.#options.serverNoContextTakeover = extensions2.has("server_no_context_takeover"); + this.#options.serverMaxWindowBits = extensions2.get("server_max_window_bits"); } decompress(chunk, fin, callback) { if (!this.#inflate) { @@ -64751,12 +64751,12 @@ var require_receiver2 = __commonJS({ #extensions; /** @type {import('./websocket').Handler} */ #handler; - constructor(handler2, extensions) { + constructor(handler2, extensions2) { super(); this.#handler = handler2; - this.#extensions = extensions == null ? /* @__PURE__ */ new Map() : extensions; + this.#extensions = extensions2 == null ? /* @__PURE__ */ new Map() : extensions2; if (this.#extensions.has("permessage-deflate")) { - this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions)); + this.#extensions.set("permessage-deflate", new PerMessageDeflate(extensions2)); } } /** @@ -65161,7 +65161,7 @@ var require_websocket2 = __commonJS({ #sendQueue; /** @type {Handler} */ #handler = { - onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), + onConnectionEstablished: (response, extensions2) => this.#onConnectionEstablished(response, extensions2), onMessage: (opcode, data) => this.#onMessage(opcode, data), onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), onParserDrain: () => this.#onParserDrain(), @@ -65406,9 +65406,9 @@ var require_websocket2 = __commonJS({ this.#parser = parser; this.#sendQueue = new SendQueue(response.socket); this.#handler.readyState = states.OPEN; - const extensions = response.headersList.get("sec-websocket-extensions"); - if (extensions !== null) { - this.#extensions = extensions; + const extensions2 = response.headersList.get("sec-websocket-extensions"); + if (extensions2 !== null) { + this.#extensions = extensions2; } const protocol = response.headersList.get("sec-websocket-protocol"); if (protocol !== null) { @@ -65714,7 +65714,7 @@ var require_websocketstream = __commonJS({ /** @type {import('../websocket').Handler} */ #handler = { // https://whatpr.org/websockets/48/7b748d3...d5570f3.html#feedback-to-websocket-stream-from-the-protocol - onConnectionEstablished: (response, extensions) => this.#onConnectionEstablished(response, extensions), + onConnectionEstablished: (response, extensions2) => this.#onConnectionEstablished(response, extensions2), onMessage: (opcode, data) => this.#onMessage(opcode, data), onParserError: (err) => failWebsocketConnection(this.#handler, null, err.message), onParserDrain: () => this.#handler.socket.resume(), @@ -65849,7 +65849,7 @@ var require_websocketstream = __commonJS({ parser.on("error", (err) => this.#handler.onParserError(err)); this.#parser = parser; this.#handler.readyState = states.OPEN; - const extensions = parsedExtensions ?? ""; + const extensions2 = parsedExtensions ?? ""; const protocol = response.headersList.get("sec-websocket-protocol") ?? ""; const readable = new ReadableStream({ start: (controller) => { @@ -65871,7 +65871,7 @@ var require_websocketstream = __commonJS({ this.#readableStream = readable; this.#writableStream = writable; this.#openedPromise.resolve({ - extensions, + extensions: extensions2, protocol, readable, writable @@ -66632,11 +66632,11 @@ var require_undici2 = __commonJS({ if (typeof opts.path !== "string") { throw new InvalidArgumentError("invalid opts.path"); } - let path3 = opts.path; + let path4 = opts.path; if (!opts.path.startsWith("/")) { - path3 = `/${path3}`; + path4 = `/${path4}`; } - url4 = new URL(util3.parseOrigin(url4).origin + path3); + url4 = new URL(util3.parseOrigin(url4).origin + path4); } else { if (!opts) { opts = typeof url4 === "object" ? url4 : {}; @@ -68288,15 +68288,15 @@ var require_route = __commonJS({ }; } function wrapConversion(toModel, graph) { - const path3 = [graph[toModel].parent, toModel]; + const path4 = [graph[toModel].parent, toModel]; let fn2 = conversions[graph[toModel].parent][toModel]; let cur = graph[toModel].parent; while (graph[cur].parent) { - path3.unshift(graph[cur].parent); + path4.unshift(graph[cur].parent); fn2 = link(conversions[graph[cur].parent][cur], fn2); cur = graph[cur].parent; } - fn2.conversion = path3; + fn2.conversion = path4; return fn2; } module.exports = function(fromModel) { @@ -74358,6 +74358,3944 @@ var require_fast_content_type_parse = __commonJS({ } }); +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/Errors.js +var defaultMessages, EndOfStreamError, AbortError; +var init_Errors = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/Errors.js"() { + defaultMessages = "End-Of-Stream"; + EndOfStreamError = class extends Error { + constructor() { + super(defaultMessages); + this.name = "EndOfStreamError"; + } + }; + AbortError = class extends Error { + constructor(message = "The operation was aborted") { + super(message); + this.name = "AbortError"; + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/Deferred.js +var init_Deferred = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/Deferred.js"() { + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/AbstractStreamReader.js +var AbstractStreamReader; +var init_AbstractStreamReader = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/AbstractStreamReader.js"() { + init_Errors(); + AbstractStreamReader = class { + constructor() { + this.endOfStream = false; + this.interrupted = false; + this.peekQueue = []; + } + async peek(uint8Array, mayBeLess = false) { + const bytesRead = await this.read(uint8Array, mayBeLess); + this.peekQueue.push(uint8Array.subarray(0, bytesRead)); + return bytesRead; + } + async read(buffer, mayBeLess = false) { + if (buffer.length === 0) { + return 0; + } + let bytesRead = this.readFromPeekBuffer(buffer); + if (!this.endOfStream) { + bytesRead += await this.readRemainderFromStream(buffer.subarray(bytesRead), mayBeLess); + } + if (bytesRead === 0 && !mayBeLess) { + throw new EndOfStreamError(); + } + return bytesRead; + } + /** + * Read chunk from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @returns Number of bytes read + */ + readFromPeekBuffer(buffer) { + let remaining = buffer.length; + let bytesRead = 0; + while (this.peekQueue.length > 0 && remaining > 0) { + const peekData = this.peekQueue.pop(); + if (!peekData) + throw new Error("peekData should be defined"); + const lenCopy = Math.min(peekData.length, remaining); + buffer.set(peekData.subarray(0, lenCopy), bytesRead); + bytesRead += lenCopy; + remaining -= lenCopy; + if (lenCopy < peekData.length) { + this.peekQueue.push(peekData.subarray(lenCopy)); + } + } + return bytesRead; + } + async readRemainderFromStream(buffer, mayBeLess) { + let bytesRead = 0; + while (bytesRead < buffer.length && !this.endOfStream) { + if (this.interrupted) { + throw new AbortError(); + } + const chunkLen = await this.readFromStream(buffer.subarray(bytesRead), mayBeLess); + if (chunkLen === 0) + break; + bytesRead += chunkLen; + } + if (!mayBeLess && bytesRead < buffer.length) { + throw new EndOfStreamError(); + } + return bytesRead; + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/StreamReader.js +var init_StreamReader = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/StreamReader.js"() { + init_Errors(); + init_Deferred(); + init_AbstractStreamReader(); + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/WebStreamReader.js +var WebStreamReader; +var init_WebStreamReader = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/WebStreamReader.js"() { + init_AbstractStreamReader(); + WebStreamReader = class extends AbstractStreamReader { + constructor(reader) { + super(); + this.reader = reader; + } + async abort() { + return this.close(); + } + async close() { + this.reader.releaseLock(); + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/WebStreamByobReader.js +var WebStreamByobReader; +var init_WebStreamByobReader = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/WebStreamByobReader.js"() { + init_WebStreamReader(); + WebStreamByobReader = class extends WebStreamReader { + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + async readFromStream(buffer, mayBeLess) { + if (buffer.length === 0) + return 0; + const result = await this.reader.read(new Uint8Array(buffer.length), { min: mayBeLess ? void 0 : buffer.length }); + if (result.done) { + this.endOfStream = result.done; + } + if (result.value) { + buffer.set(result.value); + return result.value.length; + } + return 0; + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js +var WebStreamDefaultReader; +var init_WebStreamDefaultReader = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/WebStreamDefaultReader.js"() { + init_Errors(); + init_AbstractStreamReader(); + WebStreamDefaultReader = class extends AbstractStreamReader { + constructor(reader) { + super(); + this.reader = reader; + this.buffer = null; + } + /** + * Copy chunk to target, and store the remainder in this.buffer + */ + writeChunk(target, chunk) { + const written = Math.min(chunk.length, target.length); + target.set(chunk.subarray(0, written)); + if (written < chunk.length) { + this.buffer = chunk.subarray(written); + } else { + this.buffer = null; + } + return written; + } + /** + * Read from stream + * @param buffer - Target Uint8Array (or Buffer) to store data read from stream in + * @param mayBeLess - If true, may fill the buffer partially + * @protected Bytes read + */ + async readFromStream(buffer, mayBeLess) { + if (buffer.length === 0) + return 0; + let totalBytesRead = 0; + if (this.buffer) { + totalBytesRead += this.writeChunk(buffer, this.buffer); + } + while (totalBytesRead < buffer.length && !this.endOfStream) { + const result = await this.reader.read(); + if (result.done) { + this.endOfStream = true; + break; + } + if (result.value) { + totalBytesRead += this.writeChunk(buffer.subarray(totalBytesRead), result.value); + } + } + if (!mayBeLess && totalBytesRead === 0 && this.endOfStream) { + throw new EndOfStreamError(); + } + return totalBytesRead; + } + abort() { + this.interrupted = true; + return this.reader.cancel(); + } + async close() { + await this.abort(); + this.reader.releaseLock(); + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js +function makeWebStreamReader(stream) { + try { + const reader = stream.getReader({ mode: "byob" }); + if (reader instanceof ReadableStreamDefaultReader) { + return new WebStreamDefaultReader(reader); + } + return new WebStreamByobReader(reader); + } catch (error50) { + if (error50 instanceof TypeError) { + return new WebStreamDefaultReader(stream.getReader()); + } + throw error50; + } +} +var init_WebStreamReaderFactory = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/WebStreamReaderFactory.js"() { + init_WebStreamByobReader(); + init_WebStreamDefaultReader(); + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/index.js +var init_stream = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/stream/index.js"() { + init_Errors(); + init_StreamReader(); + init_WebStreamByobReader(); + init_WebStreamDefaultReader(); + init_WebStreamReaderFactory(); + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/AbstractTokenizer.js +var AbstractTokenizer; +var init_AbstractTokenizer = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/AbstractTokenizer.js"() { + init_stream(); + AbstractTokenizer = class { + /** + * Constructor + * @param options Tokenizer options + * @protected + */ + constructor(options) { + this.numBuffer = new Uint8Array(8); + this.position = 0; + this.onClose = options?.onClose; + if (options?.abortSignal) { + options.abortSignal.addEventListener("abort", () => { + this.abort(); + }); + } + } + /** + * Read a token from the tokenizer-stream + * @param token - The token to read + * @param position - If provided, the desired position in the tokenizer-stream + * @returns Promise with token data + */ + async readToken(token, position = this.position) { + const uint8Array = new Uint8Array(token.len); + const len = await this.readBuffer(uint8Array, { position }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Peek a token from the tokenizer-stream. + * @param token - Token to peek from the tokenizer-stream. + * @param position - Offset where to begin reading within the file. If position is null, data will be read from the current file position. + * @returns Promise with token data + */ + async peekToken(token, position = this.position) { + const uint8Array = new Uint8Array(token.len); + const len = await this.peekBuffer(uint8Array, { position }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(uint8Array, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async readNumber(token) { + const len = await this.readBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Read a numeric token from the stream + * @param token - Numeric token + * @returns Promise with number + */ + async peekNumber(token) { + const len = await this.peekBuffer(this.numBuffer, { length: token.len }); + if (len < token.len) + throw new EndOfStreamError(); + return token.get(this.numBuffer, 0); + } + /** + * Ignore number of bytes, advances the pointer in under tokenizer-stream. + * @param length - Number of bytes to ignore + * @return resolves the number of bytes ignored, equals length if this available, otherwise the number of bytes available + */ + async ignore(length) { + if (this.fileInfo.size !== void 0) { + const bytesLeft = this.fileInfo.size - this.position; + if (length > bytesLeft) { + this.position += bytesLeft; + return bytesLeft; + } + } + this.position += length; + return length; + } + async close() { + await this.abort(); + await this.onClose?.(); + } + normalizeOptions(uint8Array, options) { + if (!this.supportsRandomAccess() && options && options.position !== void 0 && options.position < this.position) { + throw new Error("`options.position` must be equal or greater than `tokenizer.position`"); + } + return { + ...{ + mayBeLess: false, + offset: 0, + length: uint8Array.length, + position: this.position + }, + ...options + }; + } + abort() { + return Promise.resolve(); + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/ReadStreamTokenizer.js +var maxBufferSize, ReadStreamTokenizer; +var init_ReadStreamTokenizer = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/ReadStreamTokenizer.js"() { + init_AbstractTokenizer(); + init_stream(); + maxBufferSize = 256e3; + ReadStreamTokenizer = class extends AbstractTokenizer { + /** + * Constructor + * @param streamReader stream-reader to read from + * @param options Tokenizer options + */ + constructor(streamReader, options) { + super(options); + this.streamReader = streamReader; + this.fileInfo = options?.fileInfo ?? {}; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Target Uint8Array to fill with data read from the tokenizer-stream + * @param options - Read behaviour options + * @returns Promise with number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + await this.ignore(skipBytes); + return this.readBuffer(uint8Array, options); + } + if (skipBytes < 0) { + throw new Error("`options.position` must be equal or greater than `tokenizer.position`"); + } + if (normOptions.length === 0) { + return 0; + } + const bytesRead = await this.streamReader.read(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess); + this.position += bytesRead; + if ((!options || !options.mayBeLess) && bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise with number of bytes peeked + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + let bytesRead = 0; + if (normOptions.position) { + const skipBytes = normOptions.position - this.position; + if (skipBytes > 0) { + const skipBuffer = new Uint8Array(normOptions.length + skipBytes); + bytesRead = await this.peekBuffer(skipBuffer, { mayBeLess: normOptions.mayBeLess }); + uint8Array.set(skipBuffer.subarray(skipBytes)); + return bytesRead - skipBytes; + } + if (skipBytes < 0) { + throw new Error("Cannot peek from a negative offset in a stream"); + } + } + if (normOptions.length > 0) { + try { + bytesRead = await this.streamReader.peek(uint8Array.subarray(0, normOptions.length), normOptions.mayBeLess); + } catch (err) { + if (options?.mayBeLess && err instanceof EndOfStreamError) { + return 0; + } + throw err; + } + if (!normOptions.mayBeLess && bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + } + return bytesRead; + } + async ignore(length) { + const bufSize = Math.min(maxBufferSize, length); + const buf = new Uint8Array(bufSize); + let totBytesRead = 0; + while (totBytesRead < length) { + const remaining = length - totBytesRead; + const bytesRead = await this.readBuffer(buf, { length: Math.min(bufSize, remaining) }); + if (bytesRead < 0) { + return bytesRead; + } + totBytesRead += bytesRead; + } + return totBytesRead; + } + abort() { + return this.streamReader.abort(); + } + async close() { + return this.streamReader.close(); + } + supportsRandomAccess() { + return false; + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/BufferTokenizer.js +var BufferTokenizer; +var init_BufferTokenizer = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/BufferTokenizer.js"() { + init_stream(); + init_AbstractTokenizer(); + BufferTokenizer = class extends AbstractTokenizer { + /** + * Construct BufferTokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(uint8Array, options) { + super(options); + this.uint8Array = uint8Array; + this.fileInfo = { ...options?.fileInfo ?? {}, ...{ size: uint8Array.length } }; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + async readBuffer(uint8Array, options) { + if (options?.position) { + this.position = options.position; + } + const bytesRead = await this.peekBuffer(uint8Array, options); + this.position += bytesRead; + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param uint8Array + * @param options - Read behaviour options + * @returns {Promise} + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const bytes2read = Math.min(this.uint8Array.length - normOptions.position, normOptions.length); + if (!normOptions.mayBeLess && bytes2read < normOptions.length) { + throw new EndOfStreamError(); + } + uint8Array.set(this.uint8Array.subarray(normOptions.position, normOptions.position + bytes2read)); + return bytes2read; + } + close() { + return super.close(); + } + supportsRandomAccess() { + return true; + } + setPosition(position) { + this.position = position; + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/BlobTokenizer.js +var BlobTokenizer; +var init_BlobTokenizer = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/BlobTokenizer.js"() { + init_stream(); + init_AbstractTokenizer(); + BlobTokenizer = class extends AbstractTokenizer { + /** + * Construct BufferTokenizer + * @param blob - Uint8Array to tokenize + * @param options Tokenizer options + */ + constructor(blob, options) { + super(options); + this.blob = blob; + this.fileInfo = { ...options?.fileInfo ?? {}, ...{ size: blob.size, mimeType: blob.type } }; + } + /** + * Read buffer from tokenizer + * @param uint8Array - Uint8Array to tokenize + * @param options - Read behaviour options + * @returns {Promise} + */ + async readBuffer(uint8Array, options) { + if (options?.position) { + this.position = options.position; + } + const bytesRead = await this.peekBuffer(uint8Array, options); + this.position += bytesRead; + return bytesRead; + } + /** + * Peek (read ahead) buffer from tokenizer + * @param buffer + * @param options - Read behaviour options + * @returns {Promise} + */ + async peekBuffer(buffer, options) { + const normOptions = this.normalizeOptions(buffer, options); + const bytes2read = Math.min(this.blob.size - normOptions.position, normOptions.length); + if (!normOptions.mayBeLess && bytes2read < normOptions.length) { + throw new EndOfStreamError(); + } + const arrayBuffer = await this.blob.slice(normOptions.position, normOptions.position + bytes2read).arrayBuffer(); + buffer.set(new Uint8Array(arrayBuffer)); + return bytes2read; + } + close() { + return super.close(); + } + supportsRandomAccess() { + return true; + } + setPosition(position) { + this.position = position; + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/core.js +function fromWebStream(webStream, options) { + const webStreamReader = makeWebStreamReader(webStream); + const _options = options ?? {}; + const chainedClose = _options.onClose; + _options.onClose = async () => { + await webStreamReader.close(); + if (chainedClose) { + return chainedClose(); + } + }; + return new ReadStreamTokenizer(webStreamReader, _options); +} +function fromBuffer(uint8Array, options) { + return new BufferTokenizer(uint8Array, options); +} +function fromBlob(blob, options) { + return new BlobTokenizer(blob, options); +} +var init_core3 = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/core.js"() { + init_stream(); + init_ReadStreamTokenizer(); + init_BufferTokenizer(); + init_BlobTokenizer(); + init_stream(); + init_AbstractTokenizer(); + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/FileTokenizer.js +import { open as fsOpen } from "node:fs/promises"; +var FileTokenizer; +var init_FileTokenizer = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/FileTokenizer.js"() { + init_AbstractTokenizer(); + init_stream(); + FileTokenizer = class _FileTokenizer extends AbstractTokenizer { + /** + * Create tokenizer from provided file path + * @param sourceFilePath File path + */ + static async fromFile(sourceFilePath) { + const fileHandle = await fsOpen(sourceFilePath, "r"); + const stat = await fileHandle.stat(); + return new _FileTokenizer(fileHandle, { fileInfo: { path: sourceFilePath, size: stat.size } }); + } + constructor(fileHandle, options) { + super(options); + this.fileHandle = fileHandle; + this.fileInfo = options.fileInfo; + } + /** + * Read buffer from file + * @param uint8Array - Uint8Array to write result to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async readBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + this.position = normOptions.position; + if (normOptions.length === 0) + return 0; + const res = await this.fileHandle.read(uint8Array, 0, normOptions.length, normOptions.position); + this.position += res.bytesRead; + if (res.bytesRead < normOptions.length && (!options || !options.mayBeLess)) { + throw new EndOfStreamError(); + } + return res.bytesRead; + } + /** + * Peek buffer from file + * @param uint8Array - Uint8Array (or Buffer) to write data to + * @param options - Read behaviour options + * @returns Promise number of bytes read + */ + async peekBuffer(uint8Array, options) { + const normOptions = this.normalizeOptions(uint8Array, options); + const res = await this.fileHandle.read(uint8Array, 0, normOptions.length, normOptions.position); + if (!normOptions.mayBeLess && res.bytesRead < normOptions.length) { + throw new EndOfStreamError(); + } + return res.bytesRead; + } + async close() { + await this.fileHandle.close(); + return super.close(); + } + setPosition(position) { + this.position = position; + } + supportsRandomAccess() { + return true; + } + }; + } +}); + +// node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/index.js +var fromFile; +var init_lib = __esm({ + "node_modules/.pnpm/strtok3@10.3.4/node_modules/strtok3/lib/index.js"() { + init_core3(); + init_FileTokenizer(); + init_FileTokenizer(); + init_core3(); + fromFile = FileTokenizer.fromFile; + } +}); + +// node_modules/.pnpm/ieee754@1.2.1/node_modules/ieee754/index.js +var require_ieee754 = __commonJS({ + "node_modules/.pnpm/ieee754@1.2.1/node_modules/ieee754/index.js"(exports) { + exports.read = function(buffer, offset, isLE, mLen, nBytes) { + var e, m; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var nBits = -7; + var i = isLE ? nBytes - 1 : 0; + var d = isLE ? -1 : 1; + var s = buffer[offset + i]; + i += d; + e = s & (1 << -nBits) - 1; + s >>= -nBits; + nBits += eLen; + for (; nBits > 0; e = e * 256 + buffer[offset + i], i += d, nBits -= 8) { + } + m = e & (1 << -nBits) - 1; + e >>= -nBits; + nBits += mLen; + for (; nBits > 0; m = m * 256 + buffer[offset + i], i += d, nBits -= 8) { + } + if (e === 0) { + e = 1 - eBias; + } else if (e === eMax) { + return m ? NaN : (s ? -1 : 1) * Infinity; + } else { + m = m + Math.pow(2, mLen); + e = e - eBias; + } + return (s ? -1 : 1) * m * Math.pow(2, e - mLen); + }; + exports.write = function(buffer, value2, offset, isLE, mLen, nBytes) { + var e, m, c; + var eLen = nBytes * 8 - mLen - 1; + var eMax = (1 << eLen) - 1; + var eBias = eMax >> 1; + var rt = mLen === 23 ? Math.pow(2, -24) - Math.pow(2, -77) : 0; + var i = isLE ? 0 : nBytes - 1; + var d = isLE ? 1 : -1; + var s = value2 < 0 || value2 === 0 && 1 / value2 < 0 ? 1 : 0; + value2 = Math.abs(value2); + if (isNaN(value2) || value2 === Infinity) { + m = isNaN(value2) ? 1 : 0; + e = eMax; + } else { + e = Math.floor(Math.log(value2) / Math.LN2); + if (value2 * (c = Math.pow(2, -e)) < 1) { + e--; + c *= 2; + } + if (e + eBias >= 1) { + value2 += rt / c; + } else { + value2 += rt * Math.pow(2, 1 - eBias); + } + if (value2 * c >= 2) { + e++; + c /= 2; + } + if (e + eBias >= eMax) { + m = 0; + e = eMax; + } else if (e + eBias >= 1) { + m = (value2 * c - 1) * Math.pow(2, mLen); + e = e + eBias; + } else { + m = value2 * Math.pow(2, eBias - 1) * Math.pow(2, mLen); + e = 0; + } + } + for (; mLen >= 8; buffer[offset + i] = m & 255, i += d, m /= 256, mLen -= 8) { + } + e = e << mLen | m; + eLen += mLen; + for (; eLen > 0; buffer[offset + i] = e & 255, i += d, e /= 256, eLen -= 8) { + } + buffer[offset + i - d] |= s * 128; + }; + } +}); + +// node_modules/.pnpm/@borewit+text-codec@0.1.1/node_modules/@borewit/text-codec/lib/index.js +function textDecode(bytes, encoding = "utf-8") { + switch (encoding.toLowerCase()) { + case "utf-8": + case "utf8": + if (typeof globalThis.TextDecoder !== "undefined") { + return new globalThis.TextDecoder("utf-8").decode(bytes); + } + return decodeUTF8(bytes); + case "utf-16le": + return decodeUTF16LE(bytes); + case "ascii": + return decodeASCII(bytes); + case "latin1": + case "iso-8859-1": + return decodeLatin1(bytes); + case "windows-1252": + return decodeWindows1252(bytes); + default: + throw new RangeError(`Encoding '${encoding}' not supported`); + } +} +function decodeUTF8(bytes) { + let out = ""; + let i = 0; + while (i < bytes.length) { + const b1 = bytes[i++]; + if (b1 < 128) { + out += String.fromCharCode(b1); + } else if (b1 < 224) { + const b2 = bytes[i++] & 63; + out += String.fromCharCode((b1 & 31) << 6 | b2); + } else if (b1 < 240) { + const b2 = bytes[i++] & 63; + const b3 = bytes[i++] & 63; + out += String.fromCharCode((b1 & 15) << 12 | b2 << 6 | b3); + } else { + const b2 = bytes[i++] & 63; + const b3 = bytes[i++] & 63; + const b4 = bytes[i++] & 63; + let cp = (b1 & 7) << 18 | b2 << 12 | b3 << 6 | b4; + cp -= 65536; + out += String.fromCharCode(55296 + (cp >> 10 & 1023), 56320 + (cp & 1023)); + } + } + return out; +} +function decodeUTF16LE(bytes) { + let out = ""; + for (let i = 0; i < bytes.length; i += 2) { + out += String.fromCharCode(bytes[i] | bytes[i + 1] << 8); + } + return out; +} +function decodeASCII(bytes) { + return String.fromCharCode(...bytes.map((b) => b & 127)); +} +function decodeLatin1(bytes) { + return String.fromCharCode(...bytes); +} +function decodeWindows1252(bytes) { + let out = ""; + for (const b of bytes) { + if (b >= 128 && b <= 159 && WINDOWS_1252_EXTRA[b]) { + out += WINDOWS_1252_EXTRA[b]; + } else { + out += String.fromCharCode(b); + } + } + return out; +} +var WINDOWS_1252_EXTRA, WINDOWS_1252_REVERSE; +var init_lib2 = __esm({ + "node_modules/.pnpm/@borewit+text-codec@0.1.1/node_modules/@borewit/text-codec/lib/index.js"() { + WINDOWS_1252_EXTRA = { + 128: "\u20AC", + 130: "\u201A", + 131: "\u0192", + 132: "\u201E", + 133: "\u2026", + 134: "\u2020", + 135: "\u2021", + 136: "\u02C6", + 137: "\u2030", + 138: "\u0160", + 139: "\u2039", + 140: "\u0152", + 142: "\u017D", + 145: "\u2018", + 146: "\u2019", + 147: "\u201C", + 148: "\u201D", + 149: "\u2022", + 150: "\u2013", + 151: "\u2014", + 152: "\u02DC", + 153: "\u2122", + 154: "\u0161", + 155: "\u203A", + 156: "\u0153", + 158: "\u017E", + 159: "\u0178" + }; + WINDOWS_1252_REVERSE = {}; + for (const [code, char] of Object.entries(WINDOWS_1252_EXTRA)) { + WINDOWS_1252_REVERSE[char] = Number.parseInt(code); + } + } +}); + +// node_modules/.pnpm/token-types@6.1.1/node_modules/token-types/lib/index.js +function dv(array4) { + return new DataView(array4.buffer, array4.byteOffset); +} +var ieee754, UINT8, UINT16_LE, UINT16_BE, UINT32_LE, UINT32_BE, INT32_BE, UINT64_LE, StringType; +var init_lib3 = __esm({ + "node_modules/.pnpm/token-types@6.1.1/node_modules/token-types/lib/index.js"() { + ieee754 = __toESM(require_ieee754(), 1); + init_lib2(); + UINT8 = { + len: 1, + get(array4, offset) { + return dv(array4).getUint8(offset); + }, + put(array4, offset, value2) { + dv(array4).setUint8(offset, value2); + return offset + 1; + } + }; + UINT16_LE = { + len: 2, + get(array4, offset) { + return dv(array4).getUint16(offset, true); + }, + put(array4, offset, value2) { + dv(array4).setUint16(offset, value2, true); + return offset + 2; + } + }; + UINT16_BE = { + len: 2, + get(array4, offset) { + return dv(array4).getUint16(offset); + }, + put(array4, offset, value2) { + dv(array4).setUint16(offset, value2); + return offset + 2; + } + }; + UINT32_LE = { + len: 4, + get(array4, offset) { + return dv(array4).getUint32(offset, true); + }, + put(array4, offset, value2) { + dv(array4).setUint32(offset, value2, true); + return offset + 4; + } + }; + UINT32_BE = { + len: 4, + get(array4, offset) { + return dv(array4).getUint32(offset); + }, + put(array4, offset, value2) { + dv(array4).setUint32(offset, value2); + return offset + 4; + } + }; + INT32_BE = { + len: 4, + get(array4, offset) { + return dv(array4).getInt32(offset); + }, + put(array4, offset, value2) { + dv(array4).setInt32(offset, value2); + return offset + 4; + } + }; + UINT64_LE = { + len: 8, + get(array4, offset) { + return dv(array4).getBigUint64(offset, true); + }, + put(array4, offset, value2) { + dv(array4).setBigUint64(offset, value2, true); + return offset + 8; + } + }; + StringType = class { + constructor(len, encoding) { + this.len = len; + this.encoding = encoding; + } + get(data, offset = 0) { + const bytes = data.subarray(offset, offset + this.len); + return textDecode(bytes, this.encoding); + } + }; + } +}); + +// node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js +var require_ms = __commonJS({ + "node_modules/.pnpm/ms@2.1.3/node_modules/ms/index.js"(exports, module) { + var s = 1e3; + var m = s * 60; + var h = m * 60; + var d = h * 24; + var w = d * 7; + var y = d * 365.25; + module.exports = function(val, options) { + options = options || {}; + var type2 = typeof val; + if (type2 === "string" && val.length > 0) { + return parse5(val); + } else if (type2 === "number" && isFinite(val)) { + return options.long ? fmtLong(val) : fmtShort(val); + } + throw new Error( + "val is not a non-empty string or a valid number. val=" + JSON.stringify(val) + ); + }; + function parse5(str) { + str = String(str); + if (str.length > 100) { + return; + } + var match2 = /^(-?(?:\d+)?\.?\d+) *(milliseconds?|msecs?|ms|seconds?|secs?|s|minutes?|mins?|m|hours?|hrs?|h|days?|d|weeks?|w|years?|yrs?|y)?$/i.exec( + str + ); + if (!match2) { + return; + } + var n = parseFloat(match2[1]); + var type2 = (match2[2] || "ms").toLowerCase(); + switch (type2) { + case "years": + case "year": + case "yrs": + case "yr": + case "y": + return n * y; + case "weeks": + case "week": + case "w": + return n * w; + case "days": + case "day": + case "d": + return n * d; + case "hours": + case "hour": + case "hrs": + case "hr": + case "h": + return n * h; + case "minutes": + case "minute": + case "mins": + case "min": + case "m": + return n * m; + case "seconds": + case "second": + case "secs": + case "sec": + case "s": + return n * s; + case "milliseconds": + case "millisecond": + case "msecs": + case "msec": + case "ms": + return n; + default: + return void 0; + } + } + function fmtShort(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return Math.round(ms / d) + "d"; + } + if (msAbs >= h) { + return Math.round(ms / h) + "h"; + } + if (msAbs >= m) { + return Math.round(ms / m) + "m"; + } + if (msAbs >= s) { + return Math.round(ms / s) + "s"; + } + return ms + "ms"; + } + function fmtLong(ms) { + var msAbs = Math.abs(ms); + if (msAbs >= d) { + return plural(ms, msAbs, d, "day"); + } + if (msAbs >= h) { + return plural(ms, msAbs, h, "hour"); + } + if (msAbs >= m) { + return plural(ms, msAbs, m, "minute"); + } + if (msAbs >= s) { + return plural(ms, msAbs, s, "second"); + } + return ms + " ms"; + } + function plural(ms, msAbs, n, name) { + var isPlural = msAbs >= n * 1.5; + return Math.round(ms / n) + " " + name + (isPlural ? "s" : ""); + } + } +}); + +// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js +var require_common = __commonJS({ + "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/common.js"(exports, module) { + function setup(env3) { + createDebug.debug = createDebug; + createDebug.default = createDebug; + createDebug.coerce = coerce; + createDebug.disable = disable; + createDebug.enable = enable; + createDebug.enabled = enabled; + createDebug.humanize = require_ms(); + createDebug.destroy = destroy; + Object.keys(env3).forEach((key) => { + createDebug[key] = env3[key]; + }); + createDebug.names = []; + createDebug.skips = []; + createDebug.formatters = {}; + function selectColor(namespace) { + let hash2 = 0; + for (let i = 0; i < namespace.length; i++) { + hash2 = (hash2 << 5) - hash2 + namespace.charCodeAt(i); + hash2 |= 0; + } + return createDebug.colors[Math.abs(hash2) % createDebug.colors.length]; + } + createDebug.selectColor = selectColor; + function createDebug(namespace) { + let prevTime; + let enableOverride = null; + let namespacesCache; + let enabledCache; + function debug2(...args3) { + if (!debug2.enabled) { + return; + } + const self2 = debug2; + const curr = Number(/* @__PURE__ */ new Date()); + const ms = curr - (prevTime || curr); + self2.diff = ms; + self2.prev = prevTime; + self2.curr = curr; + prevTime = curr; + args3[0] = createDebug.coerce(args3[0]); + if (typeof args3[0] !== "string") { + args3.unshift("%O"); + } + let index = 0; + args3[0] = args3[0].replace(/%([a-zA-Z%])/g, (match2, format2) => { + if (match2 === "%%") { + return "%"; + } + index++; + const formatter = createDebug.formatters[format2]; + if (typeof formatter === "function") { + const val = args3[index]; + match2 = formatter.call(self2, val); + args3.splice(index, 1); + index--; + } + return match2; + }); + createDebug.formatArgs.call(self2, args3); + const logFn = self2.log || createDebug.log; + logFn.apply(self2, args3); + } + debug2.namespace = namespace; + debug2.useColors = createDebug.useColors(); + debug2.color = createDebug.selectColor(namespace); + debug2.extend = extend4; + debug2.destroy = createDebug.destroy; + Object.defineProperty(debug2, "enabled", { + enumerable: true, + configurable: false, + get: () => { + if (enableOverride !== null) { + return enableOverride; + } + if (namespacesCache !== createDebug.namespaces) { + namespacesCache = createDebug.namespaces; + enabledCache = createDebug.enabled(namespace); + } + return enabledCache; + }, + set: (v) => { + enableOverride = v; + } + }); + if (typeof createDebug.init === "function") { + createDebug.init(debug2); + } + return debug2; + } + function extend4(namespace, delimiter) { + const newDebug = createDebug(this.namespace + (typeof delimiter === "undefined" ? ":" : delimiter) + namespace); + newDebug.log = this.log; + return newDebug; + } + function enable(namespaces) { + createDebug.save(namespaces); + createDebug.namespaces = namespaces; + createDebug.names = []; + createDebug.skips = []; + const split = (typeof namespaces === "string" ? namespaces : "").trim().replace(/\s+/g, ",").split(",").filter(Boolean); + for (const ns of split) { + if (ns[0] === "-") { + createDebug.skips.push(ns.slice(1)); + } else { + createDebug.names.push(ns); + } + } + } + function matchesTemplate(search2, template) { + let searchIndex = 0; + let templateIndex = 0; + let starIndex = -1; + let matchIndex = 0; + while (searchIndex < search2.length) { + if (templateIndex < template.length && (template[templateIndex] === search2[searchIndex] || template[templateIndex] === "*")) { + if (template[templateIndex] === "*") { + starIndex = templateIndex; + matchIndex = searchIndex; + templateIndex++; + } else { + searchIndex++; + templateIndex++; + } + } else if (starIndex !== -1) { + templateIndex = starIndex + 1; + matchIndex++; + searchIndex = matchIndex; + } else { + return false; + } + } + while (templateIndex < template.length && template[templateIndex] === "*") { + templateIndex++; + } + return templateIndex === template.length; + } + function disable() { + const namespaces = [ + ...createDebug.names, + ...createDebug.skips.map((namespace) => "-" + namespace) + ].join(","); + createDebug.enable(""); + return namespaces; + } + function enabled(name) { + for (const skip of createDebug.skips) { + if (matchesTemplate(name, skip)) { + return false; + } + } + for (const ns of createDebug.names) { + if (matchesTemplate(name, ns)) { + return true; + } + } + return false; + } + function coerce(val) { + if (val instanceof Error) { + return val.stack || val.message; + } + return val; + } + function destroy() { + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + createDebug.enable(createDebug.load()); + return createDebug; + } + module.exports = setup; + } +}); + +// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js +var require_browser = __commonJS({ + "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/browser.js"(exports, module) { + exports.formatArgs = formatArgs2; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.storage = localstorage(); + exports.destroy = /* @__PURE__ */ (() => { + let warned = false; + return () => { + if (!warned) { + warned = true; + console.warn("Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`."); + } + }; + })(); + exports.colors = [ + "#0000CC", + "#0000FF", + "#0033CC", + "#0033FF", + "#0066CC", + "#0066FF", + "#0099CC", + "#0099FF", + "#00CC00", + "#00CC33", + "#00CC66", + "#00CC99", + "#00CCCC", + "#00CCFF", + "#3300CC", + "#3300FF", + "#3333CC", + "#3333FF", + "#3366CC", + "#3366FF", + "#3399CC", + "#3399FF", + "#33CC00", + "#33CC33", + "#33CC66", + "#33CC99", + "#33CCCC", + "#33CCFF", + "#6600CC", + "#6600FF", + "#6633CC", + "#6633FF", + "#66CC00", + "#66CC33", + "#9900CC", + "#9900FF", + "#9933CC", + "#9933FF", + "#99CC00", + "#99CC33", + "#CC0000", + "#CC0033", + "#CC0066", + "#CC0099", + "#CC00CC", + "#CC00FF", + "#CC3300", + "#CC3333", + "#CC3366", + "#CC3399", + "#CC33CC", + "#CC33FF", + "#CC6600", + "#CC6633", + "#CC9900", + "#CC9933", + "#CCCC00", + "#CCCC33", + "#FF0000", + "#FF0033", + "#FF0066", + "#FF0099", + "#FF00CC", + "#FF00FF", + "#FF3300", + "#FF3333", + "#FF3366", + "#FF3399", + "#FF33CC", + "#FF33FF", + "#FF6600", + "#FF6633", + "#FF9900", + "#FF9933", + "#FFCC00", + "#FFCC33" + ]; + function useColors() { + if (typeof window !== "undefined" && window.process && (window.process.type === "renderer" || window.process.__nwjs)) { + return true; + } + if (typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/(edge|trident)\/(\d+)/)) { + return false; + } + let m; + return typeof document !== "undefined" && document.documentElement && document.documentElement.style && document.documentElement.style.WebkitAppearance || // Is firebug? http://stackoverflow.com/a/398120/376773 + typeof window !== "undefined" && window.console && (window.console.firebug || window.console.exception && window.console.table) || // Is firefox >= v31? + // https://developer.mozilla.org/en-US/docs/Tools/Web_Console#Styling_messages + typeof navigator !== "undefined" && navigator.userAgent && (m = navigator.userAgent.toLowerCase().match(/firefox\/(\d+)/)) && parseInt(m[1], 10) >= 31 || // Double check webkit in userAgent just in case we are in a worker + typeof navigator !== "undefined" && navigator.userAgent && navigator.userAgent.toLowerCase().match(/applewebkit\/(\d+)/); + } + function formatArgs2(args3) { + args3[0] = (this.useColors ? "%c" : "") + this.namespace + (this.useColors ? " %c" : " ") + args3[0] + (this.useColors ? "%c " : " ") + "+" + module.exports.humanize(this.diff); + if (!this.useColors) { + return; + } + const c = "color: " + this.color; + args3.splice(1, 0, c, "color: inherit"); + let index = 0; + let lastC = 0; + args3[0].replace(/%[a-zA-Z%]/g, (match2) => { + if (match2 === "%%") { + return; + } + index++; + if (match2 === "%c") { + lastC = index; + } + }); + args3.splice(lastC, 0, c); + } + exports.log = console.debug || console.log || (() => { + }); + function save(namespaces) { + try { + if (namespaces) { + exports.storage.setItem("debug", namespaces); + } else { + exports.storage.removeItem("debug"); + } + } catch (error50) { + } + } + function load() { + let r; + try { + r = exports.storage.getItem("debug") || exports.storage.getItem("DEBUG"); + } catch (error50) { + } + if (!r && typeof process !== "undefined" && "env" in process) { + r = process.env.DEBUG; + } + return r; + } + function localstorage() { + try { + return localStorage; + } catch (error50) { + } + } + module.exports = require_common()(exports); + var { formatters } = module.exports; + formatters.j = function(v) { + try { + return JSON.stringify(v); + } catch (error50) { + return "[UnexpectedJSONParseError]: " + error50.message; + } + }; + } +}); + +// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js +var require_node = __commonJS({ + "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/node.js"(exports, module) { + var tty = __require("tty"); + var util3 = __require("util"); + exports.init = init; + exports.log = log2; + exports.formatArgs = formatArgs2; + exports.save = save; + exports.load = load; + exports.useColors = useColors; + exports.destroy = util3.deprecate( + () => { + }, + "Instance method `debug.destroy()` is deprecated and no longer does anything. It will be removed in the next major version of `debug`." + ); + exports.colors = [6, 2, 3, 4, 5, 1]; + try { + const supportsColor = __require("supports-color"); + if (supportsColor && (supportsColor.stderr || supportsColor).level >= 2) { + exports.colors = [ + 20, + 21, + 26, + 27, + 32, + 33, + 38, + 39, + 40, + 41, + 42, + 43, + 44, + 45, + 56, + 57, + 62, + 63, + 68, + 69, + 74, + 75, + 76, + 77, + 78, + 79, + 80, + 81, + 92, + 93, + 98, + 99, + 112, + 113, + 128, + 129, + 134, + 135, + 148, + 149, + 160, + 161, + 162, + 163, + 164, + 165, + 166, + 167, + 168, + 169, + 170, + 171, + 172, + 173, + 178, + 179, + 184, + 185, + 196, + 197, + 198, + 199, + 200, + 201, + 202, + 203, + 204, + 205, + 206, + 207, + 208, + 209, + 214, + 215, + 220, + 221 + ]; + } + } catch (error50) { + } + exports.inspectOpts = Object.keys(process.env).filter((key) => { + return /^debug_/i.test(key); + }).reduce((obj, key) => { + const prop = key.substring(6).toLowerCase().replace(/_([a-z])/g, (_, k) => { + return k.toUpperCase(); + }); + let val = process.env[key]; + if (/^(yes|on|true|enabled)$/i.test(val)) { + val = true; + } else if (/^(no|off|false|disabled)$/i.test(val)) { + val = false; + } else if (val === "null") { + val = null; + } else { + val = Number(val); + } + obj[prop] = val; + return obj; + }, {}); + function useColors() { + return "colors" in exports.inspectOpts ? Boolean(exports.inspectOpts.colors) : tty.isatty(process.stderr.fd); + } + function formatArgs2(args3) { + const { namespace: name, useColors: useColors2 } = this; + if (useColors2) { + const c = this.color; + const colorCode = "\x1B[3" + (c < 8 ? c : "8;5;" + c); + const prefix = ` ${colorCode};1m${name} \x1B[0m`; + args3[0] = prefix + args3[0].split("\n").join("\n" + prefix); + args3.push(colorCode + "m+" + module.exports.humanize(this.diff) + "\x1B[0m"); + } else { + args3[0] = getDate() + name + " " + args3[0]; + } + } + function getDate() { + if (exports.inspectOpts.hideDate) { + return ""; + } + return (/* @__PURE__ */ new Date()).toISOString() + " "; + } + function log2(...args3) { + return process.stderr.write(util3.formatWithOptions(exports.inspectOpts, ...args3) + "\n"); + } + function save(namespaces) { + if (namespaces) { + process.env.DEBUG = namespaces; + } else { + delete process.env.DEBUG; + } + } + function load() { + return process.env.DEBUG; + } + function init(debug2) { + debug2.inspectOpts = {}; + const keys = Object.keys(exports.inspectOpts); + for (let i = 0; i < keys.length; i++) { + debug2.inspectOpts[keys[i]] = exports.inspectOpts[keys[i]]; + } + } + module.exports = require_common()(exports); + var { formatters } = module.exports; + formatters.o = function(v) { + this.inspectOpts.colors = this.useColors; + return util3.inspect(v, this.inspectOpts).split("\n").map((str) => str.trim()).join(" "); + }; + formatters.O = function(v) { + this.inspectOpts.colors = this.useColors; + return util3.inspect(v, this.inspectOpts); + }; + } +}); + +// node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js +var require_src2 = __commonJS({ + "node_modules/.pnpm/debug@4.4.3/node_modules/debug/src/index.js"(exports, module) { + if (typeof process === "undefined" || process.type === "renderer" || process.browser === true || process.__nwjs) { + module.exports = require_browser(); + } else { + module.exports = require_node(); + } + } +}); + +// node_modules/.pnpm/@tokenizer+inflate@0.4.1/node_modules/@tokenizer/inflate/lib/ZipToken.js +var Signature, DataDescriptor, LocalFileHeaderToken, EndOfCentralDirectoryRecordToken, FileHeader; +var init_ZipToken = __esm({ + "node_modules/.pnpm/@tokenizer+inflate@0.4.1/node_modules/@tokenizer/inflate/lib/ZipToken.js"() { + init_lib3(); + Signature = { + LocalFileHeader: 67324752, + DataDescriptor: 134695760, + CentralFileHeader: 33639248, + EndOfCentralDirectory: 101010256 + }; + DataDescriptor = { + get(array4) { + return { + signature: UINT32_LE.get(array4, 0), + compressedSize: UINT32_LE.get(array4, 8), + uncompressedSize: UINT32_LE.get(array4, 12) + }; + }, + len: 16 + }; + LocalFileHeaderToken = { + get(array4) { + const flags = UINT16_LE.get(array4, 6); + return { + signature: UINT32_LE.get(array4, 0), + minVersion: UINT16_LE.get(array4, 4), + dataDescriptor: !!(flags & 8), + compressedMethod: UINT16_LE.get(array4, 8), + compressedSize: UINT32_LE.get(array4, 18), + uncompressedSize: UINT32_LE.get(array4, 22), + filenameLength: UINT16_LE.get(array4, 26), + extraFieldLength: UINT16_LE.get(array4, 28), + filename: null + }; + }, + len: 30 + }; + EndOfCentralDirectoryRecordToken = { + get(array4) { + return { + signature: UINT32_LE.get(array4, 0), + nrOfThisDisk: UINT16_LE.get(array4, 4), + nrOfThisDiskWithTheStart: UINT16_LE.get(array4, 6), + nrOfEntriesOnThisDisk: UINT16_LE.get(array4, 8), + nrOfEntriesOfSize: UINT16_LE.get(array4, 10), + sizeOfCd: UINT32_LE.get(array4, 12), + offsetOfStartOfCd: UINT32_LE.get(array4, 16), + zipFileCommentLength: UINT16_LE.get(array4, 20) + }; + }, + len: 22 + }; + FileHeader = { + get(array4) { + const flags = UINT16_LE.get(array4, 8); + return { + signature: UINT32_LE.get(array4, 0), + minVersion: UINT16_LE.get(array4, 6), + dataDescriptor: !!(flags & 8), + compressedMethod: UINT16_LE.get(array4, 10), + compressedSize: UINT32_LE.get(array4, 20), + uncompressedSize: UINT32_LE.get(array4, 24), + filenameLength: UINT16_LE.get(array4, 28), + extraFieldLength: UINT16_LE.get(array4, 30), + fileCommentLength: UINT16_LE.get(array4, 32), + relativeOffsetOfLocalHeader: UINT32_LE.get(array4, 42), + filename: null + }; + }, + len: 46 + }; + } +}); + +// node_modules/.pnpm/@tokenizer+inflate@0.4.1/node_modules/@tokenizer/inflate/lib/ZipHandler.js +function signatureToArray(signature) { + const signatureBytes = new Uint8Array(UINT32_LE.len); + UINT32_LE.put(signatureBytes, 0, signature); + return signatureBytes; +} +function indexOf(buffer, portion) { + const bufferLength = buffer.length; + const portionLength = portion.length; + if (portionLength > bufferLength) + return -1; + for (let i = 0; i <= bufferLength - portionLength; i++) { + let found = true; + for (let j = 0; j < portionLength; j++) { + if (buffer[i + j] !== portion[j]) { + found = false; + break; + } + } + if (found) { + return i; + } + } + return -1; +} +function mergeArrays(chunks) { + const totalLength = chunks.reduce((acc, curr) => acc + curr.length, 0); + const mergedArray = new Uint8Array(totalLength); + let offset = 0; + for (const chunk of chunks) { + mergedArray.set(chunk, offset); + offset += chunk.length; + } + return mergedArray; +} +var import_debug, debug, syncBufferSize, ddSignatureArray, eocdSignatureBytes, ZipHandler; +var init_ZipHandler = __esm({ + "node_modules/.pnpm/@tokenizer+inflate@0.4.1/node_modules/@tokenizer/inflate/lib/ZipHandler.js"() { + init_lib3(); + import_debug = __toESM(require_src2(), 1); + init_ZipToken(); + debug = (0, import_debug.default)("tokenizer:inflate"); + syncBufferSize = 256 * 1024; + ddSignatureArray = signatureToArray(Signature.DataDescriptor); + eocdSignatureBytes = signatureToArray(Signature.EndOfCentralDirectory); + ZipHandler = class _ZipHandler { + constructor(tokenizer) { + this.tokenizer = tokenizer; + this.syncBuffer = new Uint8Array(syncBufferSize); + } + async isZip() { + return await this.peekSignature() === Signature.LocalFileHeader; + } + peekSignature() { + return this.tokenizer.peekToken(UINT32_LE); + } + async findEndOfCentralDirectoryLocator() { + const randomReadTokenizer = this.tokenizer; + const chunkLength = Math.min(16 * 1024, randomReadTokenizer.fileInfo.size); + const buffer = this.syncBuffer.subarray(0, chunkLength); + await this.tokenizer.readBuffer(buffer, { position: randomReadTokenizer.fileInfo.size - chunkLength }); + for (let i = buffer.length - 4; i >= 0; i--) { + if (buffer[i] === eocdSignatureBytes[0] && buffer[i + 1] === eocdSignatureBytes[1] && buffer[i + 2] === eocdSignatureBytes[2] && buffer[i + 3] === eocdSignatureBytes[3]) { + return randomReadTokenizer.fileInfo.size - chunkLength + i; + } + } + return -1; + } + async readCentralDirectory() { + if (!this.tokenizer.supportsRandomAccess()) { + debug("Cannot reading central-directory without random-read support"); + return; + } + debug("Reading central-directory..."); + const pos = this.tokenizer.position; + const offset = await this.findEndOfCentralDirectoryLocator(); + if (offset > 0) { + debug("Central-directory 32-bit signature found"); + const eocdHeader = await this.tokenizer.readToken(EndOfCentralDirectoryRecordToken, offset); + const files = []; + this.tokenizer.setPosition(eocdHeader.offsetOfStartOfCd); + for (let n = 0; n < eocdHeader.nrOfEntriesOfSize; ++n) { + const entry = await this.tokenizer.readToken(FileHeader); + if (entry.signature !== Signature.CentralFileHeader) { + throw new Error("Expected Central-File-Header signature"); + } + entry.filename = await this.tokenizer.readToken(new StringType(entry.filenameLength, "utf-8")); + await this.tokenizer.ignore(entry.extraFieldLength); + await this.tokenizer.ignore(entry.fileCommentLength); + files.push(entry); + debug(`Add central-directory file-entry: n=${n + 1}/${files.length}: filename=${files[n].filename}`); + } + this.tokenizer.setPosition(pos); + return files; + } + this.tokenizer.setPosition(pos); + } + async unzip(fileCb) { + const entries = await this.readCentralDirectory(); + if (entries) { + return this.iterateOverCentralDirectory(entries, fileCb); + } + let stop = false; + do { + const zipHeader = await this.readLocalFileHeader(); + if (!zipHeader) + break; + const next2 = fileCb(zipHeader); + stop = !!next2.stop; + let fileData; + await this.tokenizer.ignore(zipHeader.extraFieldLength); + if (zipHeader.dataDescriptor && zipHeader.compressedSize === 0) { + const chunks = []; + let len = syncBufferSize; + debug("Compressed-file-size unknown, scanning for next data-descriptor-signature...."); + let nextHeaderIndex = -1; + while (nextHeaderIndex < 0 && len === syncBufferSize) { + len = await this.tokenizer.peekBuffer(this.syncBuffer, { mayBeLess: true }); + nextHeaderIndex = indexOf(this.syncBuffer.subarray(0, len), ddSignatureArray); + const size = nextHeaderIndex >= 0 ? nextHeaderIndex : len; + if (next2.handler) { + const data = new Uint8Array(size); + await this.tokenizer.readBuffer(data); + chunks.push(data); + } else { + await this.tokenizer.ignore(size); + } + } + debug(`Found data-descriptor-signature at pos=${this.tokenizer.position}`); + if (next2.handler) { + await this.inflate(zipHeader, mergeArrays(chunks), next2.handler); + } + } else { + if (next2.handler) { + debug(`Reading compressed-file-data: ${zipHeader.compressedSize} bytes`); + fileData = new Uint8Array(zipHeader.compressedSize); + await this.tokenizer.readBuffer(fileData); + await this.inflate(zipHeader, fileData, next2.handler); + } else { + debug(`Ignoring compressed-file-data: ${zipHeader.compressedSize} bytes`); + await this.tokenizer.ignore(zipHeader.compressedSize); + } + } + debug(`Reading data-descriptor at pos=${this.tokenizer.position}`); + if (zipHeader.dataDescriptor) { + const dataDescriptor = await this.tokenizer.readToken(DataDescriptor); + if (dataDescriptor.signature !== 134695760) { + throw new Error(`Expected data-descriptor-signature at position ${this.tokenizer.position - DataDescriptor.len}`); + } + } + } while (!stop); + } + async iterateOverCentralDirectory(entries, fileCb) { + for (const fileHeader of entries) { + const next2 = fileCb(fileHeader); + if (next2.handler) { + this.tokenizer.setPosition(fileHeader.relativeOffsetOfLocalHeader); + const zipHeader = await this.readLocalFileHeader(); + if (zipHeader) { + await this.tokenizer.ignore(zipHeader.extraFieldLength); + const fileData = new Uint8Array(fileHeader.compressedSize); + await this.tokenizer.readBuffer(fileData); + await this.inflate(zipHeader, fileData, next2.handler); + } + } + if (next2.stop) + break; + } + } + async inflate(zipHeader, fileData, cb) { + if (zipHeader.compressedMethod === 0) { + return cb(fileData); + } + if (zipHeader.compressedMethod !== 8) { + throw new Error(`Unsupported ZIP compression method: ${zipHeader.compressedMethod}`); + } + debug(`Decompress filename=${zipHeader.filename}, compressed-size=${fileData.length}`); + const uncompressedData = await _ZipHandler.decompressDeflateRaw(fileData); + return cb(uncompressedData); + } + static async decompressDeflateRaw(data) { + const input = new ReadableStream({ + start(controller) { + controller.enqueue(data); + controller.close(); + } + }); + const ds = new DecompressionStream("deflate-raw"); + const output = input.pipeThrough(ds); + try { + const response = new Response(output); + const buffer = await response.arrayBuffer(); + return new Uint8Array(buffer); + } catch (err) { + const message = err instanceof Error ? `Failed to deflate ZIP entry: ${err.message}` : "Unknown decompression error in ZIP entry"; + throw new TypeError(message); + } + } + async readLocalFileHeader() { + const signature = await this.tokenizer.peekToken(UINT32_LE); + if (signature === Signature.LocalFileHeader) { + const header = await this.tokenizer.readToken(LocalFileHeaderToken); + header.filename = await this.tokenizer.readToken(new StringType(header.filenameLength, "utf-8")); + return header; + } + if (signature === Signature.CentralFileHeader) { + return false; + } + if (signature === 3759263696) { + throw new Error("Encrypted ZIP"); + } + throw new Error("Unexpected signature"); + } + }; + } +}); + +// node_modules/.pnpm/@tokenizer+inflate@0.4.1/node_modules/@tokenizer/inflate/lib/GzipHandler.js +var GzipHandler; +var init_GzipHandler = __esm({ + "node_modules/.pnpm/@tokenizer+inflate@0.4.1/node_modules/@tokenizer/inflate/lib/GzipHandler.js"() { + GzipHandler = class { + constructor(tokenizer) { + this.tokenizer = tokenizer; + } + inflate() { + const tokenizer = this.tokenizer; + return new ReadableStream({ + async pull(controller) { + const buffer = new Uint8Array(1024); + const size = await tokenizer.readBuffer(buffer, { mayBeLess: true }); + if (size === 0) { + controller.close(); + return; + } + controller.enqueue(buffer.subarray(0, size)); + } + }).pipeThrough(new DecompressionStream("gzip")); + } + }; + } +}); + +// node_modules/.pnpm/@tokenizer+inflate@0.4.1/node_modules/@tokenizer/inflate/lib/index.js +var init_lib4 = __esm({ + "node_modules/.pnpm/@tokenizer+inflate@0.4.1/node_modules/@tokenizer/inflate/lib/index.js"() { + init_ZipHandler(); + init_GzipHandler(); + } +}); + +// node_modules/.pnpm/uint8array-extras@1.5.0/node_modules/uint8array-extras/index.js +function getUintBE(view) { + const { byteLength } = view; + if (byteLength === 6) { + return view.getUint16(0) * 2 ** 32 + view.getUint32(2); + } + if (byteLength === 5) { + return view.getUint8(0) * 2 ** 32 + view.getUint32(1); + } + if (byteLength === 4) { + return view.getUint32(0); + } + if (byteLength === 3) { + return view.getUint8(0) * 2 ** 16 + view.getUint16(1); + } + if (byteLength === 2) { + return view.getUint16(0); + } + if (byteLength === 1) { + return view.getUint8(0); + } +} +var cachedDecoders, cachedEncoder, byteToHexLookupTable; +var init_uint8array_extras = __esm({ + "node_modules/.pnpm/uint8array-extras@1.5.0/node_modules/uint8array-extras/index.js"() { + cachedDecoders = { + utf8: new globalThis.TextDecoder("utf8") + }; + cachedEncoder = new globalThis.TextEncoder(); + byteToHexLookupTable = Array.from({ length: 256 }, (_, index) => index.toString(16).padStart(2, "0")); + } +}); + +// node_modules/.pnpm/file-type@21.3.0/node_modules/file-type/util.js +function stringToBytes(string7, encoding) { + if (encoding === "utf-16le") { + const bytes = []; + for (let index = 0; index < string7.length; index++) { + const code = string7.charCodeAt(index); + bytes.push(code & 255, code >> 8 & 255); + } + return bytes; + } + if (encoding === "utf-16be") { + const bytes = []; + for (let index = 0; index < string7.length; index++) { + const code = string7.charCodeAt(index); + bytes.push(code >> 8 & 255, code & 255); + } + return bytes; + } + return [...string7].map((character) => character.charCodeAt(0)); +} +function tarHeaderChecksumMatches(arrayBuffer, offset = 0) { + const readSum = Number.parseInt(new StringType(6).get(arrayBuffer, 148).replace(/\0.*$/, "").trim(), 8); + if (Number.isNaN(readSum)) { + return false; + } + let sum = 8 * 32; + for (let index = offset; index < offset + 148; index++) { + sum += arrayBuffer[index]; + } + for (let index = offset + 156; index < offset + 512; index++) { + sum += arrayBuffer[index]; + } + return readSum === sum; +} +var uint32SyncSafeToken; +var init_util3 = __esm({ + "node_modules/.pnpm/file-type@21.3.0/node_modules/file-type/util.js"() { + init_lib3(); + uint32SyncSafeToken = { + get: (buffer, offset) => buffer[offset + 3] & 127 | buffer[offset + 2] << 7 | buffer[offset + 1] << 14 | buffer[offset] << 21, + len: 4 + }; + } +}); + +// node_modules/.pnpm/file-type@21.3.0/node_modules/file-type/supported.js +var extensions, mimeTypes; +var init_supported = __esm({ + "node_modules/.pnpm/file-type@21.3.0/node_modules/file-type/supported.js"() { + extensions = [ + "jpg", + "png", + "apng", + "gif", + "webp", + "flif", + "xcf", + "cr2", + "cr3", + "orf", + "arw", + "dng", + "nef", + "rw2", + "raf", + "tif", + "bmp", + "icns", + "jxr", + "psd", + "indd", + "zip", + "tar", + "rar", + "gz", + "bz2", + "7z", + "dmg", + "mp4", + "mid", + "mkv", + "webm", + "mov", + "avi", + "mpg", + "mp2", + "mp3", + "m4a", + "oga", + "ogg", + "ogv", + "opus", + "flac", + "wav", + "spx", + "amr", + "pdf", + "epub", + "elf", + "macho", + "exe", + "swf", + "rtf", + "wasm", + "woff", + "woff2", + "eot", + "ttf", + "otf", + "ttc", + "ico", + "flv", + "ps", + "xz", + "sqlite", + "nes", + "crx", + "xpi", + "cab", + "deb", + "ar", + "rpm", + "Z", + "lz", + "cfb", + "mxf", + "mts", + "blend", + "bpg", + "docx", + "pptx", + "xlsx", + "3gp", + "3g2", + "j2c", + "jp2", + "jpm", + "jpx", + "mj2", + "aif", + "qcp", + "odt", + "ods", + "odp", + "xml", + "mobi", + "heic", + "cur", + "ktx", + "ape", + "wv", + "dcm", + "ics", + "glb", + "pcap", + "dsf", + "lnk", + "alias", + "voc", + "ac3", + "m4v", + "m4p", + "m4b", + "f4v", + "f4p", + "f4b", + "f4a", + "mie", + "asf", + "ogm", + "ogx", + "mpc", + "arrow", + "shp", + "aac", + "mp1", + "it", + "s3m", + "xm", + "skp", + "avif", + "eps", + "lzh", + "pgp", + "asar", + "stl", + "chm", + "3mf", + "zst", + "jxl", + "vcf", + "jls", + "pst", + "dwg", + "parquet", + "class", + "arj", + "cpio", + "ace", + "avro", + "icc", + "fbx", + "vsdx", + "vtt", + "apk", + "drc", + "lz4", + "potx", + "xltx", + "dotx", + "xltm", + "ott", + "ots", + "otp", + "odg", + "otg", + "xlsm", + "docm", + "dotm", + "potm", + "pptm", + "jar", + "jmp", + "rm", + "sav", + "ppsm", + "ppsx", + "tar.gz", + "reg", + "dat" + ]; + mimeTypes = [ + "image/jpeg", + "image/png", + "image/gif", + "image/webp", + "image/flif", + "image/x-xcf", + "image/x-canon-cr2", + "image/x-canon-cr3", + "image/tiff", + "image/bmp", + "image/vnd.ms-photo", + "image/vnd.adobe.photoshop", + "application/x-indesign", + "application/epub+zip", + "application/x-xpinstall", + "application/vnd.ms-powerpoint.slideshow.macroenabled.12", + "application/vnd.oasis.opendocument.text", + "application/vnd.oasis.opendocument.spreadsheet", + "application/vnd.oasis.opendocument.presentation", + "application/vnd.openxmlformats-officedocument.wordprocessingml.document", + "application/vnd.openxmlformats-officedocument.presentationml.presentation", + "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", + "application/vnd.openxmlformats-officedocument.presentationml.slideshow", + "application/zip", + "application/x-tar", + "application/x-rar-compressed", + "application/gzip", + "application/x-bzip2", + "application/x-7z-compressed", + "application/x-apple-diskimage", + "application/vnd.apache.arrow.file", + "video/mp4", + "audio/midi", + "video/matroska", + "video/webm", + "video/quicktime", + "video/vnd.avi", + "audio/wav", + "audio/qcelp", + "audio/x-ms-asf", + "video/x-ms-asf", + "application/vnd.ms-asf", + "video/mpeg", + "video/3gpp", + "audio/mpeg", + "audio/mp4", + // RFC 4337 + "video/ogg", + "audio/ogg", + "audio/ogg; codecs=opus", + "application/ogg", + "audio/flac", + "audio/ape", + "audio/wavpack", + "audio/amr", + "application/pdf", + "application/x-elf", + "application/x-mach-binary", + "application/x-msdownload", + "application/x-shockwave-flash", + "application/rtf", + "application/wasm", + "font/woff", + "font/woff2", + "application/vnd.ms-fontobject", + "font/ttf", + "font/otf", + "font/collection", + "image/x-icon", + "video/x-flv", + "application/postscript", + "application/eps", + "application/x-xz", + "application/x-sqlite3", + "application/x-nintendo-nes-rom", + "application/x-google-chrome-extension", + "application/vnd.ms-cab-compressed", + "application/x-deb", + "application/x-unix-archive", + "application/x-rpm", + "application/x-compress", + "application/x-lzip", + "application/x-cfb", + "application/x-mie", + "application/mxf", + "video/mp2t", + "application/x-blender", + "image/bpg", + "image/j2c", + "image/jp2", + "image/jpx", + "image/jpm", + "image/mj2", + "audio/aiff", + "application/xml", + "application/x-mobipocket-ebook", + "image/heif", + "image/heif-sequence", + "image/heic", + "image/heic-sequence", + "image/icns", + "image/ktx", + "application/dicom", + "audio/x-musepack", + "text/calendar", + "text/vcard", + "text/vtt", + "model/gltf-binary", + "application/vnd.tcpdump.pcap", + "audio/x-dsf", + // Non-standard + "application/x.ms.shortcut", + // Invented by us + "application/x.apple.alias", + // Invented by us + "audio/x-voc", + "audio/vnd.dolby.dd-raw", + "audio/x-m4a", + "image/apng", + "image/x-olympus-orf", + "image/x-sony-arw", + "image/x-adobe-dng", + "image/x-nikon-nef", + "image/x-panasonic-rw2", + "image/x-fujifilm-raf", + "video/x-m4v", + "video/3gpp2", + "application/x-esri-shape", + "audio/aac", + "audio/x-it", + "audio/x-s3m", + "audio/x-xm", + "video/MP1S", + "video/MP2P", + "application/vnd.sketchup.skp", + "image/avif", + "application/x-lzh-compressed", + "application/pgp-encrypted", + "application/x-asar", + "model/stl", + "application/vnd.ms-htmlhelp", + "model/3mf", + "image/jxl", + "application/zstd", + "image/jls", + "application/vnd.ms-outlook", + "image/vnd.dwg", + "application/vnd.apache.parquet", + "application/java-vm", + "application/x-arj", + "application/x-cpio", + "application/x-ace-compressed", + "application/avro", + "application/vnd.iccprofile", + "application/x.autodesk.fbx", + // Invented by us + "application/vnd.visio", + "application/vnd.android.package-archive", + "application/vnd.google.draco", + // Invented by us + "application/x-lz4", + // Invented by us + "application/vnd.openxmlformats-officedocument.presentationml.template", + "application/vnd.openxmlformats-officedocument.spreadsheetml.template", + "application/vnd.openxmlformats-officedocument.wordprocessingml.template", + "application/vnd.ms-excel.template.macroenabled.12", + "application/vnd.oasis.opendocument.text-template", + "application/vnd.oasis.opendocument.spreadsheet-template", + "application/vnd.oasis.opendocument.presentation-template", + "application/vnd.oasis.opendocument.graphics", + "application/vnd.oasis.opendocument.graphics-template", + "application/vnd.ms-excel.sheet.macroenabled.12", + "application/vnd.ms-word.document.macroenabled.12", + "application/vnd.ms-word.template.macroenabled.12", + "application/vnd.ms-powerpoint.template.macroenabled.12", + "application/vnd.ms-powerpoint.presentation.macroenabled.12", + "application/java-archive", + "application/vnd.rn-realmedia", + "application/x-spss-sav", + "application/x-ms-regedit", + "application/x-ft-windows-registry-hive", + "application/x-jmp-data" + ]; + } +}); + +// node_modules/.pnpm/file-type@21.3.0/node_modules/file-type/core.js +async function fileTypeFromBuffer(input, options) { + return new FileTypeParser(options).fromBuffer(input); +} +function getFileTypeFromMimeType(mimeType) { + mimeType = mimeType.toLowerCase(); + switch (mimeType) { + case "application/epub+zip": + return { + ext: "epub", + mime: mimeType + }; + case "application/vnd.oasis.opendocument.text": + return { + ext: "odt", + mime: mimeType + }; + case "application/vnd.oasis.opendocument.text-template": + return { + ext: "ott", + mime: mimeType + }; + case "application/vnd.oasis.opendocument.spreadsheet": + return { + ext: "ods", + mime: mimeType + }; + case "application/vnd.oasis.opendocument.spreadsheet-template": + return { + ext: "ots", + mime: mimeType + }; + case "application/vnd.oasis.opendocument.presentation": + return { + ext: "odp", + mime: mimeType + }; + case "application/vnd.oasis.opendocument.presentation-template": + return { + ext: "otp", + mime: mimeType + }; + case "application/vnd.oasis.opendocument.graphics": + return { + ext: "odg", + mime: mimeType + }; + case "application/vnd.oasis.opendocument.graphics-template": + return { + ext: "otg", + mime: mimeType + }; + case "application/vnd.openxmlformats-officedocument.presentationml.slideshow": + return { + ext: "ppsx", + mime: mimeType + }; + case "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet": + return { + ext: "xlsx", + mime: mimeType + }; + case "application/vnd.ms-excel.sheet.macroenabled": + return { + ext: "xlsm", + mime: "application/vnd.ms-excel.sheet.macroenabled.12" + }; + case "application/vnd.openxmlformats-officedocument.spreadsheetml.template": + return { + ext: "xltx", + mime: mimeType + }; + case "application/vnd.ms-excel.template.macroenabled": + return { + ext: "xltm", + mime: "application/vnd.ms-excel.template.macroenabled.12" + }; + case "application/vnd.ms-powerpoint.slideshow.macroenabled": + return { + ext: "ppsm", + mime: "application/vnd.ms-powerpoint.slideshow.macroenabled.12" + }; + case "application/vnd.openxmlformats-officedocument.wordprocessingml.document": + return { + ext: "docx", + mime: mimeType + }; + case "application/vnd.ms-word.document.macroenabled": + return { + ext: "docm", + mime: "application/vnd.ms-word.document.macroenabled.12" + }; + case "application/vnd.openxmlformats-officedocument.wordprocessingml.template": + return { + ext: "dotx", + mime: mimeType + }; + case "application/vnd.ms-word.template.macroenabledtemplate": + return { + ext: "dotm", + mime: "application/vnd.ms-word.template.macroenabled.12" + }; + case "application/vnd.openxmlformats-officedocument.presentationml.template": + return { + ext: "potx", + mime: mimeType + }; + case "application/vnd.ms-powerpoint.template.macroenabled": + return { + ext: "potm", + mime: "application/vnd.ms-powerpoint.template.macroenabled.12" + }; + case "application/vnd.openxmlformats-officedocument.presentationml.presentation": + return { + ext: "pptx", + mime: mimeType + }; + case "application/vnd.ms-powerpoint.presentation.macroenabled": + return { + ext: "pptm", + mime: "application/vnd.ms-powerpoint.presentation.macroenabled.12" + }; + case "application/vnd.ms-visio.drawing": + return { + ext: "vsdx", + mime: "application/vnd.visio" + }; + case "application/vnd.ms-package.3dmanufacturing-3dmodel+xml": + return { + ext: "3mf", + mime: "model/3mf" + }; + default: + } +} +function _check2(buffer, headers, options) { + options = { + offset: 0, + ...options + }; + for (const [index, header] of headers.entries()) { + if (options.mask) { + if (header !== (options.mask[index] & buffer[index + options.offset])) { + return false; + } + } else if (header !== buffer[index + options.offset]) { + return false; + } + } + return true; +} +var reasonableDetectionSizeInBytes, FileTypeParser, supportedExtensions, supportedMimeTypes; +var init_core4 = __esm({ + "node_modules/.pnpm/file-type@21.3.0/node_modules/file-type/core.js"() { + init_lib3(); + init_core3(); + init_lib4(); + init_uint8array_extras(); + init_util3(); + init_supported(); + reasonableDetectionSizeInBytes = 4100; + FileTypeParser = class { + constructor(options) { + this.options = { + mpegOffsetTolerance: 0, + ...options + }; + this.detectors = [ + ...options?.customDetectors ?? [], + { id: "core", detect: this.detectConfident }, + { id: "core.imprecise", detect: this.detectImprecise } + ]; + this.tokenizerOptions = { + abortSignal: options?.signal + }; + } + async fromTokenizer(tokenizer) { + const initialPosition = tokenizer.position; + for (const detector of this.detectors) { + const fileType = await detector.detect(tokenizer); + if (fileType) { + return fileType; + } + if (initialPosition !== tokenizer.position) { + return void 0; + } + } + } + async fromBuffer(input) { + if (!(input instanceof Uint8Array || input instanceof ArrayBuffer)) { + throw new TypeError(`Expected the \`input\` argument to be of type \`Uint8Array\` or \`ArrayBuffer\`, got \`${typeof input}\``); + } + const buffer = input instanceof Uint8Array ? input : new Uint8Array(input); + if (!(buffer?.length > 1)) { + return; + } + return this.fromTokenizer(fromBuffer(buffer, this.tokenizerOptions)); + } + async fromBlob(blob) { + const tokenizer = fromBlob(blob, this.tokenizerOptions); + try { + return await this.fromTokenizer(tokenizer); + } finally { + await tokenizer.close(); + } + } + async fromStream(stream) { + const tokenizer = fromWebStream(stream, this.tokenizerOptions); + try { + return await this.fromTokenizer(tokenizer); + } finally { + await tokenizer.close(); + } + } + async toDetectionStream(stream, options) { + const { sampleSize = reasonableDetectionSizeInBytes } = options; + let detectedFileType; + let firstChunk; + const reader = stream.getReader({ mode: "byob" }); + try { + const { value: chunk, done } = await reader.read(new Uint8Array(sampleSize)); + firstChunk = chunk; + if (!done && chunk) { + try { + detectedFileType = await this.fromBuffer(chunk.subarray(0, sampleSize)); + } catch (error50) { + if (!(error50 instanceof EndOfStreamError)) { + throw error50; + } + detectedFileType = void 0; + } + } + firstChunk = chunk; + } finally { + reader.releaseLock(); + } + const transformStream = new TransformStream({ + async start(controller) { + controller.enqueue(firstChunk); + }, + transform(chunk, controller) { + controller.enqueue(chunk); + } + }); + const newStream = stream.pipeThrough(transformStream); + newStream.fileType = detectedFileType; + return newStream; + } + check(header, options) { + return _check2(this.buffer, header, options); + } + checkString(header, options) { + return this.check(stringToBytes(header, options?.encoding), options); + } + // Detections with a high degree of certainty in identifying the correct file type + detectConfident = async (tokenizer) => { + this.buffer = new Uint8Array(reasonableDetectionSizeInBytes); + if (tokenizer.fileInfo.size === void 0) { + tokenizer.fileInfo.size = Number.MAX_SAFE_INTEGER; + } + this.tokenizer = tokenizer; + await tokenizer.peekBuffer(this.buffer, { length: 32, mayBeLess: true }); + if (this.check([66, 77])) { + return { + ext: "bmp", + mime: "image/bmp" + }; + } + if (this.check([11, 119])) { + return { + ext: "ac3", + mime: "audio/vnd.dolby.dd-raw" + }; + } + if (this.check([120, 1])) { + return { + ext: "dmg", + mime: "application/x-apple-diskimage" + }; + } + if (this.check([77, 90])) { + return { + ext: "exe", + mime: "application/x-msdownload" + }; + } + if (this.check([37, 33])) { + await tokenizer.peekBuffer(this.buffer, { length: 24, mayBeLess: true }); + if (this.checkString("PS-Adobe-", { offset: 2 }) && this.checkString(" EPSF-", { offset: 14 })) { + return { + ext: "eps", + mime: "application/eps" + }; + } + return { + ext: "ps", + mime: "application/postscript" + }; + } + if (this.check([31, 160]) || this.check([31, 157])) { + return { + ext: "Z", + mime: "application/x-compress" + }; + } + if (this.check([199, 113])) { + return { + ext: "cpio", + mime: "application/x-cpio" + }; + } + if (this.check([96, 234])) { + return { + ext: "arj", + mime: "application/x-arj" + }; + } + if (this.check([239, 187, 191])) { + this.tokenizer.ignore(3); + return this.detectConfident(tokenizer); + } + if (this.check([71, 73, 70])) { + return { + ext: "gif", + mime: "image/gif" + }; + } + if (this.check([73, 73, 188])) { + return { + ext: "jxr", + mime: "image/vnd.ms-photo" + }; + } + if (this.check([31, 139, 8])) { + const gzipHandler = new GzipHandler(tokenizer); + const stream = gzipHandler.inflate(); + let shouldCancelStream = true; + try { + let compressedFileType; + try { + compressedFileType = await this.fromStream(stream); + } catch { + shouldCancelStream = false; + } + if (compressedFileType && compressedFileType.ext === "tar") { + return { + ext: "tar.gz", + mime: "application/gzip" + }; + } + } finally { + if (shouldCancelStream) { + await stream.cancel(); + } + } + return { + ext: "gz", + mime: "application/gzip" + }; + } + if (this.check([66, 90, 104])) { + return { + ext: "bz2", + mime: "application/x-bzip2" + }; + } + if (this.checkString("ID3")) { + await tokenizer.ignore(6); + const id3HeaderLength = await tokenizer.readToken(uint32SyncSafeToken); + if (tokenizer.position + id3HeaderLength > tokenizer.fileInfo.size) { + return { + ext: "mp3", + mime: "audio/mpeg" + }; + } + await tokenizer.ignore(id3HeaderLength); + return this.fromTokenizer(tokenizer); + } + if (this.checkString("MP+")) { + return { + ext: "mpc", + mime: "audio/x-musepack" + }; + } + if ((this.buffer[0] === 67 || this.buffer[0] === 70) && this.check([87, 83], { offset: 1 })) { + return { + ext: "swf", + mime: "application/x-shockwave-flash" + }; + } + if (this.check([255, 216, 255])) { + if (this.check([247], { offset: 3 })) { + return { + ext: "jls", + mime: "image/jls" + }; + } + return { + ext: "jpg", + mime: "image/jpeg" + }; + } + if (this.check([79, 98, 106, 1])) { + return { + ext: "avro", + mime: "application/avro" + }; + } + if (this.checkString("FLIF")) { + return { + ext: "flif", + mime: "image/flif" + }; + } + if (this.checkString("8BPS")) { + return { + ext: "psd", + mime: "image/vnd.adobe.photoshop" + }; + } + if (this.checkString("MPCK")) { + return { + ext: "mpc", + mime: "audio/x-musepack" + }; + } + if (this.checkString("FORM")) { + return { + ext: "aif", + mime: "audio/aiff" + }; + } + if (this.checkString("icns", { offset: 0 })) { + return { + ext: "icns", + mime: "image/icns" + }; + } + if (this.check([80, 75, 3, 4])) { + let fileType; + await new ZipHandler(tokenizer).unzip((zipHeader) => { + switch (zipHeader.filename) { + case "META-INF/mozilla.rsa": + fileType = { + ext: "xpi", + mime: "application/x-xpinstall" + }; + return { + stop: true + }; + case "META-INF/MANIFEST.MF": + fileType = { + ext: "jar", + mime: "application/java-archive" + }; + return { + stop: true + }; + case "mimetype": + return { + async handler(fileData) { + const mimeType = new TextDecoder("utf-8").decode(fileData).trim(); + fileType = getFileTypeFromMimeType(mimeType); + }, + stop: true + }; + case "[Content_Types].xml": + return { + async handler(fileData) { + let xmlContent = new TextDecoder("utf-8").decode(fileData); + const endPos = xmlContent.indexOf('.main+xml"'); + if (endPos === -1) { + const mimeType = "application/vnd.ms-package.3dmanufacturing-3dmodel+xml"; + if (xmlContent.includes(`ContentType="${mimeType}"`)) { + fileType = getFileTypeFromMimeType(mimeType); + } + } else { + xmlContent = xmlContent.slice(0, Math.max(0, endPos)); + const firstPos = xmlContent.lastIndexOf('"'); + const mimeType = xmlContent.slice(Math.max(0, firstPos + 1)); + fileType = getFileTypeFromMimeType(mimeType); + } + }, + stop: true + }; + default: + if (/classes\d*\.dex/.test(zipHeader.filename)) { + fileType = { + ext: "apk", + mime: "application/vnd.android.package-archive" + }; + return { stop: true }; + } + return {}; + } + }).catch((error50) => { + if (!(error50 instanceof EndOfStreamError)) { + throw error50; + } + }); + return fileType ?? { + ext: "zip", + mime: "application/zip" + }; + } + if (this.checkString("OggS")) { + await tokenizer.ignore(28); + const type2 = new Uint8Array(8); + await tokenizer.readBuffer(type2); + if (_check2(type2, [79, 112, 117, 115, 72, 101, 97, 100])) { + return { + ext: "opus", + mime: "audio/ogg; codecs=opus" + }; + } + if (_check2(type2, [128, 116, 104, 101, 111, 114, 97])) { + return { + ext: "ogv", + mime: "video/ogg" + }; + } + if (_check2(type2, [1, 118, 105, 100, 101, 111, 0])) { + return { + ext: "ogm", + mime: "video/ogg" + }; + } + if (_check2(type2, [127, 70, 76, 65, 67])) { + return { + ext: "oga", + mime: "audio/ogg" + }; + } + if (_check2(type2, [83, 112, 101, 101, 120, 32, 32])) { + return { + ext: "spx", + mime: "audio/ogg" + }; + } + if (_check2(type2, [1, 118, 111, 114, 98, 105, 115])) { + return { + ext: "ogg", + mime: "audio/ogg" + }; + } + return { + ext: "ogx", + mime: "application/ogg" + }; + } + if (this.check([80, 75]) && (this.buffer[2] === 3 || this.buffer[2] === 5 || this.buffer[2] === 7) && (this.buffer[3] === 4 || this.buffer[3] === 6 || this.buffer[3] === 8)) { + return { + ext: "zip", + mime: "application/zip" + }; + } + if (this.checkString("MThd")) { + return { + ext: "mid", + mime: "audio/midi" + }; + } + if (this.checkString("wOFF") && (this.check([0, 1, 0, 0], { offset: 4 }) || this.checkString("OTTO", { offset: 4 }))) { + return { + ext: "woff", + mime: "font/woff" + }; + } + if (this.checkString("wOF2") && (this.check([0, 1, 0, 0], { offset: 4 }) || this.checkString("OTTO", { offset: 4 }))) { + return { + ext: "woff2", + mime: "font/woff2" + }; + } + if (this.check([212, 195, 178, 161]) || this.check([161, 178, 195, 212])) { + return { + ext: "pcap", + mime: "application/vnd.tcpdump.pcap" + }; + } + if (this.checkString("DSD ")) { + return { + ext: "dsf", + mime: "audio/x-dsf" + // Non-standard + }; + } + if (this.checkString("LZIP")) { + return { + ext: "lz", + mime: "application/x-lzip" + }; + } + if (this.checkString("fLaC")) { + return { + ext: "flac", + mime: "audio/flac" + }; + } + if (this.check([66, 80, 71, 251])) { + return { + ext: "bpg", + mime: "image/bpg" + }; + } + if (this.checkString("wvpk")) { + return { + ext: "wv", + mime: "audio/wavpack" + }; + } + if (this.checkString("%PDF")) { + return { + ext: "pdf", + mime: "application/pdf" + }; + } + if (this.check([0, 97, 115, 109])) { + return { + ext: "wasm", + mime: "application/wasm" + }; + } + if (this.check([73, 73])) { + const fileType = await this.readTiffHeader(false); + if (fileType) { + return fileType; + } + } + if (this.check([77, 77])) { + const fileType = await this.readTiffHeader(true); + if (fileType) { + return fileType; + } + } + if (this.checkString("MAC ")) { + return { + ext: "ape", + mime: "audio/ape" + }; + } + if (this.check([26, 69, 223, 163])) { + async function readField() { + const msb = await tokenizer.peekNumber(UINT8); + let mask = 128; + let ic = 0; + while ((msb & mask) === 0 && mask !== 0) { + ++ic; + mask >>= 1; + } + const id = new Uint8Array(ic + 1); + await tokenizer.readBuffer(id); + return id; + } + async function readElement() { + const idField = await readField(); + const lengthField = await readField(); + lengthField[0] ^= 128 >> lengthField.length - 1; + const nrLength = Math.min(6, lengthField.length); + const idView = new DataView(idField.buffer); + const lengthView = new DataView(lengthField.buffer, lengthField.length - nrLength, nrLength); + return { + id: getUintBE(idView), + len: getUintBE(lengthView) + }; + } + async function readChildren(children) { + while (children > 0) { + const element = await readElement(); + if (element.id === 17026) { + const rawValue = await tokenizer.readToken(new StringType(element.len)); + return rawValue.replaceAll(/\00.*$/g, ""); + } + await tokenizer.ignore(element.len); + --children; + } + } + const re = await readElement(); + const documentType = await readChildren(re.len); + switch (documentType) { + case "webm": + return { + ext: "webm", + mime: "video/webm" + }; + case "matroska": + return { + ext: "mkv", + mime: "video/matroska" + }; + default: + return; + } + } + if (this.checkString("SQLi")) { + return { + ext: "sqlite", + mime: "application/x-sqlite3" + }; + } + if (this.check([78, 69, 83, 26])) { + return { + ext: "nes", + mime: "application/x-nintendo-nes-rom" + }; + } + if (this.checkString("Cr24")) { + return { + ext: "crx", + mime: "application/x-google-chrome-extension" + }; + } + if (this.checkString("MSCF") || this.checkString("ISc(")) { + return { + ext: "cab", + mime: "application/vnd.ms-cab-compressed" + }; + } + if (this.check([237, 171, 238, 219])) { + return { + ext: "rpm", + mime: "application/x-rpm" + }; + } + if (this.check([197, 208, 211, 198])) { + return { + ext: "eps", + mime: "application/eps" + }; + } + if (this.check([40, 181, 47, 253])) { + return { + ext: "zst", + mime: "application/zstd" + }; + } + if (this.check([127, 69, 76, 70])) { + return { + ext: "elf", + mime: "application/x-elf" + }; + } + if (this.check([33, 66, 68, 78])) { + return { + ext: "pst", + mime: "application/vnd.ms-outlook" + }; + } + if (this.checkString("PAR1") || this.checkString("PARE")) { + return { + ext: "parquet", + mime: "application/vnd.apache.parquet" + }; + } + if (this.checkString("ttcf")) { + return { + ext: "ttc", + mime: "font/collection" + }; + } + if (this.check([254, 237, 250, 206]) || this.check([254, 237, 250, 207]) || this.check([206, 250, 237, 254]) || this.check([207, 250, 237, 254])) { + return { + ext: "macho", + mime: "application/x-mach-binary" + }; + } + if (this.check([4, 34, 77, 24])) { + return { + ext: "lz4", + mime: "application/x-lz4" + // Invented by us + }; + } + if (this.checkString("regf")) { + return { + ext: "dat", + mime: "application/x-ft-windows-registry-hive" + }; + } + if (this.checkString("$FL2") || this.checkString("$FL3")) { + return { + ext: "sav", + mime: "application/x-spss-sav" + }; + } + if (this.check([79, 84, 84, 79, 0])) { + return { + ext: "otf", + mime: "font/otf" + }; + } + if (this.checkString("#!AMR")) { + return { + ext: "amr", + mime: "audio/amr" + }; + } + if (this.checkString("{\\rtf")) { + return { + ext: "rtf", + mime: "application/rtf" + }; + } + if (this.check([70, 76, 86, 1])) { + return { + ext: "flv", + mime: "video/x-flv" + }; + } + if (this.checkString("IMPM")) { + return { + ext: "it", + mime: "audio/x-it" + }; + } + if (this.checkString("-lh0-", { offset: 2 }) || this.checkString("-lh1-", { offset: 2 }) || this.checkString("-lh2-", { offset: 2 }) || this.checkString("-lh3-", { offset: 2 }) || this.checkString("-lh4-", { offset: 2 }) || this.checkString("-lh5-", { offset: 2 }) || this.checkString("-lh6-", { offset: 2 }) || this.checkString("-lh7-", { offset: 2 }) || this.checkString("-lzs-", { offset: 2 }) || this.checkString("-lz4-", { offset: 2 }) || this.checkString("-lz5-", { offset: 2 }) || this.checkString("-lhd-", { offset: 2 })) { + return { + ext: "lzh", + mime: "application/x-lzh-compressed" + }; + } + if (this.check([0, 0, 1, 186])) { + if (this.check([33], { offset: 4, mask: [241] })) { + return { + ext: "mpg", + // May also be .ps, .mpeg + mime: "video/MP1S" + }; + } + if (this.check([68], { offset: 4, mask: [196] })) { + return { + ext: "mpg", + // May also be .mpg, .m2p, .vob or .sub + mime: "video/MP2P" + }; + } + } + if (this.checkString("ITSF")) { + return { + ext: "chm", + mime: "application/vnd.ms-htmlhelp" + }; + } + if (this.check([202, 254, 186, 190])) { + const machOArchitectureCount = UINT32_BE.get(this.buffer, 4); + const javaClassFileMajorVersion = UINT16_BE.get(this.buffer, 6); + if (machOArchitectureCount > 0 && machOArchitectureCount <= 30) { + return { + ext: "macho", + mime: "application/x-mach-binary" + }; + } + if (javaClassFileMajorVersion > 30) { + return { + ext: "class", + mime: "application/java-vm" + }; + } + } + if (this.checkString(".RMF")) { + return { + ext: "rm", + mime: "application/vnd.rn-realmedia" + }; + } + if (this.checkString("DRACO")) { + return { + ext: "drc", + mime: "application/vnd.google.draco" + // Invented by us + }; + } + if (this.check([253, 55, 122, 88, 90, 0])) { + return { + ext: "xz", + mime: "application/x-xz" + }; + } + if (this.checkString("= 1e3 && version4 <= 1050) { + return { + ext: "dwg", + mime: "image/vnd.dwg" + }; + } + } + if (this.checkString("070707")) { + return { + ext: "cpio", + mime: "application/x-cpio" + }; + } + if (this.checkString("BLENDER")) { + return { + ext: "blend", + mime: "application/x-blender" + }; + } + if (this.checkString("!")) { + await tokenizer.ignore(8); + const string7 = await tokenizer.readToken(new StringType(13, "ascii")); + if (string7 === "debian-binary") { + return { + ext: "deb", + mime: "application/x-deb" + }; + } + return { + ext: "ar", + mime: "application/x-unix-archive" + }; + } + if (this.checkString("WEBVTT") && // One of LF, CR, tab, space, or end of file must follow "WEBVTT" per the spec (see `fixture/fixture-vtt-*.vtt` for examples). Note that `\0` is technically the null character (there is no such thing as an EOF character). However, checking for `\0` gives us the same result as checking for the end of the stream. + ["\n", "\r", " ", " ", "\0"].some((char7) => this.checkString(char7, { offset: 6 }))) { + return { + ext: "vtt", + mime: "text/vtt" + }; + } + if (this.check([137, 80, 78, 71, 13, 10, 26, 10])) { + await tokenizer.ignore(8); + async function readChunkHeader() { + return { + length: await tokenizer.readToken(INT32_BE), + type: await tokenizer.readToken(new StringType(4, "latin1")) + }; + } + do { + const chunk = await readChunkHeader(); + if (chunk.length < 0) { + return; + } + switch (chunk.type) { + case "IDAT": + return { + ext: "png", + mime: "image/png" + }; + case "acTL": + return { + ext: "apng", + mime: "image/apng" + }; + default: + await tokenizer.ignore(chunk.length + 4); + } + } while (tokenizer.position + 8 < tokenizer.fileInfo.size); + return { + ext: "png", + mime: "image/png" + }; + } + if (this.check([65, 82, 82, 79, 87, 49, 0, 0])) { + return { + ext: "arrow", + mime: "application/vnd.apache.arrow.file" + }; + } + if (this.check([103, 108, 84, 70, 2, 0, 0, 0])) { + return { + ext: "glb", + mime: "model/gltf-binary" + }; + } + if (this.check([102, 114, 101, 101], { offset: 4 }) || this.check([109, 100, 97, 116], { offset: 4 }) || this.check([109, 111, 111, 118], { offset: 4 }) || this.check([119, 105, 100, 101], { offset: 4 })) { + return { + ext: "mov", + mime: "video/quicktime" + }; + } + if (this.check([73, 73, 82, 79, 8, 0, 0, 0, 24])) { + return { + ext: "orf", + mime: "image/x-olympus-orf" + }; + } + if (this.checkString("gimp xcf ")) { + return { + ext: "xcf", + mime: "image/x-xcf" + }; + } + if (this.checkString("ftyp", { offset: 4 }) && (this.buffer[8] & 96) !== 0) { + const brandMajor = new StringType(4, "latin1").get(this.buffer, 8).replace("\0", " ").trim(); + switch (brandMajor) { + case "avif": + case "avis": + return { ext: "avif", mime: "image/avif" }; + case "mif1": + return { ext: "heic", mime: "image/heif" }; + case "msf1": + return { ext: "heic", mime: "image/heif-sequence" }; + case "heic": + case "heix": + return { ext: "heic", mime: "image/heic" }; + case "hevc": + case "hevx": + return { ext: "heic", mime: "image/heic-sequence" }; + case "qt": + return { ext: "mov", mime: "video/quicktime" }; + case "M4V": + case "M4VH": + case "M4VP": + return { ext: "m4v", mime: "video/x-m4v" }; + case "M4P": + return { ext: "m4p", mime: "video/mp4" }; + case "M4B": + return { ext: "m4b", mime: "audio/mp4" }; + case "M4A": + return { ext: "m4a", mime: "audio/x-m4a" }; + case "F4V": + return { ext: "f4v", mime: "video/mp4" }; + case "F4P": + return { ext: "f4p", mime: "video/mp4" }; + case "F4A": + return { ext: "f4a", mime: "audio/mp4" }; + case "F4B": + return { ext: "f4b", mime: "audio/mp4" }; + case "crx": + return { ext: "cr3", mime: "image/x-canon-cr3" }; + default: + if (brandMajor.startsWith("3g")) { + if (brandMajor.startsWith("3g2")) { + return { ext: "3g2", mime: "video/3gpp2" }; + } + return { ext: "3gp", mime: "video/3gpp" }; + } + return { ext: "mp4", mime: "video/mp4" }; + } + } + if (this.checkString("REGEDIT4\r\n")) { + return { + ext: "reg", + mime: "application/x-ms-regedit" + }; + } + if (this.check([82, 73, 70, 70])) { + if (this.checkString("WEBP", { offset: 8 })) { + return { + ext: "webp", + mime: "image/webp" + }; + } + if (this.check([65, 86, 73], { offset: 8 })) { + return { + ext: "avi", + mime: "video/vnd.avi" + }; + } + if (this.check([87, 65, 86, 69], { offset: 8 })) { + return { + ext: "wav", + mime: "audio/wav" + }; + } + if (this.check([81, 76, 67, 77], { offset: 8 })) { + return { + ext: "qcp", + mime: "audio/qcelp" + }; + } + } + if (this.check([73, 73, 85, 0, 24, 0, 0, 0, 136, 231, 116, 216])) { + return { + ext: "rw2", + mime: "image/x-panasonic-rw2" + }; + } + if (this.check([48, 38, 178, 117, 142, 102, 207, 17, 166, 217])) { + async function readHeader() { + const guid5 = new Uint8Array(16); + await tokenizer.readBuffer(guid5); + return { + id: guid5, + size: Number(await tokenizer.readToken(UINT64_LE)) + }; + } + await tokenizer.ignore(30); + while (tokenizer.position + 24 < tokenizer.fileInfo.size) { + const header = await readHeader(); + let payload = header.size - 24; + if (_check2(header.id, [145, 7, 220, 183, 183, 169, 207, 17, 142, 230, 0, 192, 12, 32, 83, 101])) { + const typeId = new Uint8Array(16); + payload -= await tokenizer.readBuffer(typeId); + if (_check2(typeId, [64, 158, 105, 248, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) { + return { + ext: "asf", + mime: "audio/x-ms-asf" + }; + } + if (_check2(typeId, [192, 239, 25, 188, 77, 91, 207, 17, 168, 253, 0, 128, 95, 92, 68, 43])) { + return { + ext: "asf", + mime: "video/x-ms-asf" + }; + } + break; + } + await tokenizer.ignore(payload); + } + return { + ext: "asf", + mime: "application/vnd.ms-asf" + }; + } + if (this.check([171, 75, 84, 88, 32, 49, 49, 187, 13, 10, 26, 10])) { + return { + ext: "ktx", + mime: "image/ktx" + }; + } + if ((this.check([126, 16, 4]) || this.check([126, 24, 4])) && this.check([48, 77, 73, 69], { offset: 4 })) { + return { + ext: "mie", + mime: "application/x-mie" + }; + } + if (this.check([39, 10, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0], { offset: 2 })) { + return { + ext: "shp", + mime: "application/x-esri-shape" + }; + } + if (this.check([255, 79, 255, 81])) { + return { + ext: "j2c", + mime: "image/j2c" + }; + } + if (this.check([0, 0, 0, 12, 106, 80, 32, 32, 13, 10, 135, 10])) { + await tokenizer.ignore(20); + const type2 = await tokenizer.readToken(new StringType(4, "ascii")); + switch (type2) { + case "jp2 ": + return { + ext: "jp2", + mime: "image/jp2" + }; + case "jpx ": + return { + ext: "jpx", + mime: "image/jpx" + }; + case "jpm ": + return { + ext: "jpm", + mime: "image/jpm" + }; + case "mjp2": + return { + ext: "mj2", + mime: "image/mj2" + }; + default: + return; + } + } + if (this.check([255, 10]) || this.check([0, 0, 0, 12, 74, 88, 76, 32, 13, 10, 135, 10])) { + return { + ext: "jxl", + mime: "image/jxl" + }; + } + if (this.check([254, 255])) { + if (this.checkString("= 16) { + const jsonSize = new DataView(this.buffer.buffer).getUint32(12, true); + if (jsonSize > 12 && this.buffer.length >= jsonSize + 16) { + try { + const header = new TextDecoder().decode(this.buffer.subarray(16, jsonSize + 16)); + const json4 = JSON.parse(header); + if (json4.files) { + return { + ext: "asar", + mime: "application/x-asar" + }; + } + } catch { + } + } + } + if (this.check([6, 14, 43, 52, 2, 5, 1, 1, 13, 1, 2, 1, 1, 2])) { + return { + ext: "mxf", + mime: "application/mxf" + }; + } + if (this.checkString("SCRM", { offset: 44 })) { + return { + ext: "s3m", + mime: "audio/x-s3m" + }; + } + if (this.check([71]) && this.check([71], { offset: 188 })) { + return { + ext: "mts", + mime: "video/mp2t" + }; + } + if (this.check([71], { offset: 4 }) && this.check([71], { offset: 196 })) { + return { + ext: "mts", + mime: "video/mp2t" + }; + } + if (this.check([66, 79, 79, 75, 77, 79, 66, 73], { offset: 60 })) { + return { + ext: "mobi", + mime: "application/x-mobipocket-ebook" + }; + } + if (this.check([68, 73, 67, 77], { offset: 128 })) { + return { + ext: "dcm", + mime: "application/dicom" + }; + } + if (this.check([76, 0, 0, 0, 1, 20, 2, 0, 0, 0, 0, 0, 192, 0, 0, 0, 0, 0, 0, 70])) { + return { + ext: "lnk", + mime: "application/x.ms.shortcut" + // Invented by us + }; + } + if (this.check([98, 111, 111, 107, 0, 0, 0, 0, 109, 97, 114, 107, 0, 0, 0, 0])) { + return { + ext: "alias", + mime: "application/x.apple.alias" + // Invented by us + }; + } + if (this.checkString("Kaydara FBX Binary \0")) { + return { + ext: "fbx", + mime: "application/x.autodesk.fbx" + // Invented by us + }; + } + if (this.check([76, 80], { offset: 34 }) && (this.check([0, 0, 1], { offset: 8 }) || this.check([1, 0, 2], { offset: 8 }) || this.check([2, 0, 2], { offset: 8 }))) { + return { + ext: "eot", + mime: "application/vnd.ms-fontobject" + }; + } + if (this.check([6, 6, 237, 245, 216, 29, 70, 229, 189, 49, 239, 231, 254, 116, 183, 29])) { + return { + ext: "indd", + mime: "application/x-indesign" + }; + } + if (this.check([255, 255, 0, 0, 7, 0, 0, 0, 4, 0, 0, 0, 1, 0, 1, 0]) || this.check([0, 0, 255, 255, 0, 0, 0, 7, 0, 0, 0, 4, 0, 1, 0, 1])) { + return { + ext: "jmp", + mime: "application/x-jmp-data" + }; + } + await tokenizer.peekBuffer(this.buffer, { length: Math.min(512, tokenizer.fileInfo.size), mayBeLess: true }); + if (this.checkString("ustar", { offset: 257 }) && (this.checkString("\0", { offset: 262 }) || this.checkString(" ", { offset: 262 })) || this.check([0, 0, 0, 0, 0, 0], { offset: 257 }) && tarHeaderChecksumMatches(this.buffer)) { + return { + ext: "tar", + mime: "application/x-tar" + }; + } + if (this.check([255, 254])) { + const encoding = "utf-16le"; + if (this.checkString(" { + this.buffer = new Uint8Array(reasonableDetectionSizeInBytes); + await tokenizer.peekBuffer(this.buffer, { length: Math.min(8, tokenizer.fileInfo.size), mayBeLess: true }); + if (this.check([0, 0, 1, 186]) || this.check([0, 0, 1, 179])) { + return { + ext: "mpg", + mime: "video/mpeg" + }; + } + if (this.check([0, 1, 0, 0, 0])) { + return { + ext: "ttf", + mime: "font/ttf" + }; + } + if (this.check([0, 0, 1, 0])) { + return { + ext: "ico", + mime: "image/x-icon" + }; + } + if (this.check([0, 0, 2, 0])) { + return { + ext: "cur", + mime: "image/x-icon" + }; + } + await tokenizer.peekBuffer(this.buffer, { length: Math.min(2 + this.options.mpegOffsetTolerance, tokenizer.fileInfo.size), mayBeLess: true }); + if (this.buffer.length >= 2 + this.options.mpegOffsetTolerance) { + for (let depth = 0; depth <= this.options.mpegOffsetTolerance; ++depth) { + const type2 = this.scanMpeg(depth); + if (type2) { + return type2; + } + } + } + }; + async readTiffTag(bigEndian) { + const tagId = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE); + this.tokenizer.ignore(10); + switch (tagId) { + case 50341: + return { + ext: "arw", + mime: "image/x-sony-arw" + }; + case 50706: + return { + ext: "dng", + mime: "image/x-adobe-dng" + }; + default: + } + } + async readTiffIFD(bigEndian) { + const numberOfTags = await this.tokenizer.readToken(bigEndian ? UINT16_BE : UINT16_LE); + for (let n = 0; n < numberOfTags; ++n) { + const fileType = await this.readTiffTag(bigEndian); + if (fileType) { + return fileType; + } + } + } + async readTiffHeader(bigEndian) { + const version4 = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 2); + const ifdOffset = (bigEndian ? UINT32_BE : UINT32_LE).get(this.buffer, 4); + if (version4 === 42) { + if (ifdOffset >= 6) { + if (this.checkString("CR", { offset: 8 })) { + return { + ext: "cr2", + mime: "image/x-canon-cr2" + }; + } + if (ifdOffset >= 8) { + const someId1 = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 8); + const someId2 = (bigEndian ? UINT16_BE : UINT16_LE).get(this.buffer, 10); + if (someId1 === 28 && someId2 === 254 || someId1 === 31 && someId2 === 11) { + return { + ext: "nef", + mime: "image/x-nikon-nef" + }; + } + } + } + await this.tokenizer.ignore(ifdOffset); + const fileType = await this.readTiffIFD(bigEndian); + return fileType ?? { + ext: "tif", + mime: "image/tiff" + }; + } + if (version4 === 43) { + return { + ext: "tif", + mime: "image/tiff" + }; + } + } + /** + Scan check MPEG 1 or 2 Layer 3 header, or 'layer 0' for ADTS (MPEG sync-word 0xFFE). + + @param offset - Offset to scan for sync-preamble. + @returns {{ext: string, mime: string}} + */ + scanMpeg(offset) { + if (this.check([255, 224], { offset, mask: [255, 224] })) { + if (this.check([16], { offset: offset + 1, mask: [22] })) { + if (this.check([8], { offset: offset + 1, mask: [8] })) { + return { + ext: "aac", + mime: "audio/aac" + }; + } + return { + ext: "aac", + mime: "audio/aac" + }; + } + if (this.check([2], { offset: offset + 1, mask: [6] })) { + return { + ext: "mp3", + mime: "audio/mpeg" + }; + } + if (this.check([4], { offset: offset + 1, mask: [6] })) { + return { + ext: "mp2", + mime: "audio/mpeg" + }; + } + if (this.check([6], { offset: offset + 1, mask: [6] })) { + return { + ext: "mp1", + mime: "audio/mpeg" + }; + } + } + } + }; + supportedExtensions = new Set(extensions); + supportedMimeTypes = new Set(mimeTypes); + } +}); + +// node_modules/.pnpm/file-type@21.3.0/node_modules/file-type/index.js +var init_file_type = __esm({ + "node_modules/.pnpm/file-type@21.3.0/node_modules/file-type/index.js"() { + init_lib(); + init_core4(); + } +}); + // node_modules/.pnpm/@mixmark-io+domino@2.2.0/node_modules/@mixmark-io/domino/lib/Event.js var require_Event = __commonJS({ "node_modules/.pnpm/@mixmark-io+domino@2.2.0/node_modules/@mixmark-io/domino/lib/Event.js"(exports, module) { @@ -76472,7 +80410,7 @@ var require_select = __commonJS({ ); }); }; - var indexOf = (function() { + var indexOf2 = (function() { if (Array.prototype.indexOf) { return Array.prototype.indexOf; } @@ -77076,7 +81014,7 @@ var require_select = __commonJS({ scope2 = node2.getElementsByTagName(test.qname); i = 0; while (el = scope2[i++]) { - if (test(el) && indexOf.call(results, el) === -1) { + if (test(el) && indexOf2.call(results, el) === -1) { results.push(el); } } @@ -77128,12 +81066,12 @@ var require_ChildNode = __commonJS({ "use strict"; var Node = require_Node(); var LinkedList = require_LinkedList(); - var createDocumentFragmentFromArguments = function(document, args3) { - var docFrag = document.createDocumentFragment(); + var createDocumentFragmentFromArguments = function(document2, args3) { + var docFrag = document2.createDocumentFragment(); for (var i = 0; i < args3.length; i++) { var argItem = args3[i]; var isNode2 = argItem instanceof Node; - docFrag.appendChild(isNode2 ? argItem : document.createTextNode(String(argItem))); + docFrag.appendChild(isNode2 ? argItem : document2.createTextNode(String(argItem))); } return docFrag; }; @@ -77401,7 +81339,7 @@ var require_Element = __commonJS({ return NodeUtils.serializeOne(this, { nodeType: 0 }); }, set: function(v) { - var document = this.ownerDocument; + var document2 = this.ownerDocument; var parent = this.parentNode; if (parent === null) { return; @@ -77412,8 +81350,8 @@ var require_Element = __commonJS({ if (parent.nodeType === Node.DOCUMENT_FRAGMENT_NODE) { parent = parent.ownerDocument.createElement("body"); } - var parser = document.implementation.mozHTMLParser( - document._address, + var parser = document2.implementation.mozHTMLParser( + document2._address, parent ); parser.parse(v === null ? "" : String(v), true); @@ -79402,32 +83340,32 @@ var require_URL = __commonJS({ else return basepath.substring(0, lastslash + 1) + refpath; } - function remove_dot_segments(path3) { - if (!path3) return path3; + function remove_dot_segments(path4) { + if (!path4) return path4; var output = ""; - while (path3.length > 0) { - if (path3 === "." || path3 === "..") { - path3 = ""; + while (path4.length > 0) { + if (path4 === "." || path4 === "..") { + path4 = ""; break; } - var twochars = path3.substring(0, 2); - var threechars = path3.substring(0, 3); - var fourchars = path3.substring(0, 4); + var twochars = path4.substring(0, 2); + var threechars = path4.substring(0, 3); + var fourchars = path4.substring(0, 4); if (threechars === "../") { - path3 = path3.substring(3); + path4 = path4.substring(3); } else if (twochars === "./") { - path3 = path3.substring(2); + path4 = path4.substring(2); } else if (threechars === "/./") { - path3 = "/" + path3.substring(3); - } else if (twochars === "/." && path3.length === 2) { - path3 = "/"; - } else if (fourchars === "/../" || threechars === "/.." && path3.length === 3) { - path3 = "/" + path3.substring(4); + path4 = "/" + path4.substring(3); + } else if (twochars === "/." && path4.length === 2) { + path4 = "/"; + } else if (fourchars === "/../" || threechars === "/.." && path4.length === 3) { + path4 = "/" + path4.substring(4); output = output.replace(/\/?[^\/]*$/, ""); } else { - var segment = path3.match(/(\/?([^\/]*))/)[0]; + var segment = path4.match(/(\/?([^\/]*))/)[0]; output += segment; - path3 = path3.substring(segment.length); + path4 = path4.substring(segment.length); } } return output; @@ -79998,9 +83936,9 @@ var require_defineElement = __commonJS({ }); return c; }; - function EventHandlerBuilder(body, document, form, element) { + function EventHandlerBuilder(body, document2, form, element) { this.body = body; - this.document = document; + this.document = document2; this.form = form; this.element = element; } @@ -90875,8 +94813,8 @@ var require_Window = __commonJS({ var Location = require_Location(); var utils = require_utils8(); module.exports = Window; - function Window(document) { - this.document = document || new DOMImplementation(null).createHTMLDocument(""); + function Window(document2) { + this.document = document2 || new DOMImplementation(null).createHTMLDocument(""); this.document._scripting_enabled = true; this.document.defaultView = this; this.location = new Location(this, this.document._address || "about:blank"); @@ -91007,11 +94945,11 @@ var require_lib3 = __commonJS({ }; }; exports.createWindow = function(html, address) { - var document = exports.createDocument(html); + var document2 = exports.createDocument(html); if (address !== void 0) { - document._address = address; + document2._address = address; } - return new impl.Window(document); + return new impl.Window(document2); }; exports.impl = impl; } @@ -91778,9 +95716,9 @@ var require_constants11 = __commonJS({ var require_debug = __commonJS({ "node_modules/.pnpm/semver@7.7.3/node_modules/semver/internal/debug.js"(exports, module) { "use strict"; - var debug = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args3) => console.error("SEMVER", ...args3) : () => { + var debug2 = typeof process === "object" && process.env && process.env.NODE_DEBUG && /\bsemver\b/i.test(process.env.NODE_DEBUG) ? (...args3) => console.error("SEMVER", ...args3) : () => { }; - module.exports = debug; + module.exports = debug2; } }); @@ -91793,7 +95731,7 @@ var require_re = __commonJS({ MAX_SAFE_BUILD_LENGTH, MAX_LENGTH } = require_constants11(); - var debug = require_debug(); + var debug2 = require_debug(); exports = module.exports = {}; var re = exports.re = []; var safeRe = exports.safeRe = []; @@ -91816,7 +95754,7 @@ var require_re = __commonJS({ var createToken = (name, value2, isGlobal) => { const safe = makeSafeRegex(value2); const index = R++; - debug(name, index, value2); + debug2(name, index, value2); t[name] = index; src[index] = value2; safeSrc[index] = safe; @@ -91920,7 +95858,7 @@ var require_identifiers = __commonJS({ var require_semver = __commonJS({ "node_modules/.pnpm/semver@7.7.3/node_modules/semver/classes/semver.js"(exports, module) { "use strict"; - var debug = require_debug(); + var debug2 = require_debug(); var { MAX_LENGTH, MAX_SAFE_INTEGER } = require_constants11(); var { safeRe: re, t } = require_re(); var parseOptions = require_parse_options(); @@ -91942,7 +95880,7 @@ var require_semver = __commonJS({ `version is longer than ${MAX_LENGTH} characters` ); } - debug("SemVer", version4, options); + debug2("SemVer", version4, options); this.options = options; this.loose = !!options.loose; this.includePrerelease = !!options.includePrerelease; @@ -91990,7 +95928,7 @@ var require_semver = __commonJS({ return this.version; } compare(other) { - debug("SemVer.compare", this.version, this.options, other); + debug2("SemVer.compare", this.version, this.options, other); if (!(other instanceof _SemVer)) { if (typeof other === "string" && other === this.version) { return 0; @@ -92041,7 +95979,7 @@ var require_semver = __commonJS({ do { const a = this.prerelease[i]; const b = other.prerelease[i]; - debug("prerelease compare", i, a, b); + debug2("prerelease compare", i, a, b); if (a === void 0 && b === void 0) { return 0; } else if (b === void 0) { @@ -92063,7 +96001,7 @@ var require_semver = __commonJS({ do { const a = this.build[i]; const b = other.build[i]; - debug("build compare", i, a, b); + debug2("build compare", i, a, b); if (a === void 0 && b === void 0) { return 0; } else if (b === void 0) { @@ -92691,21 +96629,21 @@ var require_range = __commonJS({ const loose = this.options.loose; const hr = loose ? re[t.HYPHENRANGELOOSE] : re[t.HYPHENRANGE]; range2 = range2.replace(hr, hyphenReplace(this.options.includePrerelease)); - debug("hyphen replace", range2); + debug2("hyphen replace", range2); range2 = range2.replace(re[t.COMPARATORTRIM], comparatorTrimReplace); - debug("comparator trim", range2); + debug2("comparator trim", range2); range2 = range2.replace(re[t.TILDETRIM], tildeTrimReplace); - debug("tilde trim", range2); + debug2("tilde trim", range2); range2 = range2.replace(re[t.CARETTRIM], caretTrimReplace); - debug("caret trim", range2); + debug2("caret trim", range2); let rangeList = range2.split(" ").map((comp) => parseComparator(comp, this.options)).join(" ").split(/\s+/).map((comp) => replaceGTE0(comp, this.options)); if (loose) { rangeList = rangeList.filter((comp) => { - debug("loose invalid filter", comp, this.options); + debug2("loose invalid filter", comp, this.options); return !!comp.match(re[t.COMPARATORLOOSE]); }); } - debug("range list", rangeList); + debug2("range list", rangeList); const rangeMap = /* @__PURE__ */ new Map(); const comparators = rangeList.map((comp) => new Comparator(comp, this.options)); for (const comp of comparators) { @@ -92760,7 +96698,7 @@ var require_range = __commonJS({ var cache = new LRU(); var parseOptions = require_parse_options(); var Comparator = require_comparator(); - var debug = require_debug(); + var debug2 = require_debug(); var SemVer = require_semver(); var { safeRe: re, @@ -92786,15 +96724,15 @@ var require_range = __commonJS({ }; var parseComparator = (comp, options) => { comp = comp.replace(re[t.BUILD], ""); - debug("comp", comp, options); + debug2("comp", comp, options); comp = replaceCarets(comp, options); - debug("caret", comp); + debug2("caret", comp); comp = replaceTildes(comp, options); - debug("tildes", comp); + debug2("tildes", comp); comp = replaceXRanges(comp, options); - debug("xrange", comp); + debug2("xrange", comp); comp = replaceStars(comp, options); - debug("stars", comp); + debug2("stars", comp); return comp; }; var isX = (id) => !id || id.toLowerCase() === "x" || id === "*"; @@ -92804,7 +96742,7 @@ var require_range = __commonJS({ var replaceTilde = (comp, options) => { const r = options.loose ? re[t.TILDELOOSE] : re[t.TILDE]; return comp.replace(r, (_, M, m, p, pr) => { - debug("tilde", comp, _, M, m, p, pr); + debug2("tilde", comp, _, M, m, p, pr); let ret; if (isX(M)) { ret = ""; @@ -92813,12 +96751,12 @@ var require_range = __commonJS({ } else if (isX(p)) { ret = `>=${M}.${m}.0 <${M}.${+m + 1}.0-0`; } else if (pr) { - debug("replaceTilde pr", pr); + debug2("replaceTilde pr", pr); ret = `>=${M}.${m}.${p}-${pr} <${M}.${+m + 1}.0-0`; } else { ret = `>=${M}.${m}.${p} <${M}.${+m + 1}.0-0`; } - debug("tilde return", ret); + debug2("tilde return", ret); return ret; }); }; @@ -92826,11 +96764,11 @@ var require_range = __commonJS({ return comp.trim().split(/\s+/).map((c) => replaceCaret(c, options)).join(" "); }; var replaceCaret = (comp, options) => { - debug("caret", comp, options); + debug2("caret", comp, options); const r = options.loose ? re[t.CARETLOOSE] : re[t.CARET]; const z2 = options.includePrerelease ? "-0" : ""; return comp.replace(r, (_, M, m, p, pr) => { - debug("caret", comp, _, M, m, p, pr); + debug2("caret", comp, _, M, m, p, pr); let ret; if (isX(M)) { ret = ""; @@ -92843,7 +96781,7 @@ var require_range = __commonJS({ ret = `>=${M}.${m}.0${z2} <${+M + 1}.0.0-0`; } } else if (pr) { - debug("replaceCaret pr", pr); + debug2("replaceCaret pr", pr); if (M === "0") { if (m === "0") { ret = `>=${M}.${m}.${p}-${pr} <${M}.${m}.${+p + 1}-0`; @@ -92854,7 +96792,7 @@ var require_range = __commonJS({ ret = `>=${M}.${m}.${p}-${pr} <${+M + 1}.0.0-0`; } } else { - debug("no pr"); + debug2("no pr"); if (M === "0") { if (m === "0") { ret = `>=${M}.${m}.${p}${z2} <${M}.${m}.${+p + 1}-0`; @@ -92865,19 +96803,19 @@ var require_range = __commonJS({ ret = `>=${M}.${m}.${p} <${+M + 1}.0.0-0`; } } - debug("caret return", ret); + debug2("caret return", ret); return ret; }); }; var replaceXRanges = (comp, options) => { - debug("replaceXRanges", comp, options); + debug2("replaceXRanges", comp, options); return comp.split(/\s+/).map((c) => replaceXRange(c, options)).join(" "); }; var replaceXRange = (comp, options) => { comp = comp.trim(); const r = options.loose ? re[t.XRANGELOOSE] : re[t.XRANGE]; return comp.replace(r, (ret, gtlt, M, m, p, pr) => { - debug("xRange", comp, ret, gtlt, M, m, p, pr); + debug2("xRange", comp, ret, gtlt, M, m, p, pr); const xM = isX(M); const xm = xM || isX(m); const xp = xm || isX(p); @@ -92924,16 +96862,16 @@ var require_range = __commonJS({ } else if (xp) { ret = `>=${M}.${m}.0${pr} <${M}.${+m + 1}.0-0`; } - debug("xRange return", ret); + debug2("xRange return", ret); return ret; }); }; var replaceStars = (comp, options) => { - debug("replaceStars", comp, options); + debug2("replaceStars", comp, options); return comp.trim().replace(re[t.STAR], ""); }; var replaceGTE0 = (comp, options) => { - debug("replaceGTE0", comp, options); + debug2("replaceGTE0", comp, options); return comp.trim().replace(re[options.includePrerelease ? t.GTE0PRE : t.GTE0], ""); }; var hyphenReplace = (incPr) => ($0, from, fM, fm, fp, fpr, fb, to, tM, tm, tp, tpr) => { @@ -92971,7 +96909,7 @@ var require_range = __commonJS({ } if (version4.prerelease.length && !options.includePrerelease) { for (let i = 0; i < set2.length; i++) { - debug(set2[i].semver); + debug2(set2[i].semver); if (set2[i].semver === Comparator.ANY) { continue; } @@ -93008,7 +96946,7 @@ var require_comparator = __commonJS({ } } comp = comp.trim().split(/\s+/).join(" "); - debug("comparator", comp, options); + debug2("comparator", comp, options); this.options = options; this.loose = !!options.loose; this.parse(comp); @@ -93017,7 +96955,7 @@ var require_comparator = __commonJS({ } else { this.value = this.operator + this.semver.version; } - debug("comp", this); + debug2("comp", this); } parse(comp) { const r = this.options.loose ? re[t.COMPARATORLOOSE] : re[t.COMPARATOR]; @@ -93039,7 +96977,7 @@ var require_comparator = __commonJS({ return this.value; } test(version4) { - debug("Comparator.test", version4, this.options.loose); + debug2("Comparator.test", version4, this.options.loose); if (this.semver === ANY || version4 === ANY) { return true; } @@ -93096,7 +97034,7 @@ var require_comparator = __commonJS({ var parseOptions = require_parse_options(); var { safeRe: re, t } = require_re(); var cmp = require_cmp(); - var debug = require_debug(); + var debug2 = require_debug(); var SemVer = require_semver(); var Range = require_range(); } @@ -94300,29 +98238,29 @@ var timeWithUnnecessarySeconds = /:\d\d:00$/; var pad = (value2, length) => String(value2).padStart(length, "0"); // node_modules/.pnpm/@ark+util@0.56.0/node_modules/@ark/util/out/path.js -var appendStringifiedKey = (path3, prop, ...[opts]) => { +var appendStringifiedKey = (path4, prop, ...[opts]) => { const stringifySymbol = opts?.stringifySymbol ?? printable; - let propAccessChain = path3; + let propAccessChain = path4; switch (typeof prop) { case "string": - propAccessChain = isDotAccessible(prop) ? path3 === "" ? prop : `${path3}.${prop}` : `${path3}[${JSON.stringify(prop)}]`; + propAccessChain = isDotAccessible(prop) ? path4 === "" ? prop : `${path4}.${prop}` : `${path4}[${JSON.stringify(prop)}]`; break; case "number": - propAccessChain = `${path3}[${prop}]`; + propAccessChain = `${path4}[${prop}]`; break; case "symbol": - propAccessChain = `${path3}[${stringifySymbol(prop)}]`; + propAccessChain = `${path4}[${stringifySymbol(prop)}]`; break; default: if (opts?.stringifyNonKey) - propAccessChain = `${path3}[${opts.stringifyNonKey(prop)}]`; + propAccessChain = `${path4}[${opts.stringifyNonKey(prop)}]`; else { throwParseError(`${printable(prop)} must be a PropertyKey or stringifyNonKey must be passed to options`); } } return propAccessChain; }; -var stringifyPath = (path3, ...opts) => path3.reduce((s, k) => appendStringifiedKey(s, k, ...opts), ""); +var stringifyPath = (path4, ...opts) => path4.reduce((s, k) => appendStringifiedKey(s, k, ...opts), ""); var ReadonlyPath = class extends ReadonlyArray { // alternate strategy for caching since the base object is frozen cache = {}; @@ -94349,8 +98287,8 @@ var ReadonlyPath = class extends ReadonlyArray { return this.cache.stringifyAncestors; let propString = ""; const result = [propString]; - for (const path3 of this) { - propString = appendStringifiedKey(propString, path3); + for (const path4 of this) { + propString = appendStringifiedKey(propString, path4); result.push(propString); } return this.cache.stringifyAncestors = result; @@ -96674,13 +100612,13 @@ function resolveRef(ref, ctx) { if (!ref.startsWith("#")) { throw new Error("External $ref is not supported, only local refs (#/...) are allowed"); } - const path3 = ref.slice(1).split("/").filter(Boolean); - if (path3.length === 0) { + const path4 = ref.slice(1).split("/").filter(Boolean); + if (path4.length === 0) { return ctx.rootSchema; } const defsKey = ctx.version === "draft-2020-12" ? "$defs" : "definitions"; - if (path3[0] === defsKey) { - const key = path3[1]; + if (path4[0] === defsKey) { + const key = path4[1]; if (!key || !ctx.defs[key]) { throw new Error(`Reference not found: ${ref}`); } @@ -100276,14 +104214,14 @@ var KeyStore = class { } }; function createKey(key) { - let path3 = null; + let path4 = null; let id = null; let src = null; let weight = 1; let getFn = null; if (isString(key) || isArray2(key)) { src = key; - path3 = createKeyPath(key); + path4 = createKeyPath(key); id = createKeyId(key); } else { if (!hasOwn.call(key, "name")) { @@ -100297,11 +104235,11 @@ function createKey(key) { throw new Error(INVALID_KEY_WEIGHT_VALUE(name)); } } - path3 = createKeyPath(name); + path4 = createKeyPath(name); id = createKeyId(name); getFn = key.getFn; } - return { path: path3, id, weight, src, getFn }; + return { path: path4, id, weight, src, getFn }; } function createKeyPath(key) { return isArray2(key) ? key : key.split("."); @@ -100309,34 +104247,34 @@ function createKeyPath(key) { function createKeyId(key) { return isArray2(key) ? key.join(".") : key; } -function get(obj, path3) { +function get(obj, path4) { let list = []; let arr = false; - const deepGet = (obj2, path4, index) => { + const deepGet = (obj2, path5, index) => { if (!isDefined(obj2)) { return; } - if (!path4[index]) { + if (!path5[index]) { list.push(obj2); } else { - let key = path4[index]; + let key = path5[index]; const value2 = obj2[key]; if (!isDefined(value2)) { return; } - if (index === path4.length - 1 && (isString(value2) || isNumber(value2) || isBoolean(value2))) { + if (index === path5.length - 1 && (isString(value2) || isNumber(value2) || isBoolean(value2))) { list.push(toString(value2)); } else if (isArray2(value2)) { arr = true; for (let i = 0, len = value2.length; i < len; i += 1) { - deepGet(value2[i], path4, index + 1); + deepGet(value2[i], path5, index + 1); } - } else if (path4.length) { - deepGet(value2, path4, index + 1); + } else if (path5.length) { + deepGet(value2, path5, index + 1); } } }; - deepGet(obj, isString(path3) ? path3.split(".") : path3, 0); + deepGet(obj, isString(path4) ? path4.split(".") : path4, 0); return arr ? list : list[0]; } var MatchOptions = { @@ -101954,11 +105892,11 @@ function aborted2(x, startIndex = 0) { for (let i$3 = startIndex; i$3 < x.issues.length; i$3++) if (x.issues[i$3]?.continue !== true) return true; return false; } -function prefixIssues2(path3, issues) { +function prefixIssues2(path4, issues) { return issues.map((iss) => { var _a2; (_a2 = iss).path ?? (_a2.path = []); - iss.path.unshift(path3); + iss.path.unshift(path4); return iss; }); } @@ -118890,8 +122828,8 @@ var require_utils4 = /* @__PURE__ */ __commonJSMin(((exports, module) => { for (let i$3 = 0; i$3 < str$1.length; i$3++) if (str$1[i$3] === token) ind++; return ind; } - function removeDotSegments$1(path3) { - let input = path3; + function removeDotSegments$1(path4) { + let input = path4; const output = []; let nextSlash = -1; let len = 0; @@ -119044,8 +122982,8 @@ var require_schemes2 = /* @__PURE__ */ __commonJSMin(((exports, module) => { wsComponent.secure = void 0; } if (wsComponent.resourceName) { - const [path3, query2] = wsComponent.resourceName.split("?"); - wsComponent.path = path3 && path3 !== "/" ? path3 : void 0; + const [path4, query2] = wsComponent.resourceName.split("?"); + wsComponent.path = path4 && path4 !== "/" ? path4 : void 0; wsComponent.query = query2; wsComponent.resourceName = void 0; } @@ -121918,11 +125856,11 @@ var require_dist2 = /* @__PURE__ */ __commonJSMin(((exports, module) => { if (!f) throw new Error(`Unknown format "${name}"`); return f; }; - function addFormats(ajv, list, fs4, exportName) { + function addFormats(ajv, list, fs5, exportName) { var _a2; var _b; (_a2 = (_b = ajv.opts.code).formats) !== null && _a2 !== void 0 || (_b.formats = (0, codegen_1._)`require("ajv-formats/dist/formats").${exportName}`); - for (const f of list) ajv.addFormat(f, fs4[f]); + for (const f of list) ajv.addFormat(f, fs5[f]); } module.exports = exports = formatsPlugin; Object.defineProperty(exports, "__esModule", { value: true }); @@ -123338,8 +127276,8 @@ ${error50 instanceof Error ? error50.stack : JSON.stringify(error50)}` ); if (parsed2.issues) { const friendlyErrors = this.#utils?.formatInvalidParamsErrorMessage ? this.#utils.formatInvalidParamsErrorMessage(parsed2.issues) : parsed2.issues.map((issue4) => { - const path3 = issue4.path?.join(".") || "root"; - return `${path3}: ${issue4.message}`; + const path4 = issue4.path?.join(".") || "root"; + return `${path4}: ${issue4.message}`; }).join(", "); throw new McpError( ErrorCode.InvalidParams, @@ -123977,10 +127915,10 @@ var FastMCP = class extends FastMCPEventEmitter { const healthConfig = this.#options.health ?? {}; const enabled = healthConfig.enabled === void 0 ? true : healthConfig.enabled; if (enabled) { - const path3 = healthConfig.path ?? "/health"; + const path4 = healthConfig.path ?? "/health"; const url4 = new URL(req.url || "", `http://${host}`); try { - if (req.method === "GET" && url4.pathname === path3) { + if (req.method === "GET" && url4.pathname === path4) { res.writeHead(healthConfig.status ?? 200, { "Content-Type": "text/plain" }).end(healthConfig.message ?? "\u2713 Ok"); @@ -124471,15 +128409,15 @@ var ArkErrors = class _ArkErrors extends ReadonlyArray { /** * @internal */ - affectsPath(path3) { + affectsPath(path4) { if (this.length === 0) return false; return ( // this would occur if there is an existing error at a prefix of path // e.g. the path is ["foo", "bar"] and there is an error at ["foo"] - path3.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path + path4.stringifyAncestors().some((s) => s in this.byPath) || // this would occur if there is an existing error at a suffix of path // e.g. the path is ["foo"] and there is an error at ["foo", "bar"] - path3.stringify() in this.byAncestorPath + path4.stringify() in this.byAncestorPath ); } /** @@ -124666,23 +128604,23 @@ var Traversal = class { while (this.queuedMorphs.length) { const queuedMorphs = this.queuedMorphs; this.queuedMorphs = []; - for (const { path: path3, morphs } of queuedMorphs) { - if (this.errors.affectsPath(path3)) + for (const { path: path4, morphs } of queuedMorphs) { + if (this.errors.affectsPath(path4)) continue; - this.applyMorphsAtPath(path3, morphs); + this.applyMorphsAtPath(path4, morphs); } } } - applyMorphsAtPath(path3, morphs) { - const key = path3[path3.length - 1]; + applyMorphsAtPath(path4, morphs) { + const key = path4[path4.length - 1]; let parent; if (key !== void 0) { parent = this.root; - for (let pathIndex = 0; pathIndex < path3.length - 1; pathIndex++) - parent = parent[path3[pathIndex]]; + for (let pathIndex = 0; pathIndex < path4.length - 1; pathIndex++) + parent = parent[path4[pathIndex]]; } for (const morph of morphs) { - this.path = [...path3]; + this.path = [...path4]; const morphIsNode = isNode(morph); const result = morph(parent === void 0 ? this.root : parent[key], this); if (result instanceof ArkError) { @@ -125058,15 +128996,15 @@ var NodeSelector = { normalize: (selector) => typeof selector === "function" ? { boundary: "references", method: "filter", where: selector } : typeof selector === "string" ? isKeyOf(selector, NodeSelector.applyBoundary) ? { method: "filter", boundary: selector } : { boundary: "references", method: "filter", kind: selector } : { boundary: "references", method: "filter", ...selector } }; var writeSelectAssertionMessage = (from, selector) => `${from} had no references matching ${printable(selector)}.`; -var typePathToPropString = (path3) => stringifyPath(path3, { +var typePathToPropString = (path4) => stringifyPath(path4, { stringifyNonKey: (node2) => node2.expression }); var referenceMatcher = /"(\$ark\.[^"]+)"/g; var compileMeta = (metaJson) => JSON.stringify(metaJson).replace(referenceMatcher, "$1"); -var flatRef = (path3, node2) => ({ - path: path3, +var flatRef = (path4, node2) => ({ + path: path4, node: node2, - propString: typePathToPropString(path3) + propString: typePathToPropString(path4) }); var flatRefsAreEqual = (l, r) => l.propString === r.propString && l.node.equals(r.node); var appendUniqueFlatRefs = (existing, refs) => appendUnique(existing, refs, { @@ -125102,12 +129040,12 @@ var Disjoint = class _Disjoint extends Array { } describeReasons() { if (this.length === 1) { - const { path: path3, l, r } = this[0]; - const pathString = stringifyPath(path3); + const { path: path4, l, r } = this[0]; + const pathString = stringifyPath(path4); return writeUnsatisfiableExpressionError(`Intersection${pathString && ` at ${pathString}`} of ${describeReasons(l, r)}`); } return `The following intersections result in unsatisfiable types: -\u2022 ${this.map(({ path: path3, l, r }) => `${path3}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`; +\u2022 ${this.map(({ path: path4, l, r }) => `${path4}: ${describeReasons(l, r)}`).join("\n\u2022 ")}`; } throw() { return throwParseError(this.describeReasons()); @@ -126504,10 +130442,10 @@ var BaseRoot = class extends BaseNode { }); }); } - get(...path3) { - if (path3[0] === void 0) + get(...path4) { + if (path4[0] === void 0) return this; - return this.$.schema(this.applyStructuralOperation("get", path3)); + return this.$.schema(this.applyStructuralOperation("get", path4)); } extract(r) { const rNode = this.$.parseDefinition(r); @@ -127449,13 +131387,13 @@ var implementation17 = implementNode({ description: (node2) => node2.distribute((branch) => branch.description, describeBranches), expected: (ctx) => { const byPath = groupBy(ctx.errors, "propString"); - const pathDescriptions = Object.entries(byPath).map(([path3, errors]) => { + const pathDescriptions = Object.entries(byPath).map(([path4, errors]) => { const branchesAtPath = []; for (const errorAtPath of errors) appendUnique(branchesAtPath, errorAtPath.expected); const expected = describeBranches(branchesAtPath); const actual = errors.every((e) => e.actual === errors[0].actual) ? errors[0].actual : printable(errors[0].data); - return `${path3 && `${path3} `}must be ${expected}${actual && ` (was ${actual})`}`; + return `${path4 && `${path4} `}must be ${expected}${actual && ` (was ${actual})`}`; }); return describeBranches(pathDescriptions); }, @@ -127837,10 +131775,10 @@ var viableOrderedCandidates = (candidates, originalBranches) => { }); return viableCandidates; }; -var discriminantCaseToNode = (caseDiscriminant, path3, $2) => { +var discriminantCaseToNode = (caseDiscriminant, path4, $2) => { let node2 = caseDiscriminant === "undefined" ? $2.node("unit", { unit: void 0 }) : caseDiscriminant === "null" ? $2.node("unit", { unit: null }) : caseDiscriminant === "boolean" ? $2.units([true, false]) : caseDiscriminant; - for (let i = path3.length - 1; i >= 0; i--) { - const key = path3[i]; + for (let i = path4.length - 1; i >= 0; i--) { + const key = path4[i]; node2 = $2.node("intersection", typeof key === "number" ? { proto: "Array", // create unknown for preceding elements (could be optimized with safe imports) @@ -127852,7 +131790,7 @@ var discriminantCaseToNode = (caseDiscriminant, path3, $2) => { } return node2; }; -var optionallyChainPropString = (path3) => path3.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data"); +var optionallyChainPropString = (path4) => path4.reduce((acc, k) => acc + compileLiteralPropAccess(k, true), "data"); var serializedTypeOfDescriptions = registeredReference(jsTypeOfDescriptions); var serializedPrintable = registeredReference(printable); var Union = { @@ -128838,7 +132776,7 @@ var StructureNode = class extends BaseConstraint { return throwParseError(writeInvalidKeysMessage(this.expression, invalidKeys)); } } - get(indexer, ...path3) { + get(indexer, ...path4) { let value2; let required4 = false; const key = indexerToKey(indexer); @@ -128874,7 +132812,7 @@ var StructureNode = class extends BaseConstraint { } return throwParseError(writeInvalidKeysMessage(this.expression, [key])); } - const result = value2.get(...path3); + const result = value2.get(...path4); return required4 ? result : result.or($ark.intrinsic.undefined); } pick(...keys) { @@ -130780,12 +134718,12 @@ var parseStandardSchema = (def, ctx) => ctx.$.intrinsic.unknown.pipe((v, ctx2) = const result = def["~standard"].validate(v); if (!result.issues) return result.value; - for (const { message, path: path3 } of result.issues) { - if (path3) { - if (path3.length) { + for (const { message, path: path4 } of result.issues) { + if (path4) { + if (path4.length) { ctx2.error({ problem: uncapitalize(message), - relativePath: path3.map((k) => typeof k === "object" ? k.key : k) + relativePath: path4.map((k) => typeof k === "object" ? k.key : k) }); } else { ctx2.error({ @@ -132998,7 +136936,7 @@ var triggers_notification_paths_default = [ ]; function routeMatcher(paths) { const regexes = paths.map( - (path3) => path3.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/") + (path4) => path4.split("/").map((c) => c.startsWith("{") ? "(?:.+?)" : c).join("/") ); const regex22 = `^(?:${regexes.map((r) => `(?:${r})`).join("|")})[^/]*$`; return new RegExp(regex22, "i"); @@ -134088,17 +138026,17 @@ function requestLog(octokit) { octokit.log.debug("request", options); const start = Date.now(); const requestOptions = octokit.request.endpoint.parse(options); - const path3 = requestOptions.url.replace(options.baseUrl, ""); + const path4 = requestOptions.url.replace(options.baseUrl, ""); return request2(options).then((response) => { const requestId = response.headers["x-github-request-id"]; octokit.log.info( - `${requestOptions.method} ${path3} - ${response.status} with id ${requestId} in ${Date.now() - start}ms` + `${requestOptions.method} ${path4} - ${response.status} with id ${requestId} in ${Date.now() - start}ms` ); return response; }).catch((error50) => { const requestId = error50.response?.headers["x-github-request-id"] || "UNKNOWN"; octokit.log.error( - `${requestOptions.method} ${path3} - ${error50.status} with id ${requestId} in ${Date.now() - start}ms` + `${requestOptions.method} ${path4} - ${error50.status} with id ${requestId} in ${Date.now() - start}ms` ); throw error50; }); @@ -136661,9 +140599,9 @@ var generateJWT = (appId, privateKey) => { const signature = createSign("RSA-SHA256").update(signaturePart).sign(privateKey, "base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=/g, ""); return `${signaturePart}.${signature}`; }; -var githubRequest = async (path3, options = {}) => { +var githubRequest = async (path4, options = {}) => { const { method = "GET", headers = {}, body } = options; - const url4 = `https://api.github.com${path3}`; + const url4 = `https://api.github.com${path4}`; const requestHeaders = { Accept: "application/vnd.github.v3+json", "User-Agent": "Pullfrog-Installation-Token-Generator/1.0", @@ -138131,7 +142069,7 @@ function containsSecrets(content, secrets) { // mcp/git.ts function CreateBranchTool(ctx) { - const defaultBranch = ctx.repo.repo.default_branch || "main"; + const defaultBranch = ctx.repo.data.default_branch || "main"; const CreateBranch = type({ branchName: type.string.describe( "The name of the branch to create (e.g., 'pullfrog/123-fix-bug')" @@ -138143,7 +142081,7 @@ function CreateBranchTool(ctx) { description: "Create a new git branch from the specified base branch. The branch will be created locally and pushed to the remote repository.", parameters: CreateBranch, execute: execute(async ({ branchName, baseBranch }) => { - const resolvedBaseBranch = baseBranch || ctx.repo.repo.default_branch || "main"; + const resolvedBaseBranch = baseBranch || ctx.repo.data.default_branch || "main"; if (containsSecrets(branchName)) { throw new Error( "Branch creation blocked: secrets detected in branch name. Please remove any sensitive information (API keys, tokens, passwords) before creating a branch." @@ -138221,7 +142159,7 @@ var PushBranch = type({ force: type.boolean.describe("Force push (use with caution)").default(false) }); function PushBranchTool(ctx) { - const defaultBranch = ctx.repo.repo.default_branch || "main"; + const defaultBranch = ctx.repo.data.default_branch || "main"; return tool({ name: "push_branch", description: "Push the current branch (or specified branch) to the remote repository. Git automatically determines the correct remote based on branch config (set by checkout_pr for fork PRs). Never force push unless explicitly requested. Pushes to the default branch are blocked.", @@ -139113,6 +143051,59 @@ function SelectModeTool(ctx) { }); } +// mcp/upload.ts +import * as fs2 from "node:fs"; +import * as path2 from "node:path"; +init_file_type(); +var UploadFileParams = type({ + path: type.string.describe("absolute path to file to upload") +}); +function UploadFileTool(ctx) { + return tool({ + name: "upload_file", + description: "upload a file to get a permanent public URL. use for screenshots, artifacts, or any files you want to reference in PRs/comments. max 10MB, images/text/archives allowed.", + parameters: UploadFileParams, + execute: execute(async (params) => { + const buffer = fs2.readFileSync(params.path); + const filename = path2.basename(params.path); + const contentLength = buffer.length; + const fileType = await fileTypeFromBuffer(buffer); + const contentType = fileType?.mime || "application/octet-stream"; + const apiUrl = process.env.API_URL || "https://pullfrog.com"; + const response = await fetch(`${apiUrl}/api/upload/signed-url`, { + method: "POST", + headers: { + Authorization: `Bearer ${ctx.apiToken}`, + "Content-Type": "application/json" + }, + body: JSON.stringify({ + filename, + contentType, + contentLength + }) + }); + if (!response.ok) { + const error50 = await response.text(); + throw new Error(`failed to get upload URL: ${error50}`); + } + const { uploadUrl, publicUrl } = await response.json(); + const uploadResponse = await fetch(uploadUrl, { + method: "PUT", + headers: { + "Content-Type": contentType, + // should be set automatically, but given this header is signed it's better to be explicit + "Content-Length": String(contentLength) + }, + body: buffer + }); + if (!uploadResponse.ok) { + throw new Error(`failed to upload file: ${uploadResponse.statusText}`); + } + return { success: true, publicUrl, filename, contentLength, contentType }; + }) + }); +} + // mcp/server.ts function initToolState(ctx) { const progressCommentIdStr = ctx.runInfo.workflowRunInfo.progressCommentId; @@ -139192,7 +143183,8 @@ async function startMcpHttpServer(ctx) { AddLabelsTool(ctx), CreateBranchTool(ctx), CommitFilesTool(ctx), - PushBranchTool(ctx) + PushBranchTool(ctx), + UploadFileTool(ctx) ]; if (ctx.payload.bash === "restricted") { tools.push(BashTool(ctx)); @@ -139448,7 +143440,7 @@ import { fileURLToPath as fileURLToPath2 } from "url"; import { setMaxListeners } from "events"; import { spawn as spawn3 } from "child_process"; import { createInterface } from "readline"; -import * as fs2 from "fs"; +import * as fs3 from "fs"; import { stat as statPromise, open } from "fs/promises"; import { join as join8 } from "path"; import { homedir } from "os"; @@ -142710,8 +146702,8 @@ var require_schemes3 = __commonJS2((exports, module) => { wsComponents.secure = void 0; } if (wsComponents.resourceName) { - const [path3, query2] = wsComponents.resourceName.split("?"); - wsComponents.path = path3 && path3 !== "/" ? path3 : void 0; + const [path4, query2] = wsComponents.resourceName.split("?"); + wsComponents.path = path4 && path4 !== "/" ? path4 : void 0; wsComponents.query = query2; wsComponents.resourceName = void 0; } @@ -146303,7 +150295,7 @@ function getSessionId() { function createBufferedWriter({ writeFn, flushIntervalMs = 1e3, - maxBufferSize = 100, + maxBufferSize: maxBufferSize2 = 100, immediateMode = false }) { let buffer = []; @@ -146334,7 +150326,7 @@ function createBufferedWriter({ } buffer.push(content); scheduleFlush(); - if (buffer.length >= maxBufferSize) { + if (buffer.length >= maxBufferSize2) { flush(); } }, @@ -146412,11 +150404,11 @@ function getDebugWriter() { if (!debugWriter) { debugWriter = createBufferedWriter({ writeFn: (content) => { - const path3 = getDebugLogPath(); - if (!getFsImplementation().existsSync(dirname(path3))) { - getFsImplementation().mkdirSync(dirname(path3)); + const path4 = getDebugLogPath(); + if (!getFsImplementation().existsSync(dirname(path4))) { + getFsImplementation().mkdirSync(dirname(path4)); } - getFsImplementation().appendFileSync(path3, content); + getFsImplementation().appendFileSync(path4, content); updateLatestDebugLogSymlink(); }, flushIntervalMs: 1e3, @@ -146486,90 +150478,90 @@ var NodeFsOperations = { return process.cwd(); }, existsSync(fsPath) { - return withSlowLogging2(`existsSync(${fsPath})`, () => fs2.existsSync(fsPath)); + return withSlowLogging2(`existsSync(${fsPath})`, () => fs3.existsSync(fsPath)); }, async stat(fsPath) { return statPromise(fsPath); }, statSync(fsPath) { - return withSlowLogging2(`statSync(${fsPath})`, () => fs2.statSync(fsPath)); + return withSlowLogging2(`statSync(${fsPath})`, () => fs3.statSync(fsPath)); }, lstatSync(fsPath) { - return withSlowLogging2(`lstatSync(${fsPath})`, () => fs2.lstatSync(fsPath)); + return withSlowLogging2(`lstatSync(${fsPath})`, () => fs3.lstatSync(fsPath)); }, readFileSync(fsPath, options) { - return withSlowLogging2(`readFileSync(${fsPath})`, () => fs2.readFileSync(fsPath, { encoding: options.encoding })); + return withSlowLogging2(`readFileSync(${fsPath})`, () => fs3.readFileSync(fsPath, { encoding: options.encoding })); }, readFileBytesSync(fsPath) { - return withSlowLogging2(`readFileBytesSync(${fsPath})`, () => fs2.readFileSync(fsPath)); + return withSlowLogging2(`readFileBytesSync(${fsPath})`, () => fs3.readFileSync(fsPath)); }, readSync(fsPath, options) { return withSlowLogging2(`readSync(${fsPath}, ${options.length} bytes)`, () => { let fd = void 0; try { - fd = fs2.openSync(fsPath, "r"); + fd = fs3.openSync(fsPath, "r"); const buffer = Buffer.alloc(options.length); - const bytesRead = fs2.readSync(fd, buffer, 0, options.length, 0); + const bytesRead = fs3.readSync(fd, buffer, 0, options.length, 0); return { buffer, bytesRead }; } finally { if (fd) - fs2.closeSync(fd); + fs3.closeSync(fd); } }); }, - appendFileSync(path3, data, options) { - return withSlowLogging2(`appendFileSync(${path3}, ${data.length} chars)`, () => { - if (!fs2.existsSync(path3) && options?.mode !== void 0) { - const fd = fs2.openSync(path3, "a", options.mode); + appendFileSync(path4, data, options) { + return withSlowLogging2(`appendFileSync(${path4}, ${data.length} chars)`, () => { + if (!fs3.existsSync(path4) && options?.mode !== void 0) { + const fd = fs3.openSync(path4, "a", options.mode); try { - fs2.appendFileSync(fd, data); + fs3.appendFileSync(fd, data); } finally { - fs2.closeSync(fd); + fs3.closeSync(fd); } } else { - fs2.appendFileSync(path3, data); + fs3.appendFileSync(path4, data); } }); }, copyFileSync(src, dest) { - return withSlowLogging2(`copyFileSync(${src} \u2192 ${dest})`, () => fs2.copyFileSync(src, dest)); + return withSlowLogging2(`copyFileSync(${src} \u2192 ${dest})`, () => fs3.copyFileSync(src, dest)); }, - unlinkSync(path3) { - return withSlowLogging2(`unlinkSync(${path3})`, () => fs2.unlinkSync(path3)); + unlinkSync(path4) { + return withSlowLogging2(`unlinkSync(${path4})`, () => fs3.unlinkSync(path4)); }, renameSync(oldPath, newPath) { - return withSlowLogging2(`renameSync(${oldPath} \u2192 ${newPath})`, () => fs2.renameSync(oldPath, newPath)); + return withSlowLogging2(`renameSync(${oldPath} \u2192 ${newPath})`, () => fs3.renameSync(oldPath, newPath)); }, - linkSync(target, path3) { - return withSlowLogging2(`linkSync(${target} \u2192 ${path3})`, () => fs2.linkSync(target, path3)); + linkSync(target, path4) { + return withSlowLogging2(`linkSync(${target} \u2192 ${path4})`, () => fs3.linkSync(target, path4)); }, - symlinkSync(target, path3) { - return withSlowLogging2(`symlinkSync(${target} \u2192 ${path3})`, () => fs2.symlinkSync(target, path3)); + symlinkSync(target, path4) { + return withSlowLogging2(`symlinkSync(${target} \u2192 ${path4})`, () => fs3.symlinkSync(target, path4)); }, - readlinkSync(path3) { - return withSlowLogging2(`readlinkSync(${path3})`, () => fs2.readlinkSync(path3)); + readlinkSync(path4) { + return withSlowLogging2(`readlinkSync(${path4})`, () => fs3.readlinkSync(path4)); }, - realpathSync(path3) { - return withSlowLogging2(`realpathSync(${path3})`, () => fs2.realpathSync(path3)); + realpathSync(path4) { + return withSlowLogging2(`realpathSync(${path4})`, () => fs3.realpathSync(path4)); }, mkdirSync(dirPath, options) { return withSlowLogging2(`mkdirSync(${dirPath})`, () => { - if (!fs2.existsSync(dirPath)) { + if (!fs3.existsSync(dirPath)) { const mkdirOptions = { recursive: true }; if (options?.mode !== void 0) { mkdirOptions.mode = options.mode; } - fs2.mkdirSync(dirPath, mkdirOptions); + fs3.mkdirSync(dirPath, mkdirOptions); } }); }, readdirSync(dirPath) { - return withSlowLogging2(`readdirSync(${dirPath})`, () => fs2.readdirSync(dirPath, { withFileTypes: true })); + return withSlowLogging2(`readdirSync(${dirPath})`, () => fs3.readdirSync(dirPath, { withFileTypes: true })); }, readdirStringSync(dirPath) { - return withSlowLogging2(`readdirStringSync(${dirPath})`, () => fs2.readdirSync(dirPath)); + return withSlowLogging2(`readdirStringSync(${dirPath})`, () => fs3.readdirSync(dirPath)); }, isDirEmptySync(dirPath) { return withSlowLogging2(`isDirEmptySync(${dirPath})`, () => { @@ -146578,20 +150570,20 @@ var NodeFsOperations = { }); }, rmdirSync(dirPath) { - return withSlowLogging2(`rmdirSync(${dirPath})`, () => fs2.rmdirSync(dirPath)); + return withSlowLogging2(`rmdirSync(${dirPath})`, () => fs3.rmdirSync(dirPath)); }, - rmSync(path3, options) { - return withSlowLogging2(`rmSync(${path3})`, () => fs2.rmSync(path3, options)); + rmSync(path4, options) { + return withSlowLogging2(`rmSync(${path4})`, () => fs3.rmSync(path4, options)); }, - createWriteStream(path3) { - return fs2.createWriteStream(path3); + createWriteStream(path4) { + return fs3.createWriteStream(path4); } }; var activeFs = NodeFsOperations; function getFsImplementation() { return activeFs; } -var AbortError = class extends Error { +var AbortError2 = class extends Error { }; function isRunningWithBun() { return process.versions.bun !== void 0; @@ -146616,14 +150608,14 @@ function getOrCreateDebugFile() { return debugFilePath; } function logForSdkDebugging(message) { - const path3 = getOrCreateDebugFile(); - if (!path3) { + const path4 = getOrCreateDebugFile(); + if (!path4) { return; } const timestamp = (/* @__PURE__ */ new Date()).toISOString(); const output = `${timestamp} ${message} `; - appendFileSync2(path3, output); + appendFileSync2(path4, output); } function mergeSandboxIntoExtraArgs(extraArgs, sandbox) { const effectiveExtraArgs = { ...extraArgs }; @@ -146880,7 +150872,7 @@ var ProcessTransport = class { this.process.on("error", (error50) => { this.ready = false; if (this.abortController.signal.aborted) { - this.exitError = new AbortError("Claude Code process aborted by user"); + this.exitError = new AbortError2("Claude Code process aborted by user"); } else { this.exitError = new Error(`Failed to spawn Claude Code process: ${error50.message}`); logForSdkDebugging(this.exitError.message); @@ -146889,7 +150881,7 @@ var ProcessTransport = class { this.process.on("exit", (code, signal) => { this.ready = false; if (this.abortController.signal.aborted) { - this.exitError = new AbortError("Claude Code process aborted by user"); + this.exitError = new AbortError2("Claude Code process aborted by user"); } else { const error50 = this.getProcessExitError(code, signal); if (error50) { @@ -146914,7 +150906,7 @@ var ProcessTransport = class { } write(data) { if (this.abortController.signal.aborted) { - throw new AbortError("Operation aborted"); + throw new AbortError2("Operation aborted"); } if (!this.ready || !this.processStdin) { throw new Error("ProcessTransport is not ready for writing"); @@ -147029,7 +151021,7 @@ var ProcessTransport = class { return new Promise((resolve2, reject) => { const exitHandler = (code, signal) => { if (this.abortController.signal.aborted) { - reject(new AbortError("Operation aborted")); + reject(new AbortError2("Operation aborted")); return; } const error50 = this.getProcessExitError(code, signal); @@ -147523,7 +151515,7 @@ var Query = class { logForDebugging2(`[Query] Calling transport.endInput() to close stdin to CLI process`); this.transport.endInput(); } catch (error50) { - if (!(error50 instanceof AbortError)) { + if (!(error50 instanceof AbortError2)) { throw error50; } } @@ -147967,8 +151959,8 @@ function getErrorMap3() { return overrideErrorMap2; } var makeIssue2 = (params) => { - const { data, path: path3, errorMaps, issueData } = params; - const fullPath = [...path3, ...issueData.path || []]; + const { data, path: path4, errorMaps, issueData } = params; + const fullPath = [...path4, ...issueData.path || []]; const fullIssue = { ...issueData, path: fullPath @@ -148075,11 +152067,11 @@ var errorUtil2; errorUtil22.toString = (message) => typeof message === "string" ? message : message?.message; })(errorUtil2 || (errorUtil2 = {})); var ParseInputLazyPath2 = class { - constructor(parent, value2, path3, key) { + constructor(parent, value2, path4, key) { this._cachedPath = []; this.parent = parent; this.data = value2; - this._path = path3; + this._path = path4; this._key = key; } get path() { @@ -151572,10 +155564,10 @@ function assignProp3(target, prop, value2) { configurable: true }); } -function getElementAtPath2(obj, path3) { - if (!path3) +function getElementAtPath2(obj, path4) { + if (!path4) return obj; - return path3.reduce((acc, key) => acc?.[key], obj); + return path4.reduce((acc, key) => acc?.[key], obj); } function promiseAllObject2(promisesObj) { const keys = Object.keys(promisesObj); @@ -151892,11 +155884,11 @@ function aborted3(x, startIndex = 0) { } return false; } -function prefixIssues3(path3, issues) { +function prefixIssues3(path4, issues) { return issues.map((iss) => { var _a2; (_a2 = iss).path ?? (_a2.path = []); - iss.path.unshift(path3); + iss.path.unshift(path4); return iss; }); } @@ -156015,6 +160007,7 @@ var package_default = { dotenv: "^17.2.3", execa: "^9.6.0", fastmcp: "^3.26.8", + "file-type": "^21.3.0", "package-manager-detector": "^1.6.0", semver: "^7.7.3", table: "^6.9.0", @@ -156252,7 +160245,7 @@ var agent = (input) => { const bash = ctx.payload.bash; const web = ctx.payload.web; const search2 = ctx.payload.search; - const write = ctx.payload.write; + const write2 = ctx.payload.write; log.info(`\xBB running ${input.name} with effort=${ctx.payload.effort}...`); const eventWithInstructions = ctx.instructions.eventInstructions ? `additionalInstructions: ${ctx.instructions.eventInstructions} ${ctx.instructions.event}` : ctx.instructions.event; @@ -156260,7 +160253,7 @@ ${ctx.instructions.event}` : ctx.instructions.event; log.box(logParts.join("\n\n---\n\n"), { title: "Instructions" }); - log.info(`\xBB tool permissions: web=${web}, search=${search2}, write=${write}, bash=${bash}`); + log.info(`\xBB tool permissions: web=${web}, search=${search2}, write=${write2}, bash=${bash}`); return input.run(ctx); }, ...agentsManifest[input.name] @@ -156416,9 +160409,9 @@ import { mkdirSync as mkdirSync3, writeFileSync as writeFileSync6 } from "node:f import { join as join10 } from "node:path"; // node_modules/.pnpm/@openai+codex-sdk@0.80.0/node_modules/@openai/codex-sdk/dist/index.js -import { promises as fs3 } from "fs"; +import { promises as fs4 } from "fs"; import os from "os"; -import path2 from "path"; +import path3 from "path"; import { spawn as spawn4 } from "child_process"; import path22 from "path"; import readline from "readline"; @@ -156431,16 +160424,16 @@ async function createOutputSchemaFile(schema2) { if (!isJsonObject2(schema2)) { throw new Error("outputSchema must be a plain JSON object"); } - const schemaDir = await fs3.mkdtemp(path2.join(os.tmpdir(), "codex-output-schema-")); - const schemaPath = path2.join(schemaDir, "schema.json"); + const schemaDir = await fs4.mkdtemp(path3.join(os.tmpdir(), "codex-output-schema-")); + const schemaPath = path3.join(schemaDir, "schema.json"); const cleanup = async () => { try { - await fs3.rm(schemaDir, { recursive: true, force: true }); + await fs4.rm(schemaDir, { recursive: true, force: true }); } catch { } }; try { - await fs3.writeFile(schemaPath, JSON.stringify(schema2), "utf8"); + await fs4.writeFile(schemaPath, JSON.stringify(schema2), "utf8"); return { schemaPath, cleanup }; } catch (error50) { await cleanup(); @@ -156795,7 +160788,9 @@ ${featuresSection} ${mcpServerSections.join("\n\n")} `.trim() + "\n" ); - log.info(`\xBB Codex config written to ${configPath} (shell: ${bash === "enabled" ? "enabled" : "disabled"})`); + log.info( + `\xBB Codex config written to ${configPath} (shell: ${bash === "enabled" ? "enabled" : "disabled"})` + ); return codexDir; } async function installCodex() { @@ -156955,7 +160950,7 @@ var messageHandlers2 = { // agents/cursor.ts import { spawn as spawn5 } from "node:child_process"; -import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync3, writeFileSync as writeFileSync7 } from "node:fs"; +import { existsSync as existsSync6, mkdirSync as mkdirSync4, readFileSync as readFileSync4, writeFileSync as writeFileSync7 } from "node:fs"; import { homedir as homedir2 } from "node:os"; import { join as join11 } from "node:path"; var cursorEffortModels = { @@ -156986,7 +160981,7 @@ var cursor = agent({ let modelOverride = null; if (existsSync6(projectCliConfigPath)) { try { - const projectConfig = JSON.parse(readFileSync3(projectCliConfigPath, "utf-8")); + const projectConfig = JSON.parse(readFileSync4(projectCliConfigPath, "utf-8")); if (projectConfig.model) { log.info(`\xBB using model from project .cursor/cli.json: ${projectConfig.model}`); } else { @@ -157191,7 +161186,7 @@ function configureCursorTools(ctx) { } // agents/gemini.ts -import { mkdirSync as mkdirSync5, readFileSync as readFileSync4, writeFileSync as writeFileSync8 } from "node:fs"; +import { mkdirSync as mkdirSync5, readFileSync as readFileSync5, writeFileSync as writeFileSync8 } from "node:fs"; import { homedir as homedir3 } from "node:os"; import { join as join12 } from "node:path"; var geminiEffortConfig = { @@ -157369,7 +161364,7 @@ function configureGeminiSettings(ctx) { mkdirSync5(geminiConfigDir, { recursive: true }); let existingSettings = {}; try { - const content = readFileSync4(settingsPath, "utf-8"); + const content = readFileSync5(settingsPath, "utf-8"); existingSettings = JSON.parse(content); } catch { } @@ -157812,7 +161807,7 @@ function collectApiKeys(agent2) { } return apiKeys; } -function validateApiKey(params) { +function validateAgentApiKey(params) { const apiKeys = collectApiKeys(params.agent); if (Object.keys(apiKeys).length === 0) { throw new Error( @@ -158032,8 +162027,8 @@ function buildRuntimeContext(ctx) { } const data = { ...payloadRest, - repo: `${ctx.repoData.owner}/${ctx.repoData.name}`, - default_branch: ctx.repoData.repo.default_branch, + repo: `${ctx.repo.owner}/${ctx.repo.name}`, + default_branch: ctx.repo.data.default_branch, working_directory: process.cwd(), log_level: process.env.LOG_LEVEL, git_status: gitStatus, @@ -158103,7 +162098,7 @@ You are careful, to-the-point, and kind. You only say things you know to be true You do not break up sentences with hyphens. You use emdashes. You have a strong bias toward minimalism: no dead code, no premature abstractions, no speculative features, and no comments that merely restate what the code does. Your code is focused, elegant, and production-ready. -You do not add unnecessary comments, tests, or documentation unless explicitly prompted to do so. +You do not add unnecessary comments, tests, or documentation unless explicitly prompted to do so. You adapt your writing style to match existing patterns in the codebase (commit messages, PR descriptions, code comments) while never being unprofessional. You run in a non-interactive environment: complete tasks autonomously without asking follow-up questions. You are running inside a GitHub Actions ephemeral environment. All processes and resources will be cleaned up at the end of the run. @@ -158261,7 +162256,8 @@ var import_semver = __toESM(require_semver2(), 1); var COMPATIBILITY_POLICY = "non-breaking"; function validateCompatibility(payloadVersion, actionVersion) { const payloadSemVer = import_semver.default.parse(payloadVersion); - if (!payloadSemVer) throw new Error(`Payload version ${payloadVersion} is not a valid semantic version.`); + if (!payloadSemVer) + throw new Error(`Payload version ${payloadVersion} is not a valid semantic version.`); const major = payloadSemVer.major; const minor = payloadSemVer.minor; const patch = payloadSemVer.patch; @@ -158373,79 +162369,6 @@ function resolvePayload(repoSettings) { }; } -// utils/repoSettings.ts -async function fetchRepoSettings(params) { - const apiUrl = process.env.API_URL || "https://pullfrog.com"; - const timeoutMs = 3e4; - const controller = new AbortController(); - const timeoutId = setTimeout(() => controller.abort(), timeoutMs); - try { - const response = await fetch( - `${apiUrl}/api/repo/${params.repoContext.owner}/${params.repoContext.name}/settings`, - { - method: "GET", - headers: { - Authorization: `Bearer ${params.token}`, - "Content-Type": "application/json" - }, - signal: controller.signal - } - ); - clearTimeout(timeoutId); - if (!response.ok) { - return { - defaultAgent: null, - modes: [], - repoInstructions: "", - web: "enabled", - search: "enabled", - write: "enabled", - bash: "restricted" - }; - } - const settings = await response.json(); - if (settings === null) { - return { - defaultAgent: null, - modes: [], - repoInstructions: "", - web: "enabled", - search: "enabled", - write: "enabled", - bash: "restricted" - }; - } - return settings; - } catch { - clearTimeout(timeoutId); - return { - defaultAgent: null, - modes: [], - repoInstructions: "", - web: "enabled", - search: "enabled", - write: "enabled", - bash: "restricted" - }; - } -} - -// utils/repoData.ts -async function resolveRepoData(params) { - log.info(`\xBB running Pullfrog v${package_default.version}...`); - const { owner, name } = parseRepoContext(); - const [repoResponse, repoSettings] = await Promise.all([ - params.octokit.repos.get({ owner, repo: name }), - fetchRepoSettings({ token: params.token, repoContext: { owner, name } }) - ]); - return { - owner, - name, - repo: repoResponse.data, - repoSettings - }; -} - // utils/run.ts async function handleAgentResult(result) { if (!result.success) { @@ -158462,6 +162385,74 @@ async function handleAgentResult(result) { }; } +// utils/runContext.ts +var defaultSettings = { + defaultAgent: null, + modes: [], + repoInstructions: "", + web: "enabled", + search: "enabled", + write: "enabled", + bash: "restricted" +}; +var defaultRunContext = { + settings: defaultSettings, + apiToken: "" +}; +async function fetchRunContext(params) { + const apiUrl = process.env.API_URL || "https://pullfrog.com"; + const timeoutMs = 3e4; + const controller = new AbortController(); + const timeoutId = setTimeout(() => controller.abort(), timeoutMs); + try { + const response = await fetch( + `${apiUrl}/api/repo/${params.repoContext.owner}/${params.repoContext.name}/run-context`, + { + method: "GET", + headers: { + Authorization: `Bearer ${params.token}`, + "Content-Type": "application/json" + }, + signal: controller.signal + } + ); + clearTimeout(timeoutId); + if (!response.ok) { + return defaultRunContext; + } + const data = await response.json(); + if (data === null) { + return defaultRunContext; + } + return { + settings: data.settings ?? defaultSettings, + apiToken: data.apiToken + }; + } catch { + clearTimeout(timeoutId); + return defaultRunContext; + } +} + +// utils/runContextData.ts +async function resolveRunContextData(params) { + log.info(`\xBB running Pullfrog v${package_default.version}...`); + const repoContext = parseRepoContext(); + const [repoResponse, runContext] = await Promise.all([ + params.octokit.repos.get({ owner: repoContext.owner, repo: repoContext.name }), + fetchRunContext({ token: params.token, repoContext }) + ]); + return { + repo: { + owner: repoContext.owner, + name: repoContext.name, + data: repoResponse.data + }, + repoSettings: runContext.settings, + apiToken: runContext.apiToken + }; +} + // utils/setup.ts import { execSync as execSync2 } from "node:child_process"; import { mkdtempSync } from "node:fs"; @@ -158625,14 +162616,18 @@ async function main() { try { var _stack = []; try { - const repo = await resolveRepoData({ octokit, token: tokenRef.token }); - timer.checkpoint("repoData"); - const payload = resolvePayload(repo.repoSettings); + const runContext = await resolveRunContextData({ octokit, token: tokenRef.token }); + timer.checkpoint("runContextData"); + const payload = resolvePayload(runContext.repoSettings); if (payload.cwd && process.cwd() !== payload.cwd) { process.chdir(payload.cwd); } const originalBody = payload.event.body; - const resolvedBody = await resolveBody({ event: payload.event, octokit, repo }); + const resolvedBody = await resolveBody({ + event: payload.event, + octokit, + repo: runContext.repo + }); if (resolvedBody !== originalBody) { payload.event.body = resolvedBody; if (originalBody && payload.prompt.includes(originalBody)) { @@ -158640,29 +162635,30 @@ async function main() { } } const tmpdir3 = createTempDirectory(); - const agent2 = resolveAgent({ payload, repoSettings: repo.repoSettings }); - validateApiKey({ + const agent2 = resolveAgent({ payload, repoSettings: runContext.repoSettings }); + validateAgentApiKey({ agent: agent2, - owner: repo.owner, - name: repo.name + owner: runContext.repo.owner, + name: runContext.repo.name }); await setupGit({ token: tokenRef.token, originalToken: process.env.ORIGINAL_GITHUB_TOKEN, bashPermission: payload.bash, - owner: repo.owner, - name: repo.name, + owner: runContext.repo.owner, + name: runContext.repo.name, event: payload.event, octokit, toolState }); timer.checkpoint("git"); - const modes2 = [...computeModes(), ...repo.repoSettings.modes]; + const modes2 = [...computeModes(), ...runContext.repoSettings.modes]; const mcpHttpServer = __using(_stack, await startMcpHttpServer({ - repo, + repo: runContext.repo, payload, octokit, githubInstallationToken: tokenRef.token, + apiToken: runContext.apiToken, agent: agent2, modes: modes2, toolState, @@ -158673,7 +162669,7 @@ async function main() { timer.checkpoint("mcpServer"); const instructions = resolveInstructions({ payload, - repoData: repo, + repo: runContext.repo, modes: modes2 }); const result = await agent2.run({ @@ -158731,6 +162727,9 @@ undici/lib/websocket/frame.js: undici/lib/web/websocket/frame.js: (*! ws. MIT License. Einar Otto Stangvik *) +ieee754/index.js: + (*! ieee754. BSD-3-Clause License. Feross Aboukhadijeh *) + @mixmark-io/domino/lib/style_parser.js: (** * @license diff --git a/index.ts b/index.ts index 5178ce0..d45f4ee 100644 --- a/index.ts +++ b/index.ts @@ -3,7 +3,7 @@ * This exports the main function for programmatic usage */ -export type { Agent, AgentRunContext, AgentResult } from "./agents/shared.ts"; +export type { Agent, AgentResult, AgentRunContext } from "./agents/shared.ts"; export { type Inputs as ExecutionInputs, type MainResult, diff --git a/main.ts b/main.ts index 8b2b4b5..8ff980b 100644 --- a/main.ts +++ b/main.ts @@ -2,7 +2,7 @@ import { initToolState, startMcpHttpServer } from "./mcp/server.ts"; import { computeModes } from "./modes.ts"; import { resolveAgent } from "./utils/agent.ts"; -import { validateApiKey } from "./utils/apiKeys.ts"; +import { validateAgentApiKey } from "./utils/apiKeys.ts"; import { resolveBody } from "./utils/body.ts"; import { log, writeSummary } from "./utils/cli.ts"; import { reportErrorToComment } from "./utils/errorReport.ts"; @@ -11,8 +11,8 @@ import { createOctokit } from "./utils/github.ts"; import { resolveInstructions } from "./utils/instructions.ts"; import { normalizeEnv } from "./utils/normalizeEnv.ts"; import { resolvePayload } from "./utils/payload.ts"; -import { resolveRepoData } from "./utils/repoData.ts"; import { handleAgentResult } from "./utils/run.ts"; +import { resolveRunContextData } from "./utils/runContextData.ts"; import { createTempDirectory, setupGit } from "./utils/setup.ts"; import { Timer } from "./utils/timer.ts"; import { resolveInstallationToken } from "./utils/token.ts"; @@ -44,12 +44,12 @@ export async function main(): Promise { setupExitHandler(toolState); try { - const repo = await resolveRepoData({ octokit, token: tokenRef.token }); - timer.checkpoint("repoData"); + const runContext = await resolveRunContextData({ octokit, token: tokenRef.token }); + timer.checkpoint("runContextData"); - // resolve payload after repoData so permissions can use DB settings + // resolve payload after runContextData so permissions can use DB settings // precedence: action inputs > json payload > repoSettings > fallbacks - const payload = resolvePayload(repo.repoSettings); + const payload = resolvePayload(runContext.repoSettings); if (payload.cwd && process.cwd() !== payload.cwd) { process.chdir(payload.cwd); } @@ -57,7 +57,11 @@ export async function main(): Promise { // resolve body - fetches body_html and converts to markdown if images present // this ensures agents receive markdown with working signed image URLs const originalBody = payload.event.body; - const resolvedBody = await resolveBody({ event: payload.event, octokit, repo }); + const resolvedBody = await resolveBody({ + event: payload.event, + octokit, + repo: runContext.repo, + }); if (resolvedBody !== originalBody) { payload.event.body = resolvedBody; // also update prompt if original body was included there @@ -68,33 +72,34 @@ export async function main(): Promise { const tmpdir = createTempDirectory(); - const agent = resolveAgent({ payload, repoSettings: repo.repoSettings }); + const agent = resolveAgent({ payload, repoSettings: runContext.repoSettings }); - validateApiKey({ + validateAgentApiKey({ agent, - owner: repo.owner, - name: repo.name, + owner: runContext.repo.owner, + name: runContext.repo.name, }); await setupGit({ token: tokenRef.token, originalToken: process.env.ORIGINAL_GITHUB_TOKEN, bashPermission: payload.bash, - owner: repo.owner, - name: repo.name, + owner: runContext.repo.owner, + name: runContext.repo.name, event: payload.event, octokit, toolState, }); timer.checkpoint("git"); - const modes = [...computeModes(), ...repo.repoSettings.modes]; + const modes = [...computeModes(), ...runContext.repoSettings.modes]; await using mcpHttpServer = await startMcpHttpServer({ - repo, + repo: runContext.repo, payload, octokit, githubInstallationToken: tokenRef.token, + apiToken: runContext.apiToken, agent, modes, toolState, @@ -106,7 +111,7 @@ export async function main(): Promise { const instructions = resolveInstructions({ payload, - repoData: repo, + repo: runContext.repo, modes, }); diff --git a/mcp/bash.ts b/mcp/bash.ts index 0c5c36b..7b91ff1 100644 --- a/mcp/bash.ts +++ b/mcp/bash.ts @@ -49,7 +49,7 @@ function spawnBash(params: SpawnParams): ChildProcess { // return useNamespaceIsolation // ? spawn("unshare", ["--pid", "--fork", "--mount-proc", "bash", "-c", params.command], spawnOpts) // : spawn("bash", ["-c", params.command], spawnOpts); - return spawn("bash", ["-c", params.command], spawnOpts); + return spawn("bash", ["-c", params.command], spawnOpts); } /** kill process and its entire process group */ diff --git a/mcp/dependencies.ts b/mcp/dependencies.ts index 6ee9ef3..e63569a 100644 --- a/mcp/dependencies.ts +++ b/mcp/dependencies.ts @@ -1,7 +1,7 @@ import { type } from "arktype"; -import type { ToolContext } from "./server.ts"; import type { PrepResult } from "../prep/index.ts"; import { runPrepPhase } from "../prep/index.ts"; +import type { ToolContext } from "./server.ts"; import { execute, tool } from "./shared.ts"; // empty schema for tools with no parameters diff --git a/mcp/git.ts b/mcp/git.ts index 76300c6..5e22ea3 100644 --- a/mcp/git.ts +++ b/mcp/git.ts @@ -6,7 +6,7 @@ import type { ToolContext } from "./server.ts"; import { execute, tool } from "./shared.ts"; export function CreateBranchTool(ctx: ToolContext) { - const defaultBranch = ctx.repo.repo.default_branch || "main"; + const defaultBranch = ctx.repo.data.default_branch || "main"; const CreateBranch = type({ branchName: type.string.describe( @@ -24,7 +24,7 @@ export function CreateBranchTool(ctx: ToolContext) { parameters: CreateBranch, execute: execute(async ({ branchName, baseBranch }) => { // baseBranch should always be defined due to default, but TypeScript needs help - const resolvedBaseBranch = baseBranch || ctx.repo.repo.default_branch || "main"; + const resolvedBaseBranch = baseBranch || ctx.repo.data.default_branch || "main"; // validate branch name for secrets if (containsSecrets(branchName)) { @@ -142,7 +142,7 @@ export const PushBranch = type({ }); export function PushBranchTool(ctx: ToolContext) { - const defaultBranch = ctx.repo.repo.default_branch || "main"; + const defaultBranch = ctx.repo.data.default_branch || "main"; return tool({ name: "push_branch", diff --git a/mcp/server.ts b/mcp/server.ts index 54f7056..be157e7 100644 --- a/mcp/server.ts +++ b/mcp/server.ts @@ -8,7 +8,6 @@ import type { Mode } from "../modes.ts"; import type { PrepResult } from "../prep/index.ts"; import type { OctokitWithPlugins } from "../utils/github.ts"; import type { ResolvedPayload } from "../utils/payload.ts"; -import type { RepoData } from "../utils/repoData.ts"; export type BackgroundProcess = { pid: number; @@ -53,10 +52,11 @@ export function initToolState(ctx: InitToolStateParams): ToolState { } export interface ToolContext { - repo: RepoData; + repo: RunContextData["repo"]; payload: ResolvedPayload; octokit: OctokitWithPlugins; githubInstallationToken: string; + apiToken: string; agent: Agent; modes: Mode[]; toolState: ToolState; @@ -64,6 +64,7 @@ export interface ToolContext { jobId: string | undefined; } +import type { RunContextData } from "../utils/runContextData.ts"; import { BashTool, KillBackgroundTool } from "./bash.ts"; import { CheckoutPrTool } from "./checkout.ts"; import { GetCheckSuiteLogsTool } from "./checkSuite.ts"; @@ -90,6 +91,7 @@ import { CreatePullRequestReviewTool } from "./review.ts"; import { GetReviewCommentsTool, ListPullRequestReviewsTool } from "./reviewComments.ts"; import { SelectModeTool } from "./selectMode.ts"; import { addTools } from "./shared.ts"; +import { UploadFileTool } from "./upload.ts"; /** * Find an available port starting from the given port @@ -176,6 +178,7 @@ export async function startMcpHttpServer( CreateBranchTool(ctx), CommitFilesTool(ctx), PushBranchTool(ctx), + UploadFileTool(ctx), ]; // only add BashTool when bash is "restricted" diff --git a/mcp/upload.ts b/mcp/upload.ts new file mode 100644 index 0000000..29638e9 --- /dev/null +++ b/mcp/upload.ts @@ -0,0 +1,69 @@ +import * as fs from "node:fs"; +import * as path from "node:path"; +import { type } from "arktype"; +import { fileTypeFromBuffer } from "file-type"; +import type { ToolContext } from "./server.ts"; +import { execute, tool } from "./shared.ts"; + +const UploadFileParams = type({ + path: type.string.describe("absolute path to file to upload"), +}); + +export function UploadFileTool(ctx: ToolContext) { + return tool({ + name: "upload_file", + description: + "upload a file to get a permanent public URL. use for screenshots, artifacts, or any files you want to reference in PRs/comments. max 10MB, images/text/archives allowed.", + parameters: UploadFileParams, + execute: execute(async (params) => { + // read file from disk eagerly on purpose to avoid its content being changed by the time it's uploaded + const buffer = fs.readFileSync(params.path); + const filename = path.basename(params.path); + const contentLength = buffer.length; + + const fileType = await fileTypeFromBuffer(buffer); + const contentType = fileType?.mime || "application/octet-stream"; + + const apiUrl = process.env.API_URL || "https://pullfrog.com"; + + const response = await fetch(`${apiUrl}/api/upload/signed-url`, { + method: "POST", + headers: { + Authorization: `Bearer ${ctx.apiToken}`, + "Content-Type": "application/json", + }, + body: JSON.stringify({ + filename, + contentType, + contentLength, + }), + }); + + if (!response.ok) { + const error = await response.text(); + throw new Error(`failed to get upload URL: ${error}`); + } + + const { uploadUrl, publicUrl } = (await response.json()) as { + uploadUrl: string; + publicUrl: string; + }; + + const uploadResponse = await fetch(uploadUrl, { + method: "PUT", + headers: { + "Content-Type": contentType, + // should be set automatically, but given this header is signed it's better to be explicit + "Content-Length": String(contentLength), + }, + body: buffer, + }); + + if (!uploadResponse.ok) { + throw new Error(`failed to upload file: ${uploadResponse.statusText}`); + } + + return { success: true, publicUrl, filename, contentLength, contentType }; + }), + }); +} diff --git a/package.json b/package.json index 0d35684..187e5fd 100644 --- a/package.json +++ b/package.json @@ -42,6 +42,7 @@ "dotenv": "^17.2.3", "execa": "^9.6.0", "fastmcp": "^3.26.8", + "file-type": "^21.3.0", "package-manager-detector": "^1.6.0", "semver": "^7.7.3", "table": "^6.9.0", diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml index ca471b7..f514060 100644 --- a/pnpm-lock.yaml +++ b/pnpm-lock.yaml @@ -56,6 +56,9 @@ importers: fastmcp: specifier: ^3.26.8 version: 3.26.8(arktype@2.1.28)(hono@4.11.3) + file-type: + specifier: ^21.3.0 + version: 21.3.0 package-manager-detector: specifier: ^1.6.0 version: 1.6.0 diff --git a/test/nobash.ts b/test/nobash.ts index bee9f0d..860559a 100644 --- a/test/nobash.ts +++ b/test/nobash.ts @@ -1,5 +1,5 @@ import type { AgentResult, ValidationCheck } from "./utils.ts"; -import { generateAgentUuids, defineFixture, getAgentOutput, runTests } from "./utils.ts"; +import { defineFixture, generateAgentUuids, getAgentOutput, runTests } from "./utils.ts"; /** * nobash test - validates agents respect bash=disabled setting. diff --git a/test/restricted.ts b/test/restricted.ts index f757f59..114366b 100644 --- a/test/restricted.ts +++ b/test/restricted.ts @@ -1,5 +1,5 @@ import type { AgentResult, ValidationCheck } from "./utils.ts"; -import { generateAgentUuids, defineFixture, getAgentOutput, runTests } from "./utils.ts"; +import { defineFixture, generateAgentUuids, getAgentOutput, runTests } from "./utils.ts"; /** * restricted test - validates bash=restricted environment filtering. diff --git a/test/utils.ts b/test/utils.ts index f29c1c6..079365b 100644 --- a/test/utils.ts +++ b/test/utils.ts @@ -1,5 +1,5 @@ -import { randomUUID } from "node:crypto"; import { spawn } from "node:child_process"; +import { randomUUID } from "node:crypto"; import { dirname, join } from "node:path"; import { fileURLToPath } from "node:url"; import { config } from "dotenv"; diff --git a/utils/agent.ts b/utils/agent.ts index b0dc012..8eb9f22 100644 --- a/utils/agent.ts +++ b/utils/agent.ts @@ -2,7 +2,7 @@ import { type Agent, agents } from "../agents/index.ts"; import type { AgentName } from "../external.ts"; import { log } from "./cli.ts"; import type { ResolvedPayload } from "./payload.ts"; -import type { RepoSettings } from "./repoSettings.ts"; +import type { RepoSettings } from "./runContext.ts"; /** * Check if an agent has API keys available (from process.env) diff --git a/utils/apiKeys.ts b/utils/apiKeys.ts index 00bb1a8..a7afd16 100644 --- a/utils/apiKeys.ts +++ b/utils/apiKeys.ts @@ -56,7 +56,7 @@ function collectApiKeys(agent: Agent): Record { return apiKeys; } -export function validateApiKey(params: { agent: Agent; owner: string; name: string }): void { +export function validateAgentApiKey(params: { agent: Agent; owner: string; name: string }): void { const apiKeys = collectApiKeys(params.agent); if (Object.keys(apiKeys).length === 0) { diff --git a/utils/body.ts b/utils/body.ts index dfd1989..9e357f5 100644 --- a/utils/body.ts +++ b/utils/body.ts @@ -2,7 +2,7 @@ import TurndownService from "turndown"; import type { PayloadEvent } from "../external.ts"; import { log } from "./cli.ts"; import type { OctokitWithPlugins } from "./github.ts"; -import type { RepoData } from "./repoData.ts"; +import type { RunContextData } from "./runContextData.ts"; const turndown = new TurndownService(); @@ -14,7 +14,7 @@ function hasImages(body: string | null | undefined): boolean { interface ResolveBodyContext { event: PayloadEvent; octokit: OctokitWithPlugins; - repo: RepoData; + repo: RunContextData["repo"]; } /** diff --git a/utils/github.ts b/utils/github.ts index 1ca0133..10e4340 100644 --- a/utils/github.ts +++ b/utils/github.ts @@ -1,4 +1,3 @@ -import assert from "node:assert/strict"; import { createSign } from "node:crypto"; import * as core from "@actions/core"; import { throttling } from "@octokit/plugin-throttling"; diff --git a/utils/instructions.ts b/utils/instructions.ts index 8d61169..5f6458b 100644 --- a/utils/instructions.ts +++ b/utils/instructions.ts @@ -4,11 +4,11 @@ import { encode as toonEncode } from "@toon-format/toon"; import { ghPullfrogMcpName, type PayloadEvent } from "../external.ts"; import type { Mode } from "../modes.ts"; import type { ResolvedPayload } from "./payload.ts"; -import type { RepoData } from "./repoData.ts"; +import type { RunContextData } from "./runContextData.ts"; interface InstructionsContext { payload: ResolvedPayload; - repoData: RepoData; + repo: RunContextData["repo"]; modes: Mode[]; } @@ -33,8 +33,8 @@ function buildRuntimeContext(ctx: InstructionsContext): string { const data: Record = { ...payloadRest, - repo: `${ctx.repoData.owner}/${ctx.repoData.name}`, - default_branch: ctx.repoData.repo.default_branch, + repo: `${ctx.repo.owner}/${ctx.repo.name}`, + default_branch: ctx.repo.data.default_branch, working_directory: process.cwd(), log_level: process.env.LOG_LEVEL, git_status: gitStatus, @@ -150,7 +150,7 @@ You are careful, to-the-point, and kind. You only say things you know to be true You do not break up sentences with hyphens. You use emdashes. You have a strong bias toward minimalism: no dead code, no premature abstractions, no speculative features, and no comments that merely restate what the code does. Your code is focused, elegant, and production-ready. -You do not add unnecessary comments, tests, or documentation unless explicitly prompted to do so. +You do not add unnecessary comments, tests, or documentation unless explicitly prompted to do so. You adapt your writing style to match existing patterns in the codebase (commit messages, PR descriptions, code comments) while never being unprofessional. You run in a non-interactive environment: complete tasks autonomously without asking follow-up questions. You are running inside a GitHub Actions ephemeral environment. All processes and resources will be cleaned up at the end of the run. diff --git a/utils/payload.ts b/utils/payload.ts index d1d0363..8726e37 100644 --- a/utils/payload.ts +++ b/utils/payload.ts @@ -3,7 +3,7 @@ import * as core from "@actions/core"; import { type } from "arktype"; import { AgentName, type AuthorPermission, Effort, type PayloadEvent } from "../external.ts"; import packageJson from "../package.json" with { type: "json" }; -import type { RepoSettings } from "./repoSettings.ts"; +import type { RepoSettings } from "./runContext.ts"; import { validateCompatibility } from "./versioning.ts"; // tool permission enum types for inputs diff --git a/utils/repoData.ts b/utils/repoData.ts deleted file mode 100644 index e3d012d..0000000 --- a/utils/repoData.ts +++ /dev/null @@ -1,42 +0,0 @@ -import type { Octokit } from "@octokit/rest"; -import packageJson from "../package.json" with { type: "json" }; -import { log } from "./cli.ts"; -import { createOctokit, type OctokitWithPlugins, parseRepoContext } from "./github.ts"; -import { fetchRepoSettings, type RepoSettings } from "./repoSettings.ts"; - -export interface RepoData { - owner: string; - name: string; - repo: Awaited>["data"]; - repoSettings: RepoSettings; -} - -interface ResolveRepoDataParams { - octokit: OctokitWithPlugins; - token: string; -} - -/** - * Initialize repo data: parse context, fetch repo info and settings - */ -export async function resolveRepoData(params: ResolveRepoDataParams): Promise { - log.info(`» running Pullfrog v${packageJson.version}...`); - - const { owner, name } = parseRepoContext(); - - // fetch repo data and settings in parallel - const [repoResponse, repoSettings] = await Promise.all([ - params.octokit.repos.get({ owner, repo: name }), - fetchRepoSettings({ token: params.token, repoContext: { owner, name } }), - ]); - - return { - owner, - name, - repo: repoResponse.data, - repoSettings, - }; -} - -// re-export for convenience -export { createOctokit }; diff --git a/utils/repoSettings.ts b/utils/runContext.ts similarity index 55% rename from utils/repoSettings.ts rename to utils/runContext.ts index 28f9975..024ea6a 100644 --- a/utils/repoSettings.ts +++ b/utils/runContext.ts @@ -18,14 +18,35 @@ export interface RepoSettings { bash: BashPermission; } +export interface RunContext { + settings: RepoSettings; + apiToken: string; +} + +const defaultSettings: RepoSettings = { + defaultAgent: null, + modes: [], + repoInstructions: "", + web: "enabled", + search: "enabled", + write: "enabled", + bash: "restricted", +}; + +const defaultRunContext: RunContext = { + settings: defaultSettings, + apiToken: "", +}; + /** - * Fetch repository settings from the Pullfrog API - * Returns defaults if repo doesn't exist or fetch fails + * fetch run context from Pullfrog API + * returns settings + API token for subsequent calls + * returns defaults if fetch fails */ -export async function fetchRepoSettings(params: { +export async function fetchRunContext(params: { token: string; repoContext: RepoContext; -}): Promise { +}): Promise { const apiUrl = process.env.API_URL || "https://pullfrog.com"; const timeoutMs = 30000; const controller = new AbortController(); @@ -33,7 +54,7 @@ export async function fetchRepoSettings(params: { try { const response = await fetch( - `${apiUrl}/api/repo/${params.repoContext.owner}/${params.repoContext.name}/settings`, + `${apiUrl}/api/repo/${params.repoContext.owner}/${params.repoContext.name}/run-context`, { method: "GET", headers: { @@ -47,41 +68,24 @@ export async function fetchRepoSettings(params: { clearTimeout(timeoutId); if (!response.ok) { - return { - defaultAgent: null, - modes: [], - repoInstructions: "", - web: "enabled", - search: "enabled", - write: "enabled", - bash: "restricted", - }; + return defaultRunContext; } - const settings = (await response.json()) as RepoSettings | null; - if (settings === null) { - return { - defaultAgent: null, - modes: [], - repoInstructions: "", - web: "enabled", - search: "enabled", - write: "enabled", - bash: "restricted", - }; + const data = (await response.json()) as { + settings: RepoSettings | null; + apiToken: string; + } | null; + + if (data === null) { + return defaultRunContext; } - return settings; + return { + settings: data.settings ?? defaultSettings, + apiToken: data.apiToken, + }; } catch { clearTimeout(timeoutId); - return { - defaultAgent: null, - modes: [], - repoInstructions: "", - web: "enabled", - search: "enabled", - write: "enabled", - bash: "restricted", - }; + return defaultRunContext; } } diff --git a/utils/runContextData.ts b/utils/runContextData.ts new file mode 100644 index 0000000..68d84cf --- /dev/null +++ b/utils/runContextData.ts @@ -0,0 +1,46 @@ +import type { Octokit } from "@octokit/rest"; +import packageJson from "../package.json" with { type: "json" }; +import { log } from "./cli.ts"; +import { type OctokitWithPlugins, parseRepoContext } from "./github.ts"; +import { fetchRunContext, type RepoSettings } from "./runContext.ts"; + +export interface RunContextData { + repo: { + owner: string; + name: string; + data: Awaited>["data"]; + }; + repoSettings: RepoSettings; + apiToken: string; +} + +interface ResolveRunContextDataParams { + octokit: OctokitWithPlugins; + token: string; +} + +/** + * initialize run context data: parse context, fetch repo info and settings + */ +export async function resolveRunContextData( + params: ResolveRunContextDataParams +): Promise { + log.info(`» running Pullfrog v${packageJson.version}...`); + + const repoContext = parseRepoContext(); + + const [repoResponse, runContext] = await Promise.all([ + params.octokit.repos.get({ owner: repoContext.owner, repo: repoContext.name }), + fetchRunContext({ token: params.token, repoContext }), + ]); + + return { + repo: { + owner: repoContext.owner, + name: repoContext.name, + data: repoResponse.data, + }, + repoSettings: runContext.settings, + apiToken: runContext.apiToken, + }; +} diff --git a/utils/setup.ts b/utils/setup.ts index 8e58cce..559eccd 100644 --- a/utils/setup.ts +++ b/utils/setup.ts @@ -134,10 +134,8 @@ export async function setupGit(params: SetupGitParams): Promise { // - restricted/disabled: workflow token (limited by permissions block) // this protects the base repo while allowing fork PR edits via fork remote const originToken = - params.bashPermission === "enabled" - ? params.token - : (params.originalToken || params.token); - + params.bashPermission === "enabled" ? params.token : params.originalToken || params.token; + // non-PR events: set up origin with token, stay on default branch if (params.event.is_pr !== true || !params.event.issue_number) { const originUrl = `https://x-access-token:${originToken}@github.com/${params.owner}/${params.name}.git`; diff --git a/utils/timer.test.ts b/utils/timer.test.ts index 9b41743..12a3881 100644 --- a/utils/timer.test.ts +++ b/utils/timer.test.ts @@ -1,9 +1,9 @@ -import { Timer } from './timer.ts'; -import * as cli from './cli.ts'; +import * as cli from "./cli.ts"; +import { Timer } from "./timer.ts"; -describe('Timer', () => { +describe("Timer", () => { beforeEach(() => { - vi.spyOn(cli.log, 'debug'); + vi.spyOn(cli.log, "debug"); // Mock Date.now to have predictable timestamps vi.useFakeTimers(); }); @@ -13,34 +13,32 @@ describe('Timer', () => { vi.useRealTimers(); }); - describe('constructor', () => { - it('should initialize with current timestamp', () => { + describe("constructor", () => { + it("should initialize with current timestamp", () => { const mockTime = 1000000; vi.setSystemTime(mockTime); const timer = new Timer(); - timer.checkpoint('test'); + timer.checkpoint("test"); - expect(cli.log.debug).toHaveBeenCalledWith( - expect.stringContaining('test') - ); + expect(cli.log.debug).toHaveBeenCalledWith(expect.stringContaining("test")); }); }); - describe('checkpoint', () => { - it('should log duration from initial timestamp on first checkpoint', () => { + describe("checkpoint", () => { + it("should log duration from initial timestamp on first checkpoint", () => { const startTime = 1000000; vi.setSystemTime(startTime); const timer = new Timer(); const checkpointTime = startTime + 100; vi.setSystemTime(checkpointTime); - timer.checkpoint('first'); + timer.checkpoint("first"); - expect(cli.log.debug).toHaveBeenCalledWith('» first: 100ms'); + expect(cli.log.debug).toHaveBeenCalledWith("» first: 100ms"); }); - it('should log duration from last checkpoint on subsequent checkpoints', () => { + it("should log duration from last checkpoint on subsequent checkpoints", () => { const startTime = 1000000; vi.setSystemTime(startTime); const timer = new Timer(); @@ -48,63 +46,61 @@ describe('Timer', () => { // First checkpoint const firstCheckpointTime = startTime + 50; vi.setSystemTime(firstCheckpointTime); - timer.checkpoint('first'); + timer.checkpoint("first"); // Second checkpoint const secondCheckpointTime = firstCheckpointTime + 75; vi.setSystemTime(secondCheckpointTime); - timer.checkpoint('second'); + timer.checkpoint("second"); expect(cli.log.debug).toHaveBeenCalledTimes(2); - expect(cli.log.debug).toHaveBeenNthCalledWith(1, '» first: 50ms'); - expect(cli.log.debug).toHaveBeenNthCalledWith(2, '» second: 75ms'); + expect(cli.log.debug).toHaveBeenNthCalledWith(1, "» first: 50ms"); + expect(cli.log.debug).toHaveBeenNthCalledWith(2, "» second: 75ms"); }); - it('should handle multiple checkpoints correctly', () => { + it("should handle multiple checkpoints correctly", () => { const startTime = 1000000; vi.setSystemTime(startTime); const timer = new Timer(); // First checkpoint vi.setSystemTime(startTime + 10); - timer.checkpoint('step1'); + timer.checkpoint("step1"); // Second checkpoint vi.setSystemTime(startTime + 25); - timer.checkpoint('step2'); + timer.checkpoint("step2"); // Third checkpoint vi.setSystemTime(startTime + 45); - timer.checkpoint('step3'); + timer.checkpoint("step3"); expect(cli.log.debug).toHaveBeenCalledTimes(3); - expect(cli.log.debug).toHaveBeenNthCalledWith(1, '» step1: 10ms'); - expect(cli.log.debug).toHaveBeenNthCalledWith(2, '» step2: 15ms'); - expect(cli.log.debug).toHaveBeenNthCalledWith(3, '» step3: 20ms'); + expect(cli.log.debug).toHaveBeenNthCalledWith(1, "» step1: 10ms"); + expect(cli.log.debug).toHaveBeenNthCalledWith(2, "» step2: 15ms"); + expect(cli.log.debug).toHaveBeenNthCalledWith(3, "» step3: 20ms"); }); - it('should handle zero duration correctly', () => { + it("should handle zero duration correctly", () => { const startTime = 1000000; vi.setSystemTime(startTime); const timer = new Timer(); // Checkpoint immediately - timer.checkpoint('immediate'); + timer.checkpoint("immediate"); - expect(cli.log.debug).toHaveBeenCalledWith('» immediate: 0ms'); + expect(cli.log.debug).toHaveBeenCalledWith("» immediate: 0ms"); }); - it('should handle custom checkpoint names', () => { + it("should handle custom checkpoint names", () => { const startTime = 1000000; vi.setSystemTime(startTime); const timer = new Timer(); vi.setSystemTime(startTime + 200); - timer.checkpoint('Custom Checkpoint Name'); + timer.checkpoint("Custom Checkpoint Name"); - expect(cli.log.debug).toHaveBeenCalledWith( - '» Custom Checkpoint Name: 200ms' - ); + expect(cli.log.debug).toHaveBeenCalledWith("» Custom Checkpoint Name: 200ms"); }); }); }); diff --git a/utils/versioning.test.ts b/utils/versioning.test.ts index 51ffdd9..217f9f6 100644 --- a/utils/versioning.test.ts +++ b/utils/versioning.test.ts @@ -1,9 +1,9 @@ -import { describe, it, expect } from 'vitest'; -import { validateCompatibility } from './versioning.ts'; +import { describe, expect, it } from "vitest"; +import { validateCompatibility } from "./versioning.ts"; -describe('validateCompatibility', () => { - it('should throw if payload version is invalid', () => { - expect(() => validateCompatibility('invalid', '1.0.0')).toThrow(/not a valid semantic version/); +describe("validateCompatibility", () => { + it("should throw if payload version is invalid", () => { + expect(() => validateCompatibility("invalid", "1.0.0")).toThrow(/not a valid semantic version/); }); it.each([ @@ -17,7 +17,7 @@ describe('validateCompatibility', () => { ["1.0.0", "1.1.0"], // action has a new feature (backward compatible) ["1.0.1", "1.0.0"], // payload is newer (patch) ["1.1.0", "1.0.0"], // payload is newer (feature is backward compatible) - ])('should accept compatible payload %#', (payloadVersion, actionVersion) => { + ])("should accept compatible payload %#", (payloadVersion, actionVersion) => { expect(() => validateCompatibility(payloadVersion, actionVersion)).not.toThrow(); }); @@ -26,7 +26,9 @@ describe('validateCompatibility', () => { ["0.2.0", "0.1.0"], // payload had breaking changes during active development ["2.0.0", "1.0.0"], // payload is majorly newer ["1.0.0", "2.0.0"], // action had breaking changes - ])('should reject incompatible payload %#', (payloadVersion, actionVersion) => { - expect(() => validateCompatibility(payloadVersion, actionVersion)).toThrow(/is incompatible with action version/); + ])("should reject incompatible payload %#", (payloadVersion, actionVersion) => { + expect(() => validateCompatibility(payloadVersion, actionVersion)).toThrow( + /is incompatible with action version/ + ); }); }); diff --git a/utils/versioning.ts b/utils/versioning.ts index 5e35f8d..66be406 100644 --- a/utils/versioning.ts +++ b/utils/versioning.ts @@ -1,4 +1,4 @@ -import semver from 'semver'; +import semver from "semver"; type CompatibilityPolicy = /** @@ -6,13 +6,13 @@ type CompatibilityPolicy = * @example Payload version 1.2.3 => ^1.2.0 range of action versions supported * @example Payload version 0.1.55 => ^0.1.55 range of action versions supported */ - | 'same-features' + | "same-features" /** * Loose policy: the action must have no breaking changes compared to the payload version * @example Payload version 1.2.3 => ^1.0.0 range of action versions supported * @example Payload version 0.1.55 => ^0.1.0 range of action versions supported */ - | 'non-breaking'; + | "non-breaking"; const COMPATIBILITY_POLICY: CompatibilityPolicy = "non-breaking"; @@ -24,19 +24,21 @@ const COMPATIBILITY_POLICY: CompatibilityPolicy = "non-breaking"; */ export function validateCompatibility(payloadVersion: string, actionVersion: string): void { const payloadSemVer = semver.parse(payloadVersion); - if (!payloadSemVer) throw new Error(`Payload version ${payloadVersion} is not a valid semantic version.`); + if (!payloadSemVer) + throw new Error(`Payload version ${payloadVersion} is not a valid semantic version.`); const major = payloadSemVer.major; const minor = payloadSemVer.minor; const patch = payloadSemVer.patch; - const compatibilityRange = COMPATIBILITY_POLICY === 'same-features' - ? `^${major}.${minor}.${major === 0 ? patch : 0}` - : `^${major}.${major === 0 ? minor : 0}.${major === 0 ? "x" : 0}`; // non-breaking + const compatibilityRange = + COMPATIBILITY_POLICY === "same-features" + ? `^${major}.${minor}.${major === 0 ? patch : 0}` + : `^${major}.${major === 0 ? minor : 0}.${major === 0 ? "x" : 0}`; // non-breaking if (!semver.satisfies(actionVersion, compatibilityRange)) { throw new Error( `Payload version ${payloadVersion} is incompatible with action version ${actionVersion}. ` + - `Please update your workflow to use at least ${semver.minVersion(compatibilityRange)} version of the action.` + `Please update your workflow to use at least ${semver.minVersion(compatibilityRange)} version of the action.` ); } }