1397 lines
45 KiB
JavaScript
1397 lines
45 KiB
JavaScript
import { minimatch } from 'minimatch';
|
|
import debug from 'debug';
|
|
import { zodToJsonSchema } from 'zod-to-json-schema';
|
|
import { z } from 'zod';
|
|
import { AxiosError } from 'axios';
|
|
import * as jsonc from 'jsonc-parser';
|
|
|
|
function sleep(ms) {
|
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
}
|
|
function hasOwn(obj, prop) {
|
|
return Object.prototype.hasOwnProperty.call(obj, prop);
|
|
}
|
|
function formatSourceValue(value) {
|
|
let result;
|
|
if (value === "true") {
|
|
result = true;
|
|
} else if (value === "false") {
|
|
result = false;
|
|
} else if (/^-?\d*\.?\d+$/.test(value)) {
|
|
result = parseFloat(value);
|
|
} else if (/^-?\d+$/.test(value)) {
|
|
result = parseInt(value, 10);
|
|
} else {
|
|
result = value;
|
|
}
|
|
return result;
|
|
}
|
|
function travelTree(tree, callback) {
|
|
const travel = (tree2, parent) => {
|
|
const result = [];
|
|
tree2.forEach((item) => {
|
|
const callbackResult = callback(item, parent);
|
|
const finalItem = callbackResult === void 0 ? item : callbackResult;
|
|
if (finalItem && item.children)
|
|
finalItem.children = travel(item.children, item);
|
|
if (finalItem !== null)
|
|
result.push(finalItem);
|
|
});
|
|
return result;
|
|
};
|
|
return travel(tree);
|
|
}
|
|
function travelTreeDeepFirst(tree, callback) {
|
|
const travel = (tree2, parent) => {
|
|
const result = [];
|
|
tree2.forEach((item) => {
|
|
let children;
|
|
if (item.children)
|
|
children = travel(item.children, item);
|
|
const callbackResult = callback({ ...item, children }, parent);
|
|
const finalItem = callbackResult === void 0 ? item : callbackResult;
|
|
if (finalItem !== null)
|
|
result.push(finalItem);
|
|
});
|
|
return result;
|
|
};
|
|
return travel(tree);
|
|
}
|
|
function tryParseJson(str, supportJsonc = false) {
|
|
try {
|
|
const target = str?.trim() ?? "";
|
|
return supportJsonc ? jsonc.parse(target) : JSON.parse(target);
|
|
} catch (e) {
|
|
console.error("tryParseJson error: ", str, e);
|
|
return {};
|
|
}
|
|
}
|
|
function tryStringifyJson(obj, ignoreError = false) {
|
|
try {
|
|
return JSON.stringify(obj);
|
|
} catch (e) {
|
|
!ignoreError && console.error("tryStringifyJson error: ", e);
|
|
return "";
|
|
}
|
|
}
|
|
function debounce(callback, wait) {
|
|
let timeout;
|
|
return function(...args) {
|
|
const context = this;
|
|
const later = function() {
|
|
timeout = void 0;
|
|
callback.apply(context, args);
|
|
};
|
|
clearTimeout(timeout);
|
|
timeout = setTimeout(later, wait);
|
|
};
|
|
}
|
|
const keyIsCalledMap = /* @__PURE__ */ new Map();
|
|
function runOnceByKey(callback, key) {
|
|
return function(...args) {
|
|
const context = this;
|
|
const keyIsCalled = keyIsCalledMap.get(key);
|
|
if (keyIsCalled)
|
|
return;
|
|
const result = callback?.apply(context, args);
|
|
if (result instanceof Promise) {
|
|
result?.then?.(() => {
|
|
keyIsCalledMap.set(key, true);
|
|
});
|
|
} else {
|
|
keyIsCalledMap.set(key, true);
|
|
}
|
|
return result;
|
|
};
|
|
}
|
|
function urlRemoveLocalhost(url) {
|
|
if (typeof window === "undefined")
|
|
return url || "";
|
|
if (!url)
|
|
return "";
|
|
try {
|
|
const uri = new URL(url);
|
|
let result = url;
|
|
const currentHostname = window.location.hostname;
|
|
const currentPort = window.location.port;
|
|
if (["localhost", "127.0.0.1"].includes(uri.hostname))
|
|
uri.hostname = currentHostname;
|
|
if (!currentPort || [80, 443].includes(Number(currentPort)))
|
|
uri.port = currentPort;
|
|
uri.protocol = window.location.protocol;
|
|
result = uri.toString();
|
|
if (!url.endsWith("/"))
|
|
result = result.replace(/\/$/, "");
|
|
return result;
|
|
} catch {
|
|
return url;
|
|
}
|
|
}
|
|
function objectToQueryString(obj, prefix) {
|
|
const queryStringArray = [];
|
|
for (const key in obj) {
|
|
if (hasOwn(obj, key)) {
|
|
const value = obj[key];
|
|
const encodedKey = encodeURIComponent(prefix ? `${prefix}[${key}]` : key);
|
|
if (Array.isArray(value)) {
|
|
for (const item of value) {
|
|
queryStringArray.push(
|
|
`${encodedKey}[]=${encodeURIComponent(item)}`
|
|
);
|
|
}
|
|
} else if (typeof value === "object" && value !== null) {
|
|
queryStringArray.push(objectToQueryString(value, encodedKey));
|
|
} else {
|
|
queryStringArray.push(`${encodedKey}=${encodeURIComponent(value)}`);
|
|
}
|
|
}
|
|
}
|
|
return queryStringArray.join("&");
|
|
}
|
|
function toUnixPath(path) {
|
|
if (!path)
|
|
return "";
|
|
return path.replace(/\\+/g, "/");
|
|
}
|
|
function getProcessCwd() {
|
|
try {
|
|
return toUnixPath(process.cwd());
|
|
} catch (e) {
|
|
return void 0;
|
|
}
|
|
}
|
|
function getErrorMsg(error) {
|
|
const errorMessage = String(
|
|
error instanceof AxiosError ? error.response?.data?.message : error?.message || error || ""
|
|
);
|
|
return errorMessage;
|
|
}
|
|
function waitForCondition(conditionFn, timeout = 1e4) {
|
|
return new Promise((resolve, reject) => {
|
|
const startTime = Date.now();
|
|
const interval = setInterval(() => {
|
|
if (conditionFn()) {
|
|
clearInterval(interval);
|
|
resolve();
|
|
} else if (Date.now() - startTime > timeout) {
|
|
clearInterval(interval);
|
|
console.warn("waitForCondition timeout with function", conditionFn.toString());
|
|
reject(new Error("waitForCondition timeout"));
|
|
}
|
|
}, 100);
|
|
});
|
|
}
|
|
function isChineseCharacter(char) {
|
|
const charCode = char.charCodeAt(0);
|
|
return charCode >= 19968 && charCode <= 40959 || charCode >= 13312 && charCode <= 19903 || charCode >= 131072 && charCode <= 173791 || charCode >= 173824 && charCode <= 177983 || charCode >= 177984 && charCode <= 178207 || charCode >= 178208 && charCode <= 183983 || charCode >= 63744 && charCode <= 64255 || charCode >= 194560 && charCode <= 195103;
|
|
}
|
|
|
|
var ChatModelType = /* @__PURE__ */ ((ChatModelType2) => {
|
|
ChatModelType2["Openai"] = "openai";
|
|
ChatModelType2["HuggingFace"] = "huggingFace";
|
|
ChatModelType2["Anthropic"] = "anthropic";
|
|
return ChatModelType2;
|
|
})(ChatModelType || {});
|
|
var ChatRole = /* @__PURE__ */ ((ChatRole2) => {
|
|
ChatRole2["User"] = "user";
|
|
ChatRole2["Assistant"] = "assistant";
|
|
ChatRole2["System"] = "system";
|
|
return ChatRole2;
|
|
})(ChatRole || {});
|
|
var ChatMessageStatus = /* @__PURE__ */ ((ChatMessageStatus2) => {
|
|
ChatMessageStatus2["Pending"] = "pending";
|
|
ChatMessageStatus2["Success"] = "success";
|
|
ChatMessageStatus2["Error"] = "error";
|
|
return ChatMessageStatus2;
|
|
})(ChatMessageStatus || {});
|
|
var ClientEventName = /* @__PURE__ */ ((ClientEventName2) => {
|
|
ClientEventName2["InitSuccess"] = "initSuccess";
|
|
ClientEventName2["RefreshTree"] = "refreshTree";
|
|
ClientEventName2["RefreshChatTree"] = "refreshChatTree";
|
|
ClientEventName2["RefreshFileTree"] = "refreshFileTree";
|
|
ClientEventName2["InsertCodes"] = "insertCodes";
|
|
ClientEventName2["DiffCodes"] = "diffCodes";
|
|
ClientEventName2["UpdateIdeOpeningFiles"] = "updateIdeOpeningFiles";
|
|
ClientEventName2["UpdateIdeActiveFilePath"] = "updateIdeActiveFilePath";
|
|
ClientEventName2["UpdateUserSelectedText"] = "updateUserSelectedText";
|
|
ClientEventName2["OpenFileInIde"] = "openFileInIde";
|
|
ClientEventName2["OpenFileInFileEditor"] = "openFileInFileEditor";
|
|
ClientEventName2["GoToChatPanel"] = "goToChatPanel";
|
|
return ClientEventName2;
|
|
})(ClientEventName || {});
|
|
var GptFileTreeItemType = /* @__PURE__ */ ((GptFileTreeItemType2) => {
|
|
GptFileTreeItemType2["Folder"] = "folder";
|
|
GptFileTreeItemType2["File"] = "file";
|
|
GptFileTreeItemType2["Chat"] = "chat";
|
|
return GptFileTreeItemType2;
|
|
})(GptFileTreeItemType || {});
|
|
var ServerStorageName = /* @__PURE__ */ ((ServerStorageName2) => {
|
|
ServerStorageName2["FrontendState"] = "frontend-state";
|
|
ServerStorageName2["SecretsConfig"] = "secrets-config";
|
|
ServerStorageName2["GlobalState"] = "global-state";
|
|
ServerStorageName2["WebPreset"] = "web-preset";
|
|
return ServerStorageName2;
|
|
})(ServerStorageName || {});
|
|
var WssActionName = /* @__PURE__ */ ((WssActionName2) => {
|
|
WssActionName2["Error"] = "error";
|
|
WssActionName2["StorageGetItem"] = "storageGetItem";
|
|
WssActionName2["StorageSetItem"] = "storageSetItem";
|
|
WssActionName2["StorageRemoveItem"] = "storageRemoveItem";
|
|
WssActionName2["StorageClear"] = "storageClear";
|
|
return WssActionName2;
|
|
})(WssActionName || {});
|
|
var LocaleLang = /* @__PURE__ */ ((LocaleLang2) => {
|
|
LocaleLang2["English"] = "en";
|
|
LocaleLang2["ChineseSimplified"] = "zh_CN";
|
|
LocaleLang2["ChineseTraditional"] = "zh_Hant";
|
|
LocaleLang2["Japanese"] = "ja";
|
|
LocaleLang2["German"] = "de";
|
|
return LocaleLang2;
|
|
})(LocaleLang || {});
|
|
var SecretStorageKey = /* @__PURE__ */ ((SecretStorageKey2) => {
|
|
SecretStorageKey2["Anthropic"] = "anthropic";
|
|
SecretStorageKey2["HuggingFace"] = "huggingFace";
|
|
SecretStorageKey2["Openai"] = "openai";
|
|
SecretStorageKey2["Proxy"] = "proxy";
|
|
return SecretStorageKey2;
|
|
})(SecretStorageKey || {});
|
|
var VendorTag = /* @__PURE__ */ ((VendorTag2) => {
|
|
VendorTag2["Free"] = "free";
|
|
VendorTag2["Official"] = "official";
|
|
VendorTag2["Unofficial"] = "unofficial";
|
|
VendorTag2["Recommended"] = "recommended";
|
|
return VendorTag2;
|
|
})(VendorTag || {});
|
|
|
|
const MIN_NODE_VERSION = "16.15.0";
|
|
const SECRET_KEY_PLACEHOLDER = "********";
|
|
const STREAM_DONE_FLAG = "[DONE]";
|
|
const GPT_RUNNER_OFFICIAL_FOLDER = ".gpt-runner";
|
|
const DEFAULT_API_BASE_PATH = {
|
|
[ChatModelType.Anthropic]: "https://api.anthropic.com",
|
|
[ChatModelType.HuggingFace]: "https://api-inference.huggingface.co",
|
|
[ChatModelType.Openai]: "https://api.openai.com/v1"
|
|
};
|
|
const DEFAULT_MODEL_NAMES_FOR_CHOOSE = {
|
|
[ChatModelType.Anthropic]: [
|
|
"claude-2",
|
|
"claude-instant-1"
|
|
],
|
|
[ChatModelType.HuggingFace]: [],
|
|
[ChatModelType.Openai]: [
|
|
"gpt-3.5-turbo-16k",
|
|
"gpt-4",
|
|
"gpt-4-32k",
|
|
"gpt-3.5-turbo"
|
|
]
|
|
};
|
|
const DEFAULT_EXCLUDE_FILES = [
|
|
"**/node_modules",
|
|
"**/.git",
|
|
"**/__pycache__",
|
|
"**/.Python",
|
|
"**/.DS_Store",
|
|
"**/.cache",
|
|
"**/.next",
|
|
"**/.nuxt",
|
|
"**/.out",
|
|
"**/dist",
|
|
"**/.serverless",
|
|
"**/.parcel-cache"
|
|
];
|
|
const DEFAULT_EXCLUDE_FILE_EXTS = [
|
|
".jpg",
|
|
".png",
|
|
".gif",
|
|
".jpeg",
|
|
".svg",
|
|
".mp4",
|
|
".mp3",
|
|
".wav",
|
|
".flac",
|
|
".ogg",
|
|
".webm",
|
|
".ico",
|
|
".pdf",
|
|
".doc",
|
|
".docx",
|
|
".xls",
|
|
".xlsx",
|
|
".ppt",
|
|
".pptx",
|
|
".zip",
|
|
".rar",
|
|
".7z",
|
|
".tar",
|
|
".gz",
|
|
".tgz",
|
|
".bz2",
|
|
".xz",
|
|
".exe",
|
|
".dmg",
|
|
".pkg",
|
|
".deb",
|
|
".rpm",
|
|
".msi",
|
|
".apk",
|
|
".ipa",
|
|
".iso",
|
|
".img",
|
|
".bin",
|
|
".dll",
|
|
".so",
|
|
".dylib",
|
|
".a",
|
|
".lib",
|
|
".o",
|
|
".obj",
|
|
".class",
|
|
".jar",
|
|
".war",
|
|
".ear",
|
|
".swf",
|
|
".fla",
|
|
".as",
|
|
".as3",
|
|
".mxml",
|
|
".swc",
|
|
".swd",
|
|
".swz",
|
|
".swt",
|
|
".air",
|
|
".ane",
|
|
".ttf",
|
|
".woff",
|
|
".woff2",
|
|
".eot",
|
|
".otf",
|
|
".psd",
|
|
".ai",
|
|
".sketch",
|
|
".fig",
|
|
".xd",
|
|
".blend",
|
|
".fbx",
|
|
".obj",
|
|
".mtl",
|
|
".stl",
|
|
".3ds",
|
|
".dae",
|
|
".max",
|
|
".ma",
|
|
".mb",
|
|
".lwo",
|
|
".lws",
|
|
".lxo",
|
|
".c4d",
|
|
".csv",
|
|
".tsv",
|
|
".pth",
|
|
".pt",
|
|
".h5",
|
|
".hdf5",
|
|
".ckpt",
|
|
".ckpt.index"
|
|
];
|
|
|
|
const config = {
|
|
NODE_ENV: {
|
|
defaultValue: "production"
|
|
},
|
|
OPENAI_API_KEY: {
|
|
serverSideOnly: true
|
|
},
|
|
GPTR_DEFAULT_ROOT_PATH: {
|
|
defaultValue: getProcessCwd()
|
|
},
|
|
GPTR_ONLY_LOAD_CONFIG_PATH: {},
|
|
GPTR_BASE_SERVER_URL: {
|
|
defaultValue: "http://localhost:3003"
|
|
}
|
|
};
|
|
class EnvConfig {
|
|
static get(key) {
|
|
const envVarConfig = config[key];
|
|
if (!envVarConfig)
|
|
return "";
|
|
const { defaultValue, serverSideOnly = false } = envVarConfig;
|
|
if (typeof window !== "undefined" && !serverSideOnly)
|
|
return window?.__env__?.[key] ?? defaultValue ?? "";
|
|
return process.env[key] ?? defaultValue ?? "";
|
|
}
|
|
static getAllEnvVarsOnScopes(type, getWays = "all") {
|
|
const envVars = {};
|
|
for (const _key in config) {
|
|
const key = _key;
|
|
const keyConfig = config[key];
|
|
if (!keyConfig)
|
|
continue;
|
|
const { serverSideOnly } = keyConfig;
|
|
if (serverSideOnly && type === "client")
|
|
continue;
|
|
envVars[key] = getWays === "all" ? EnvConfig.get(key) : process.env[key];
|
|
}
|
|
return envVars;
|
|
}
|
|
static logServerSideEnvVars() {
|
|
const envVars = EnvConfig.getAllEnvVarsOnScopes("server");
|
|
console.log(
|
|
"Server side environment variables:",
|
|
JSON.stringify(envVars, null, 2)
|
|
);
|
|
}
|
|
static logClientSideEnvVars() {
|
|
const envVars = EnvConfig.getAllEnvVarsOnScopes("client");
|
|
console.log(
|
|
"Client side environment variables:",
|
|
JSON.stringify(envVars, null, 2)
|
|
);
|
|
}
|
|
static getClientEnvVarsInServerSide() {
|
|
return EnvConfig.getAllEnvVarsOnScopes("client", "all");
|
|
}
|
|
}
|
|
|
|
function createFilterByPattern(pattern) {
|
|
if (pattern === null || pattern === void 0)
|
|
return () => true;
|
|
if (typeof pattern === "function")
|
|
return pattern;
|
|
if (typeof pattern === "string")
|
|
return (source) => minimatch(source, pattern);
|
|
if (pattern instanceof RegExp)
|
|
return (source) => pattern.test(source);
|
|
if (Array.isArray(pattern)) {
|
|
const matchers = pattern.map((p) => createFilterByPattern(p));
|
|
return (source) => matchers.some((matcher) => matcher(source));
|
|
}
|
|
throw new Error(`Invalid pattern: ${pattern}`);
|
|
}
|
|
|
|
class Debug {
|
|
constructor(label) {
|
|
this.label = `gpt-runner:${label}`;
|
|
if (process.env.DEBUG)
|
|
debug.enable(this.label);
|
|
this.debugger = debug(this.label);
|
|
this.debugger.useColors = true;
|
|
this.debugger.color = String(debug.selectColor(this.label));
|
|
}
|
|
static getInstance(label = "default") {
|
|
if (!Debug.instance)
|
|
Debug.instance = new Debug(label);
|
|
return Debug.instance;
|
|
}
|
|
log(message, ...args) {
|
|
this.debugger(message, ...args);
|
|
}
|
|
warn(message, ...args) {
|
|
this.debugger(`[WARN]: ${message}`, ...args);
|
|
}
|
|
error(message, ...args) {
|
|
this.debugger(`[ERROR]: ${message}`, ...args);
|
|
}
|
|
}
|
|
|
|
function buildSuccessResponse(options) {
|
|
return {
|
|
type: "Success",
|
|
status: options.status || 200,
|
|
...options
|
|
};
|
|
}
|
|
function buildFailResponse(options) {
|
|
return {
|
|
type: "Fail",
|
|
status: options.status || 400,
|
|
...options
|
|
};
|
|
}
|
|
|
|
// Unique ID creation requires a high quality random # generator. In the browser we therefore
|
|
// require the crypto API and do not support built-in fallback to lower quality random number
|
|
// generators (like Math.random()).
|
|
let getRandomValues;
|
|
const rnds8 = new Uint8Array(16);
|
|
function rng() {
|
|
// lazy load so that environments that need to polyfill have a chance to do so
|
|
if (!getRandomValues) {
|
|
// getRandomValues needs to be invoked in a context where "this" is a Crypto implementation.
|
|
getRandomValues = typeof crypto !== 'undefined' && crypto.getRandomValues && crypto.getRandomValues.bind(crypto);
|
|
|
|
if (!getRandomValues) {
|
|
throw new Error('crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported');
|
|
}
|
|
}
|
|
|
|
return getRandomValues(rnds8);
|
|
}
|
|
|
|
const REGEX = /^(?:[0-9a-f]{8}-[0-9a-f]{4}-[1-5][0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}|00000000-0000-0000-0000-000000000000)$/i;
|
|
|
|
function validate(uuid) {
|
|
return typeof uuid === 'string' && REGEX.test(uuid);
|
|
}
|
|
|
|
/**
|
|
* Convert array of 16 byte values to UUID string format of the form:
|
|
* XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX
|
|
*/
|
|
|
|
const byteToHex = [];
|
|
|
|
for (let i = 0; i < 256; ++i) {
|
|
byteToHex.push((i + 0x100).toString(16).slice(1));
|
|
}
|
|
|
|
function unsafeStringify(arr, offset = 0) {
|
|
// Note: Be careful editing this code! It's been tuned for performance
|
|
// and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434
|
|
return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();
|
|
}
|
|
|
|
function parse(uuid) {
|
|
if (!validate(uuid)) {
|
|
throw TypeError('Invalid UUID');
|
|
}
|
|
|
|
let v;
|
|
const arr = new Uint8Array(16); // Parse ########-....-....-....-............
|
|
|
|
arr[0] = (v = parseInt(uuid.slice(0, 8), 16)) >>> 24;
|
|
arr[1] = v >>> 16 & 0xff;
|
|
arr[2] = v >>> 8 & 0xff;
|
|
arr[3] = v & 0xff; // Parse ........-####-....-....-............
|
|
|
|
arr[4] = (v = parseInt(uuid.slice(9, 13), 16)) >>> 8;
|
|
arr[5] = v & 0xff; // Parse ........-....-####-....-............
|
|
|
|
arr[6] = (v = parseInt(uuid.slice(14, 18), 16)) >>> 8;
|
|
arr[7] = v & 0xff; // Parse ........-....-....-####-............
|
|
|
|
arr[8] = (v = parseInt(uuid.slice(19, 23), 16)) >>> 8;
|
|
arr[9] = v & 0xff; // Parse ........-....-....-....-############
|
|
// (Use "/" to avoid 32-bit truncation when bit-shifting high-order bytes)
|
|
|
|
arr[10] = (v = parseInt(uuid.slice(24, 36), 16)) / 0x10000000000 & 0xff;
|
|
arr[11] = v / 0x100000000 & 0xff;
|
|
arr[12] = v >>> 24 & 0xff;
|
|
arr[13] = v >>> 16 & 0xff;
|
|
arr[14] = v >>> 8 & 0xff;
|
|
arr[15] = v & 0xff;
|
|
return arr;
|
|
}
|
|
|
|
function stringToBytes(str) {
|
|
str = unescape(encodeURIComponent(str)); // UTF8 escape
|
|
|
|
const bytes = [];
|
|
|
|
for (let i = 0; i < str.length; ++i) {
|
|
bytes.push(str.charCodeAt(i));
|
|
}
|
|
|
|
return bytes;
|
|
}
|
|
|
|
const DNS = '6ba7b810-9dad-11d1-80b4-00c04fd430c8';
|
|
const URL$1 = '6ba7b811-9dad-11d1-80b4-00c04fd430c8';
|
|
function v35(name, version, hashfunc) {
|
|
function generateUUID(value, namespace, buf, offset) {
|
|
var _namespace;
|
|
|
|
if (typeof value === 'string') {
|
|
value = stringToBytes(value);
|
|
}
|
|
|
|
if (typeof namespace === 'string') {
|
|
namespace = parse(namespace);
|
|
}
|
|
|
|
if (((_namespace = namespace) === null || _namespace === void 0 ? void 0 : _namespace.length) !== 16) {
|
|
throw TypeError('Namespace must be array-like (16 iterable integer values, 0-255)');
|
|
} // Compute hash of namespace and value, Per 4.3
|
|
// Future: Use spread syntax when supported on all platforms, e.g. `bytes =
|
|
// hashfunc([...namespace, ... value])`
|
|
|
|
|
|
let bytes = new Uint8Array(16 + value.length);
|
|
bytes.set(namespace);
|
|
bytes.set(value, namespace.length);
|
|
bytes = hashfunc(bytes);
|
|
bytes[6] = bytes[6] & 0x0f | version;
|
|
bytes[8] = bytes[8] & 0x3f | 0x80;
|
|
|
|
if (buf) {
|
|
offset = offset || 0;
|
|
|
|
for (let i = 0; i < 16; ++i) {
|
|
buf[offset + i] = bytes[i];
|
|
}
|
|
|
|
return buf;
|
|
}
|
|
|
|
return unsafeStringify(bytes);
|
|
} // Function#name is not settable on some platforms (#270)
|
|
|
|
|
|
try {
|
|
generateUUID.name = name; // eslint-disable-next-line no-empty
|
|
} catch (err) {} // For CommonJS default export support
|
|
|
|
|
|
generateUUID.DNS = DNS;
|
|
generateUUID.URL = URL$1;
|
|
return generateUUID;
|
|
}
|
|
|
|
/*
|
|
* Browser-compatible JavaScript MD5
|
|
*
|
|
* Modification of JavaScript MD5
|
|
* https://github.com/blueimp/JavaScript-MD5
|
|
*
|
|
* Copyright 2011, Sebastian Tschan
|
|
* https://blueimp.net
|
|
*
|
|
* Licensed under the MIT license:
|
|
* https://opensource.org/licenses/MIT
|
|
*
|
|
* Based on
|
|
* A JavaScript implementation of the RSA Data Security, Inc. MD5 Message
|
|
* Digest Algorithm, as defined in RFC 1321.
|
|
* Version 2.2 Copyright (C) Paul Johnston 1999 - 2009
|
|
* Other contributors: Greg Holt, Andrew Kepert, Ydnar, Lostinet
|
|
* Distributed under the BSD License
|
|
* See http://pajhome.org.uk/crypt/md5 for more info.
|
|
*/
|
|
function md5(bytes) {
|
|
if (typeof bytes === 'string') {
|
|
const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
|
|
|
|
bytes = new Uint8Array(msg.length);
|
|
|
|
for (let i = 0; i < msg.length; ++i) {
|
|
bytes[i] = msg.charCodeAt(i);
|
|
}
|
|
}
|
|
|
|
return md5ToHexEncodedArray(wordsToMd5(bytesToWords(bytes), bytes.length * 8));
|
|
}
|
|
/*
|
|
* Convert an array of little-endian words to an array of bytes
|
|
*/
|
|
|
|
|
|
function md5ToHexEncodedArray(input) {
|
|
const output = [];
|
|
const length32 = input.length * 32;
|
|
const hexTab = '0123456789abcdef';
|
|
|
|
for (let i = 0; i < length32; i += 8) {
|
|
const x = input[i >> 5] >>> i % 32 & 0xff;
|
|
const hex = parseInt(hexTab.charAt(x >>> 4 & 0x0f) + hexTab.charAt(x & 0x0f), 16);
|
|
output.push(hex);
|
|
}
|
|
|
|
return output;
|
|
}
|
|
/**
|
|
* Calculate output length with padding and bit length
|
|
*/
|
|
|
|
|
|
function getOutputLength(inputLength8) {
|
|
return (inputLength8 + 64 >>> 9 << 4) + 14 + 1;
|
|
}
|
|
/*
|
|
* Calculate the MD5 of an array of little-endian words, and a bit length.
|
|
*/
|
|
|
|
|
|
function wordsToMd5(x, len) {
|
|
/* append padding */
|
|
x[len >> 5] |= 0x80 << len % 32;
|
|
x[getOutputLength(len) - 1] = len;
|
|
let a = 1732584193;
|
|
let b = -271733879;
|
|
let c = -1732584194;
|
|
let d = 271733878;
|
|
|
|
for (let i = 0; i < x.length; i += 16) {
|
|
const olda = a;
|
|
const oldb = b;
|
|
const oldc = c;
|
|
const oldd = d;
|
|
a = md5ff(a, b, c, d, x[i], 7, -680876936);
|
|
d = md5ff(d, a, b, c, x[i + 1], 12, -389564586);
|
|
c = md5ff(c, d, a, b, x[i + 2], 17, 606105819);
|
|
b = md5ff(b, c, d, a, x[i + 3], 22, -1044525330);
|
|
a = md5ff(a, b, c, d, x[i + 4], 7, -176418897);
|
|
d = md5ff(d, a, b, c, x[i + 5], 12, 1200080426);
|
|
c = md5ff(c, d, a, b, x[i + 6], 17, -1473231341);
|
|
b = md5ff(b, c, d, a, x[i + 7], 22, -45705983);
|
|
a = md5ff(a, b, c, d, x[i + 8], 7, 1770035416);
|
|
d = md5ff(d, a, b, c, x[i + 9], 12, -1958414417);
|
|
c = md5ff(c, d, a, b, x[i + 10], 17, -42063);
|
|
b = md5ff(b, c, d, a, x[i + 11], 22, -1990404162);
|
|
a = md5ff(a, b, c, d, x[i + 12], 7, 1804603682);
|
|
d = md5ff(d, a, b, c, x[i + 13], 12, -40341101);
|
|
c = md5ff(c, d, a, b, x[i + 14], 17, -1502002290);
|
|
b = md5ff(b, c, d, a, x[i + 15], 22, 1236535329);
|
|
a = md5gg(a, b, c, d, x[i + 1], 5, -165796510);
|
|
d = md5gg(d, a, b, c, x[i + 6], 9, -1069501632);
|
|
c = md5gg(c, d, a, b, x[i + 11], 14, 643717713);
|
|
b = md5gg(b, c, d, a, x[i], 20, -373897302);
|
|
a = md5gg(a, b, c, d, x[i + 5], 5, -701558691);
|
|
d = md5gg(d, a, b, c, x[i + 10], 9, 38016083);
|
|
c = md5gg(c, d, a, b, x[i + 15], 14, -660478335);
|
|
b = md5gg(b, c, d, a, x[i + 4], 20, -405537848);
|
|
a = md5gg(a, b, c, d, x[i + 9], 5, 568446438);
|
|
d = md5gg(d, a, b, c, x[i + 14], 9, -1019803690);
|
|
c = md5gg(c, d, a, b, x[i + 3], 14, -187363961);
|
|
b = md5gg(b, c, d, a, x[i + 8], 20, 1163531501);
|
|
a = md5gg(a, b, c, d, x[i + 13], 5, -1444681467);
|
|
d = md5gg(d, a, b, c, x[i + 2], 9, -51403784);
|
|
c = md5gg(c, d, a, b, x[i + 7], 14, 1735328473);
|
|
b = md5gg(b, c, d, a, x[i + 12], 20, -1926607734);
|
|
a = md5hh(a, b, c, d, x[i + 5], 4, -378558);
|
|
d = md5hh(d, a, b, c, x[i + 8], 11, -2022574463);
|
|
c = md5hh(c, d, a, b, x[i + 11], 16, 1839030562);
|
|
b = md5hh(b, c, d, a, x[i + 14], 23, -35309556);
|
|
a = md5hh(a, b, c, d, x[i + 1], 4, -1530992060);
|
|
d = md5hh(d, a, b, c, x[i + 4], 11, 1272893353);
|
|
c = md5hh(c, d, a, b, x[i + 7], 16, -155497632);
|
|
b = md5hh(b, c, d, a, x[i + 10], 23, -1094730640);
|
|
a = md5hh(a, b, c, d, x[i + 13], 4, 681279174);
|
|
d = md5hh(d, a, b, c, x[i], 11, -358537222);
|
|
c = md5hh(c, d, a, b, x[i + 3], 16, -722521979);
|
|
b = md5hh(b, c, d, a, x[i + 6], 23, 76029189);
|
|
a = md5hh(a, b, c, d, x[i + 9], 4, -640364487);
|
|
d = md5hh(d, a, b, c, x[i + 12], 11, -421815835);
|
|
c = md5hh(c, d, a, b, x[i + 15], 16, 530742520);
|
|
b = md5hh(b, c, d, a, x[i + 2], 23, -995338651);
|
|
a = md5ii(a, b, c, d, x[i], 6, -198630844);
|
|
d = md5ii(d, a, b, c, x[i + 7], 10, 1126891415);
|
|
c = md5ii(c, d, a, b, x[i + 14], 15, -1416354905);
|
|
b = md5ii(b, c, d, a, x[i + 5], 21, -57434055);
|
|
a = md5ii(a, b, c, d, x[i + 12], 6, 1700485571);
|
|
d = md5ii(d, a, b, c, x[i + 3], 10, -1894986606);
|
|
c = md5ii(c, d, a, b, x[i + 10], 15, -1051523);
|
|
b = md5ii(b, c, d, a, x[i + 1], 21, -2054922799);
|
|
a = md5ii(a, b, c, d, x[i + 8], 6, 1873313359);
|
|
d = md5ii(d, a, b, c, x[i + 15], 10, -30611744);
|
|
c = md5ii(c, d, a, b, x[i + 6], 15, -1560198380);
|
|
b = md5ii(b, c, d, a, x[i + 13], 21, 1309151649);
|
|
a = md5ii(a, b, c, d, x[i + 4], 6, -145523070);
|
|
d = md5ii(d, a, b, c, x[i + 11], 10, -1120210379);
|
|
c = md5ii(c, d, a, b, x[i + 2], 15, 718787259);
|
|
b = md5ii(b, c, d, a, x[i + 9], 21, -343485551);
|
|
a = safeAdd(a, olda);
|
|
b = safeAdd(b, oldb);
|
|
c = safeAdd(c, oldc);
|
|
d = safeAdd(d, oldd);
|
|
}
|
|
|
|
return [a, b, c, d];
|
|
}
|
|
/*
|
|
* Convert an array bytes to an array of little-endian words
|
|
* Characters >255 have their high-byte silently ignored.
|
|
*/
|
|
|
|
|
|
function bytesToWords(input) {
|
|
if (input.length === 0) {
|
|
return [];
|
|
}
|
|
|
|
const length8 = input.length * 8;
|
|
const output = new Uint32Array(getOutputLength(length8));
|
|
|
|
for (let i = 0; i < length8; i += 8) {
|
|
output[i >> 5] |= (input[i / 8] & 0xff) << i % 32;
|
|
}
|
|
|
|
return output;
|
|
}
|
|
/*
|
|
* Add integers, wrapping at 2^32. This uses 16-bit operations internally
|
|
* to work around bugs in some JS interpreters.
|
|
*/
|
|
|
|
|
|
function safeAdd(x, y) {
|
|
const lsw = (x & 0xffff) + (y & 0xffff);
|
|
const msw = (x >> 16) + (y >> 16) + (lsw >> 16);
|
|
return msw << 16 | lsw & 0xffff;
|
|
}
|
|
/*
|
|
* Bitwise rotate a 32-bit number to the left.
|
|
*/
|
|
|
|
|
|
function bitRotateLeft(num, cnt) {
|
|
return num << cnt | num >>> 32 - cnt;
|
|
}
|
|
/*
|
|
* These functions implement the four basic operations the algorithm uses.
|
|
*/
|
|
|
|
|
|
function md5cmn(q, a, b, x, s, t) {
|
|
return safeAdd(bitRotateLeft(safeAdd(safeAdd(a, q), safeAdd(x, t)), s), b);
|
|
}
|
|
|
|
function md5ff(a, b, c, d, x, s, t) {
|
|
return md5cmn(b & c | ~b & d, a, b, x, s, t);
|
|
}
|
|
|
|
function md5gg(a, b, c, d, x, s, t) {
|
|
return md5cmn(b & d | c & ~d, a, b, x, s, t);
|
|
}
|
|
|
|
function md5hh(a, b, c, d, x, s, t) {
|
|
return md5cmn(b ^ c ^ d, a, b, x, s, t);
|
|
}
|
|
|
|
function md5ii(a, b, c, d, x, s, t) {
|
|
return md5cmn(c ^ (b | ~d), a, b, x, s, t);
|
|
}
|
|
|
|
v35('v3', 0x30, md5);
|
|
|
|
const randomUUID = typeof crypto !== 'undefined' && crypto.randomUUID && crypto.randomUUID.bind(crypto);
|
|
const native = {
|
|
randomUUID
|
|
};
|
|
|
|
function v4(options, buf, offset) {
|
|
if (native.randomUUID && !buf && !options) {
|
|
return native.randomUUID();
|
|
}
|
|
|
|
options = options || {};
|
|
const rnds = options.random || (options.rng || rng)(); // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`
|
|
|
|
rnds[6] = rnds[6] & 0x0f | 0x40;
|
|
rnds[8] = rnds[8] & 0x3f | 0x80; // Copy bytes to buffer, if provided
|
|
|
|
if (buf) {
|
|
offset = offset || 0;
|
|
|
|
for (let i = 0; i < 16; ++i) {
|
|
buf[offset + i] = rnds[i];
|
|
}
|
|
|
|
return buf;
|
|
}
|
|
|
|
return unsafeStringify(rnds);
|
|
}
|
|
|
|
// Adapted from Chris Veness' SHA1 code at
|
|
// http://www.movable-type.co.uk/scripts/sha1.html
|
|
function f(s, x, y, z) {
|
|
switch (s) {
|
|
case 0:
|
|
return x & y ^ ~x & z;
|
|
|
|
case 1:
|
|
return x ^ y ^ z;
|
|
|
|
case 2:
|
|
return x & y ^ x & z ^ y & z;
|
|
|
|
case 3:
|
|
return x ^ y ^ z;
|
|
}
|
|
}
|
|
|
|
function ROTL(x, n) {
|
|
return x << n | x >>> 32 - n;
|
|
}
|
|
|
|
function sha1(bytes) {
|
|
const K = [0x5a827999, 0x6ed9eba1, 0x8f1bbcdc, 0xca62c1d6];
|
|
const H = [0x67452301, 0xefcdab89, 0x98badcfe, 0x10325476, 0xc3d2e1f0];
|
|
|
|
if (typeof bytes === 'string') {
|
|
const msg = unescape(encodeURIComponent(bytes)); // UTF8 escape
|
|
|
|
bytes = [];
|
|
|
|
for (let i = 0; i < msg.length; ++i) {
|
|
bytes.push(msg.charCodeAt(i));
|
|
}
|
|
} else if (!Array.isArray(bytes)) {
|
|
// Convert Array-like to Array
|
|
bytes = Array.prototype.slice.call(bytes);
|
|
}
|
|
|
|
bytes.push(0x80);
|
|
const l = bytes.length / 4 + 2;
|
|
const N = Math.ceil(l / 16);
|
|
const M = new Array(N);
|
|
|
|
for (let i = 0; i < N; ++i) {
|
|
const arr = new Uint32Array(16);
|
|
|
|
for (let j = 0; j < 16; ++j) {
|
|
arr[j] = bytes[i * 64 + j * 4] << 24 | bytes[i * 64 + j * 4 + 1] << 16 | bytes[i * 64 + j * 4 + 2] << 8 | bytes[i * 64 + j * 4 + 3];
|
|
}
|
|
|
|
M[i] = arr;
|
|
}
|
|
|
|
M[N - 1][14] = (bytes.length - 1) * 8 / Math.pow(2, 32);
|
|
M[N - 1][14] = Math.floor(M[N - 1][14]);
|
|
M[N - 1][15] = (bytes.length - 1) * 8 & 0xffffffff;
|
|
|
|
for (let i = 0; i < N; ++i) {
|
|
const W = new Uint32Array(80);
|
|
|
|
for (let t = 0; t < 16; ++t) {
|
|
W[t] = M[i][t];
|
|
}
|
|
|
|
for (let t = 16; t < 80; ++t) {
|
|
W[t] = ROTL(W[t - 3] ^ W[t - 8] ^ W[t - 14] ^ W[t - 16], 1);
|
|
}
|
|
|
|
let a = H[0];
|
|
let b = H[1];
|
|
let c = H[2];
|
|
let d = H[3];
|
|
let e = H[4];
|
|
|
|
for (let t = 0; t < 80; ++t) {
|
|
const s = Math.floor(t / 20);
|
|
const T = ROTL(a, 5) + f(s, b, c, d) + e + K[s] + W[t] >>> 0;
|
|
e = d;
|
|
d = c;
|
|
c = ROTL(b, 30) >>> 0;
|
|
b = a;
|
|
a = T;
|
|
}
|
|
|
|
H[0] = H[0] + a >>> 0;
|
|
H[1] = H[1] + b >>> 0;
|
|
H[2] = H[2] + c >>> 0;
|
|
H[3] = H[3] + d >>> 0;
|
|
H[4] = H[4] + e >>> 0;
|
|
}
|
|
|
|
return [H[0] >> 24 & 0xff, H[0] >> 16 & 0xff, H[0] >> 8 & 0xff, H[0] & 0xff, H[1] >> 24 & 0xff, H[1] >> 16 & 0xff, H[1] >> 8 & 0xff, H[1] & 0xff, H[2] >> 24 & 0xff, H[2] >> 16 & 0xff, H[2] >> 8 & 0xff, H[2] & 0xff, H[3] >> 24 & 0xff, H[3] >> 16 & 0xff, H[3] >> 8 & 0xff, H[3] & 0xff, H[4] >> 24 & 0xff, H[4] >> 16 & 0xff, H[4] >> 8 & 0xff, H[4] & 0xff];
|
|
}
|
|
|
|
v35('v5', 0x50, sha1);
|
|
|
|
var __accessCheck = (obj, member, msg) => {
|
|
if (!member.has(obj))
|
|
throw TypeError("Cannot " + msg);
|
|
};
|
|
var __privateGet = (obj, member, getter) => {
|
|
__accessCheck(obj, member, "read from private field");
|
|
return getter ? getter.call(obj) : member.get(obj);
|
|
};
|
|
var __privateAdd = (obj, member, value) => {
|
|
if (member.has(obj))
|
|
throw TypeError("Cannot add the same private member more than once");
|
|
member instanceof WeakSet ? member.add(obj) : member.set(obj, value);
|
|
};
|
|
var __privateSet = (obj, member, value, setter) => {
|
|
__accessCheck(obj, member, "write to private field");
|
|
setter ? setter.call(obj, value) : member.set(obj, value);
|
|
return value;
|
|
};
|
|
var _wssUrl, _socketQueue, _hasConnected, _wss, _setWss, _connectNodeSocket, _connectBrowserSocket, _handleConnection;
|
|
const _WssUtils = class {
|
|
constructor(wssUrl) {
|
|
__privateAdd(this, _wssUrl, void 0);
|
|
__privateAdd(this, _socketQueue, []);
|
|
__privateAdd(this, _hasConnected, false);
|
|
__privateAdd(this, _wss, void 0);
|
|
__privateAdd(this, _setWss, (socket) => {
|
|
__privateSet(this, _wss, socket);
|
|
__privateGet(this, _socketQueue).forEach((fn) => fn(socket));
|
|
__privateSet(this, _socketQueue, []);
|
|
});
|
|
this.connect = async (params) => {
|
|
if (this.wss || __privateGet(this, _hasConnected))
|
|
return this.wss;
|
|
console.log("Connecting to WS...");
|
|
const { server } = params || {};
|
|
try {
|
|
if (_WssUtils.isBrowser)
|
|
await __privateGet(this, _connectBrowserSocket).call(this);
|
|
else
|
|
server && await __privateGet(this, _connectNodeSocket).call(this, server);
|
|
__privateSet(this, _hasConnected, true);
|
|
return this.wss;
|
|
} catch (error) {
|
|
console.error("Error connecting to WS", error);
|
|
throw error;
|
|
}
|
|
};
|
|
__privateAdd(this, _connectNodeSocket, async (server) => {
|
|
if (_WssUtils.isBrowser || this.wss)
|
|
return;
|
|
const { Server } = await import('socket.io');
|
|
const serverSocket = new Server(server, {
|
|
cors: {
|
|
origin: "*"
|
|
}
|
|
});
|
|
serverSocket.on("connection", (socket) => {
|
|
__privateGet(this, _setWss).call(this, socket);
|
|
__privateGet(this, _handleConnection).call(this);
|
|
});
|
|
});
|
|
__privateAdd(this, _connectBrowserSocket, async () => {
|
|
if (!_WssUtils.isBrowser || this.wss)
|
|
return;
|
|
const { io } = await import('socket.io-client');
|
|
const socket = io(this.wsUrl);
|
|
__privateGet(this, _setWss).call(this, socket);
|
|
});
|
|
__privateAdd(this, _handleConnection, async () => {
|
|
console.log("Connected to Socket server");
|
|
});
|
|
this.on = (eventName, callback) => {
|
|
if (!this.wss) {
|
|
__privateGet(this, _socketQueue).push((socket) => {
|
|
socket.on(eventName, callback);
|
|
});
|
|
return;
|
|
}
|
|
this.wss.on(eventName, callback);
|
|
};
|
|
this.emit = (eventName, message) => {
|
|
if (!this.wss) {
|
|
__privateGet(this, _socketQueue).push((socket) => {
|
|
socket.emit(eventName, message);
|
|
});
|
|
return;
|
|
}
|
|
this.wss.emit(eventName, message);
|
|
};
|
|
this.off = (eventName, callback) => {
|
|
if (!this.wss) {
|
|
__privateGet(this, _socketQueue).push((socket) => {
|
|
socket.off(eventName, callback);
|
|
});
|
|
return;
|
|
}
|
|
this.wss.off(eventName, callback);
|
|
};
|
|
this.emitAndWaitForRes = async (eventName, message) => {
|
|
return new Promise((resolve, reject) => {
|
|
let destroyFn;
|
|
const timeout = setTimeout(() => {
|
|
destroyFn?.();
|
|
reject(new Error(`WS timeout, actionName: ${eventName}`));
|
|
}, 1e4);
|
|
const __id__ = v4();
|
|
this.emit(eventName, { ...message, __id__ });
|
|
const handler = (message2) => {
|
|
if (message2.__id__ !== __id__)
|
|
return;
|
|
destroyFn?.();
|
|
resolve(message2);
|
|
};
|
|
this.on(eventName, handler);
|
|
destroyFn = () => {
|
|
clearTimeout(timeout);
|
|
this.off(eventName, handler);
|
|
};
|
|
});
|
|
};
|
|
__privateSet(this, _wssUrl, urlRemoveLocalhost(wssUrl ?? _WssUtils.defaultWssUrl));
|
|
}
|
|
static get instance() {
|
|
if (!this._instance)
|
|
this._instance = new _WssUtils();
|
|
return this._instance;
|
|
}
|
|
static get isBrowser() {
|
|
return typeof window !== "undefined";
|
|
}
|
|
static isNodeServerSocket(socket) {
|
|
return typeof window === "undefined" && Boolean(socket);
|
|
}
|
|
static isBrowserSocket(socket) {
|
|
return _WssUtils.isBrowser && Boolean(socket);
|
|
}
|
|
get wsUrl() {
|
|
return __privateGet(this, _wssUrl);
|
|
}
|
|
get wss() {
|
|
return __privateGet(this, _wss);
|
|
}
|
|
};
|
|
let WssUtils = _WssUtils;
|
|
_wssUrl = new WeakMap();
|
|
_socketQueue = new WeakMap();
|
|
_hasConnected = new WeakMap();
|
|
_wss = new WeakMap();
|
|
_setWss = new WeakMap();
|
|
_connectNodeSocket = new WeakMap();
|
|
_connectBrowserSocket = new WeakMap();
|
|
_handleConnection = new WeakMap();
|
|
WssUtils.defaultWssUrl = `http://${new URL(EnvConfig.get("GPTR_BASE_SERVER_URL")).host}`;
|
|
|
|
function verifyZod(schema, value) {
|
|
const result = schema.safeParse(value);
|
|
if (!result.success) {
|
|
const errorTextArr = [];
|
|
result.error.issues.forEach((issue) => {
|
|
const { path: fields } = issue;
|
|
return fields.forEach((field) => {
|
|
const prefix = errorTextArr.length === 0 ? "Error: " : ".\n";
|
|
const errorText = `${prefix}${field} field is ${issue.message?.toLowerCase()}`;
|
|
errorTextArr.push(errorText);
|
|
});
|
|
});
|
|
throw new Error(errorTextArr.join("\n"));
|
|
}
|
|
return result.data;
|
|
}
|
|
|
|
const ChatModelTypeSchema = z.nativeEnum(ChatModelType);
|
|
const ChatRoleSchema = z.nativeEnum(ChatRole);
|
|
const ChatMessageStatusSchema = z.nativeEnum(ChatMessageStatus);
|
|
const ClientEventNameSchema = z.nativeEnum(ClientEventName);
|
|
const GptFileTreeItemTypeSchema = z.nativeEnum(GptFileTreeItemType);
|
|
const ServerStorageNameSchema = z.nativeEnum(ServerStorageName);
|
|
const LocaleLangSchema = z.nativeEnum(LocaleLang);
|
|
|
|
const BaseSecretsSchema = z.object({
|
|
basePath: z.string().optional().describe("The base API url")
|
|
});
|
|
const BaseModelConfigSchema = z.object({
|
|
type: ChatModelTypeSchema.optional().describe("The type of the model"),
|
|
modelName: z.string().optional().describe("The name of the model"),
|
|
secrets: z.any().optional().describe("The API secrets config")
|
|
});
|
|
|
|
const AnthropicSecretsSchema = BaseSecretsSchema.extend({
|
|
apiKey: z.string().optional().describe("The Anthropic API key"),
|
|
basePath: z.string().optional().default(DEFAULT_API_BASE_PATH[ChatModelType.Anthropic]).describe("The Anthropic base API url")
|
|
});
|
|
const AnthropicModelConfigSchema = BaseModelConfigSchema.extend({
|
|
type: z.literal(ChatModelType.Anthropic).describe("Use Anthropic model"),
|
|
secrets: AnthropicSecretsSchema.optional().describe("The Anthropic API secrets config"),
|
|
temperature: z.number().optional().describe("The temperature for the Anthropic model"),
|
|
maxTokens: z.number().optional().describe("The maximum number of tokens for the Anthropic model"),
|
|
topP: z.number().optional().describe("The top P value for the Anthropic model"),
|
|
topK: z.number().optional().describe("The top K value for the Anthropic model")
|
|
});
|
|
|
|
const HuggingFaceSecretsSchema = BaseSecretsSchema.extend({
|
|
apiKey: z.string().optional().describe("The HuggingFace API key")
|
|
});
|
|
const HuggingFaceModelConfigSchema = BaseModelConfigSchema.extend({
|
|
type: z.literal(ChatModelType.HuggingFace).describe("Use Open AI model"),
|
|
secrets: HuggingFaceSecretsSchema.optional().describe("The HuggingFace API secrets config"),
|
|
temperature: z.number().optional().describe("The temperature for the HuggingFace model"),
|
|
maxTokens: z.number().optional().describe("The maximum number of tokens for the HuggingFace model"),
|
|
topP: z.number().optional().describe("The top P value for the HuggingFace model"),
|
|
topK: z.number().optional().describe("The top K value for the HuggingFace model"),
|
|
frequencyPenalty: z.number().optional().describe("The frequency penalty for the HuggingFace model")
|
|
});
|
|
|
|
const OpenaiSecretsSchema = BaseSecretsSchema.extend({
|
|
apiKey: z.string().optional().describe("The OpenAI API key"),
|
|
organization: z.string().optional().describe("The OpenAI organization"),
|
|
accessToken: z.string().optional().describe("The OpenAI access token"),
|
|
basePath: z.string().optional().default(DEFAULT_API_BASE_PATH[ChatModelType.Openai]).describe("The OpenAI base API path")
|
|
});
|
|
const OpenaiModelConfigSchema = BaseModelConfigSchema.extend({
|
|
type: z.literal(ChatModelType.Openai).describe("Use OpenAI model"),
|
|
secrets: OpenaiSecretsSchema.optional().describe("The OpenAI API secrets config"),
|
|
temperature: z.number().optional().describe("The temperature for the OpenAI model"),
|
|
maxTokens: z.number().optional().describe("The maximum number of tokens for the OpenAI model"),
|
|
topP: z.number().optional().describe("The top P value for the OpenAI model"),
|
|
frequencyPenalty: z.number().optional().describe("The frequency penalty for the OpenAI model"),
|
|
presencePenalty: z.number().optional().describe("The presence penalty for the OpenAI model")
|
|
});
|
|
|
|
const FilterPatternSchema = z.union([
|
|
z.array(z.union([z.string(), z.instanceof(RegExp)])),
|
|
z.string(),
|
|
z.instanceof(RegExp),
|
|
z.function(z.tuple([z.string()]), z.boolean()).optional(),
|
|
z.null(),
|
|
z.undefined()
|
|
]);
|
|
const ChatModelSchema = z.union([
|
|
AnthropicModelConfigSchema,
|
|
HuggingFaceModelConfigSchema,
|
|
OpenaiModelConfigSchema
|
|
]);
|
|
const PartialChatModelTypeMapSchema = z.object({
|
|
[ChatModelType.Anthropic]: AnthropicModelConfigSchema.optional(),
|
|
[ChatModelType.HuggingFace]: HuggingFaceModelConfigSchema.optional(),
|
|
[ChatModelType.Openai]: OpenaiModelConfigSchema.optional()
|
|
});
|
|
const UserConfigSchema = z.object({
|
|
model: ChatModelSchema.optional().describe("The LLM model configuration"),
|
|
rootPath: z.string().optional().describe("The root path of the project"),
|
|
exts: z.array(z.string()).optional().default([".gpt.md"]).describe("The file extensions to be used"),
|
|
includes: FilterPatternSchema.optional().default(null).describe("The include patterns for filtering files"),
|
|
excludes: FilterPatternSchema.optional().default(null).describe("The exclude patterns for filtering files"),
|
|
respectGitIgnore: z.boolean().optional().default(true).describe("Whether to respect .gitignore rules"),
|
|
urlConfig: z.record(z.object({
|
|
modelNames: z.array(z.string()).optional().describe("The model name that will be displayed in the model selector"),
|
|
httpRequestHeader: z.record(z.string()).optional().describe("Additional request headers are required")
|
|
})).optional().default({}).describe("Custom http request headers and models names for specific urls")
|
|
});
|
|
const UserConfigForUserSchema = UserConfigSchema.omit({
|
|
rootPath: true,
|
|
exts: true
|
|
});
|
|
const SingleChatMessageSchema = z.object({
|
|
name: ChatRoleSchema,
|
|
text: z.string()
|
|
});
|
|
const FormOptionSchema = z.object({
|
|
label: z.string().optional(),
|
|
value: z.string()
|
|
});
|
|
const FormFieldBaseConfigSchema = z.object({
|
|
type: z.string(),
|
|
defaultValue: z.any().optional(),
|
|
description: z.string().optional()
|
|
});
|
|
const FormInputConfigSchema = FormFieldBaseConfigSchema.extend({
|
|
type: z.literal("input")
|
|
});
|
|
const FormTextareaConfigSchema = FormFieldBaseConfigSchema.extend({
|
|
type: z.literal("textarea"),
|
|
row: z.number().optional()
|
|
});
|
|
const FormSelectConfigSchema = FormFieldBaseConfigSchema.extend({
|
|
type: z.literal("select"),
|
|
options: z.array(FormOptionSchema)
|
|
});
|
|
const FormCheckboxGroupConfigSchema = FormFieldBaseConfigSchema.extend({
|
|
type: z.literal("checkbox-group"),
|
|
options: z.array(FormOptionSchema)
|
|
}).refine((config) => Array.isArray(config.defaultValue), {
|
|
message: "defaultValue must be an array of strings for checkbox-group",
|
|
path: ["defaultValue"]
|
|
});
|
|
const FormRadioGroupConfigSchema = FormFieldBaseConfigSchema.extend({
|
|
type: z.literal("radio-group"),
|
|
options: z.array(FormOptionSchema)
|
|
});
|
|
const FormItemConfigSchema = z.union([
|
|
FormInputConfigSchema,
|
|
FormTextareaConfigSchema,
|
|
FormSelectConfigSchema,
|
|
FormCheckboxGroupConfigSchema,
|
|
FormRadioGroupConfigSchema
|
|
]);
|
|
const SingleFileConfigSchema = z.object({
|
|
model: UserConfigSchema.shape.model,
|
|
title: z.string().optional(),
|
|
userPrompt: z.string().optional(),
|
|
systemPrompt: z.string().optional(),
|
|
messages: z.array(SingleChatMessageSchema).optional(),
|
|
forms: z.record(FormItemConfigSchema).optional()
|
|
});
|
|
|
|
const ChatStreamReqParamsSchema = z.object({
|
|
messages: z.array(SingleChatMessageSchema),
|
|
prompt: z.string(),
|
|
systemPrompt: z.string().optional(),
|
|
appendSystemPrompt: z.string().optional(),
|
|
systemPromptAsUserPrompt: z.boolean().optional(),
|
|
singleFilePath: z.string().optional(),
|
|
singleFileConfig: SingleFileConfigSchema.optional(),
|
|
overrideModelType: ChatModelTypeSchema.optional(),
|
|
overrideModelsConfig: PartialChatModelTypeMapSchema.optional(),
|
|
modelTypeVendorNameMap: z.record(z.string()).optional(),
|
|
contextFilePaths: z.array(z.string()).optional(),
|
|
editingFilePath: z.string().optional(),
|
|
rootPath: z.string().optional()
|
|
});
|
|
const GetModelNamesForChooseReqParamsSchema = z.object({
|
|
rootPath: z.string(),
|
|
modelType: ChatModelTypeSchema,
|
|
modelTypeVendorNameMap: z.record(z.string()).optional()
|
|
});
|
|
const GetGptFilesReqParamsSchema = z.object({
|
|
rootPath: z.string()
|
|
});
|
|
const GetGptFileInfoReqParamsSchema = z.object({
|
|
rootPath: z.string(),
|
|
filePath: z.string()
|
|
});
|
|
const InitGptFilesReqParamsSchema = z.object({
|
|
rootPath: z.string(),
|
|
gptFilesNames: z.array(z.string())
|
|
});
|
|
const GetUserConfigReqParamsSchema = z.object({
|
|
rootPath: z.string()
|
|
});
|
|
const StorageGetItemReqParamsSchema = z.object({
|
|
storageName: ServerStorageNameSchema,
|
|
key: z.string()
|
|
});
|
|
const StorageSetItemReqParamsSchema = z.object({
|
|
storageName: ServerStorageNameSchema,
|
|
key: z.string(),
|
|
value: z.record(z.any()).nullable().optional()
|
|
});
|
|
const StorageRemoveItemReqParamsSchema = z.object({
|
|
storageName: ServerStorageNameSchema,
|
|
key: z.string()
|
|
});
|
|
const StorageClearReqParamsSchema = z.object({
|
|
storageName: ServerStorageNameSchema
|
|
});
|
|
const GetCommonFilesReqParamsSchema = z.object({
|
|
rootPath: z.string(),
|
|
excludeExts: z.array(z.string()).optional()
|
|
});
|
|
const OpenEditorReqParamsSchema = z.object({
|
|
rootPath: z.string().optional(),
|
|
path: z.string(),
|
|
matchContent: z.string().optional()
|
|
});
|
|
const CreateFilePathReqParamsSchema = z.object({
|
|
fileFullPath: z.string(),
|
|
isDir: z.boolean()
|
|
});
|
|
const RenameFilePathReqParamsSchema = z.object({
|
|
oldFileFullPath: z.string(),
|
|
newFileFullPath: z.string()
|
|
});
|
|
const DeleteFilePathReqParamsSchema = z.object({
|
|
fileFullPath: z.string()
|
|
});
|
|
const GetFileInfoReqParamsSchema = z.object({
|
|
fileFullPath: z.string()
|
|
});
|
|
const SaveFileContentReqParamsSchema = z.object({
|
|
fileFullPath: z.string(),
|
|
content: z.string()
|
|
});
|
|
const GetAppConfigReqParamsSchema = z.object({
|
|
langId: LocaleLangSchema.optional()
|
|
});
|
|
const MarkAsVisitedAppConfigReqParamsSchema = z.object({
|
|
types: z.array(z.union([
|
|
z.literal("notificationDate"),
|
|
z.literal("releaseDate")
|
|
]))
|
|
});
|
|
|
|
const userConfigJsonSchema = zodToJsonSchema(UserConfigForUserSchema);
|
|
const singleFileJsonSchema = zodToJsonSchema(SingleFileConfigSchema);
|
|
|
|
export { PartialChatModelTypeMapSchema as $, AnthropicModelConfigSchema as A, buildFailResponse as B, ChatModelType as C, DEFAULT_EXCLUDE_FILES as D, EnvConfig as E, verifyZod as F, GPT_RUNNER_OFFICIAL_FOLDER as G, HuggingFaceModelConfigSchema as H, userConfigJsonSchema as I, singleFileJsonSchema as J, ChatRole as K, ChatMessageStatus as L, MIN_NODE_VERSION as M, ClientEventName as N, OpenaiModelConfigSchema as O, GptFileTreeItemType as P, ServerStorageName as Q, WssActionName as R, SECRET_KEY_PLACEHOLDER as S, LocaleLang as T, SecretStorageKey as U, VendorTag as V, WssUtils as W, BaseSecretsSchema as X, BaseModelConfigSchema as Y, FilterPatternSchema as Z, ChatModelSchema as _, AnthropicSecretsSchema as a, UserConfigSchema as a0, UserConfigForUserSchema as a1, SingleChatMessageSchema as a2, FormOptionSchema as a3, FormFieldBaseConfigSchema as a4, FormInputConfigSchema as a5, FormTextareaConfigSchema as a6, FormSelectConfigSchema as a7, FormCheckboxGroupConfigSchema as a8, FormRadioGroupConfigSchema as a9, GetAppConfigReqParamsSchema as aA, MarkAsVisitedAppConfigReqParamsSchema as aB, FormItemConfigSchema as aa, SingleFileConfigSchema as ab, ChatModelTypeSchema as ac, ChatRoleSchema as ad, ChatMessageStatusSchema as ae, ClientEventNameSchema as af, GptFileTreeItemTypeSchema as ag, ServerStorageNameSchema as ah, LocaleLangSchema as ai, ChatStreamReqParamsSchema as aj, GetModelNamesForChooseReqParamsSchema as ak, GetGptFilesReqParamsSchema as al, GetGptFileInfoReqParamsSchema as am, InitGptFilesReqParamsSchema as an, GetUserConfigReqParamsSchema as ao, StorageGetItemReqParamsSchema as ap, StorageSetItemReqParamsSchema as aq, StorageRemoveItemReqParamsSchema as ar, StorageClearReqParamsSchema as as, GetCommonFilesReqParamsSchema as at, OpenEditorReqParamsSchema as au, CreateFilePathReqParamsSchema as av, RenameFilePathReqParamsSchema as aw, DeleteFilePathReqParamsSchema as ax, GetFileInfoReqParamsSchema as ay, SaveFileContentReqParamsSchema as az, HuggingFaceSecretsSchema as b, OpenaiSecretsSchema as c, travelTreeDeepFirst as d, tryParseJson as e, formatSourceValue as f, getProcessCwd as g, hasOwn as h, tryStringifyJson as i, debounce as j, toUnixPath as k, getErrorMsg as l, isChineseCharacter as m, STREAM_DONE_FLAG as n, objectToQueryString as o, DEFAULT_API_BASE_PATH as p, DEFAULT_MODEL_NAMES_FOR_CHOOSE as q, runOnceByKey as r, sleep as s, travelTree as t, urlRemoveLocalhost as u, DEFAULT_EXCLUDE_FILE_EXTS as v, waitForCondition as w, createFilterByPattern as x, Debug as y, buildSuccessResponse as z };
|