1507 lines
49 KiB
JavaScript
1507 lines
49 KiB
JavaScript
'use strict';
|
|
|
|
const minimatch = require('minimatch');
|
|
const debug = require('debug');
|
|
const zodToJsonSchema = require('zod-to-json-schema');
|
|
const zod = require('zod');
|
|
const axios = require('axios');
|
|
const jsonc = require('jsonc-parser');
|
|
|
|
function _interopDefaultLegacy (e) { return e && typeof e === 'object' && 'default' in e ? e["default"] : e; }
|
|
|
|
function _interopNamespace(e) {
|
|
if (e && e.__esModule) return e;
|
|
const n = Object.create(null);
|
|
if (e) {
|
|
for (const k in e) {
|
|
n[k] = e[k];
|
|
}
|
|
}
|
|
n["default"] = e;
|
|
return n;
|
|
}
|
|
|
|
const debug__default = /*#__PURE__*/_interopDefaultLegacy(debug);
|
|
const jsonc__namespace = /*#__PURE__*/_interopNamespace(jsonc);
|
|
|
|
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__namespace.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 axios.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.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__default.enable(this.label);
|
|
this.debugger = debug__default(this.label);
|
|
this.debugger.useColors = true;
|
|
this.debugger.color = String(debug__default.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 = zod.z.nativeEnum(ChatModelType);
|
|
const ChatRoleSchema = zod.z.nativeEnum(ChatRole);
|
|
const ChatMessageStatusSchema = zod.z.nativeEnum(ChatMessageStatus);
|
|
const ClientEventNameSchema = zod.z.nativeEnum(ClientEventName);
|
|
const GptFileTreeItemTypeSchema = zod.z.nativeEnum(GptFileTreeItemType);
|
|
const ServerStorageNameSchema = zod.z.nativeEnum(ServerStorageName);
|
|
const LocaleLangSchema = zod.z.nativeEnum(LocaleLang);
|
|
|
|
const BaseSecretsSchema = zod.z.object({
|
|
basePath: zod.z.string().optional().describe("The base API url")
|
|
});
|
|
const BaseModelConfigSchema = zod.z.object({
|
|
type: ChatModelTypeSchema.optional().describe("The type of the model"),
|
|
modelName: zod.z.string().optional().describe("The name of the model"),
|
|
secrets: zod.z.any().optional().describe("The API secrets config")
|
|
});
|
|
|
|
const AnthropicSecretsSchema = BaseSecretsSchema.extend({
|
|
apiKey: zod.z.string().optional().describe("The Anthropic API key"),
|
|
basePath: zod.z.string().optional().default(DEFAULT_API_BASE_PATH[ChatModelType.Anthropic]).describe("The Anthropic base API url")
|
|
});
|
|
const AnthropicModelConfigSchema = BaseModelConfigSchema.extend({
|
|
type: zod.z.literal(ChatModelType.Anthropic).describe("Use Anthropic model"),
|
|
secrets: AnthropicSecretsSchema.optional().describe("The Anthropic API secrets config"),
|
|
temperature: zod.z.number().optional().describe("The temperature for the Anthropic model"),
|
|
maxTokens: zod.z.number().optional().describe("The maximum number of tokens for the Anthropic model"),
|
|
topP: zod.z.number().optional().describe("The top P value for the Anthropic model"),
|
|
topK: zod.z.number().optional().describe("The top K value for the Anthropic model")
|
|
});
|
|
|
|
const HuggingFaceSecretsSchema = BaseSecretsSchema.extend({
|
|
apiKey: zod.z.string().optional().describe("The HuggingFace API key")
|
|
});
|
|
const HuggingFaceModelConfigSchema = BaseModelConfigSchema.extend({
|
|
type: zod.z.literal(ChatModelType.HuggingFace).describe("Use Open AI model"),
|
|
secrets: HuggingFaceSecretsSchema.optional().describe("The HuggingFace API secrets config"),
|
|
temperature: zod.z.number().optional().describe("The temperature for the HuggingFace model"),
|
|
maxTokens: zod.z.number().optional().describe("The maximum number of tokens for the HuggingFace model"),
|
|
topP: zod.z.number().optional().describe("The top P value for the HuggingFace model"),
|
|
topK: zod.z.number().optional().describe("The top K value for the HuggingFace model"),
|
|
frequencyPenalty: zod.z.number().optional().describe("The frequency penalty for the HuggingFace model")
|
|
});
|
|
|
|
const OpenaiSecretsSchema = BaseSecretsSchema.extend({
|
|
apiKey: zod.z.string().optional().describe("The OpenAI API key"),
|
|
organization: zod.z.string().optional().describe("The OpenAI organization"),
|
|
accessToken: zod.z.string().optional().describe("The OpenAI access token"),
|
|
basePath: zod.z.string().optional().default(DEFAULT_API_BASE_PATH[ChatModelType.Openai]).describe("The OpenAI base API path")
|
|
});
|
|
const OpenaiModelConfigSchema = BaseModelConfigSchema.extend({
|
|
type: zod.z.literal(ChatModelType.Openai).describe("Use OpenAI model"),
|
|
secrets: OpenaiSecretsSchema.optional().describe("The OpenAI API secrets config"),
|
|
temperature: zod.z.number().optional().describe("The temperature for the OpenAI model"),
|
|
maxTokens: zod.z.number().optional().describe("The maximum number of tokens for the OpenAI model"),
|
|
topP: zod.z.number().optional().describe("The top P value for the OpenAI model"),
|
|
frequencyPenalty: zod.z.number().optional().describe("The frequency penalty for the OpenAI model"),
|
|
presencePenalty: zod.z.number().optional().describe("The presence penalty for the OpenAI model")
|
|
});
|
|
|
|
const FilterPatternSchema = zod.z.union([
|
|
zod.z.array(zod.z.union([zod.z.string(), zod.z.instanceof(RegExp)])),
|
|
zod.z.string(),
|
|
zod.z.instanceof(RegExp),
|
|
zod.z.function(zod.z.tuple([zod.z.string()]), zod.z.boolean()).optional(),
|
|
zod.z.null(),
|
|
zod.z.undefined()
|
|
]);
|
|
const ChatModelSchema = zod.z.union([
|
|
AnthropicModelConfigSchema,
|
|
HuggingFaceModelConfigSchema,
|
|
OpenaiModelConfigSchema
|
|
]);
|
|
const PartialChatModelTypeMapSchema = zod.z.object({
|
|
[ChatModelType.Anthropic]: AnthropicModelConfigSchema.optional(),
|
|
[ChatModelType.HuggingFace]: HuggingFaceModelConfigSchema.optional(),
|
|
[ChatModelType.Openai]: OpenaiModelConfigSchema.optional()
|
|
});
|
|
const UserConfigSchema = zod.z.object({
|
|
model: ChatModelSchema.optional().describe("The LLM model configuration"),
|
|
rootPath: zod.z.string().optional().describe("The root path of the project"),
|
|
exts: zod.z.array(zod.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: zod.z.boolean().optional().default(true).describe("Whether to respect .gitignore rules"),
|
|
urlConfig: zod.z.record(zod.z.object({
|
|
modelNames: zod.z.array(zod.z.string()).optional().describe("The model name that will be displayed in the model selector"),
|
|
httpRequestHeader: zod.z.record(zod.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 = zod.z.object({
|
|
name: ChatRoleSchema,
|
|
text: zod.z.string()
|
|
});
|
|
const FormOptionSchema = zod.z.object({
|
|
label: zod.z.string().optional(),
|
|
value: zod.z.string()
|
|
});
|
|
const FormFieldBaseConfigSchema = zod.z.object({
|
|
type: zod.z.string(),
|
|
defaultValue: zod.z.any().optional(),
|
|
description: zod.z.string().optional()
|
|
});
|
|
const FormInputConfigSchema = FormFieldBaseConfigSchema.extend({
|
|
type: zod.z.literal("input")
|
|
});
|
|
const FormTextareaConfigSchema = FormFieldBaseConfigSchema.extend({
|
|
type: zod.z.literal("textarea"),
|
|
row: zod.z.number().optional()
|
|
});
|
|
const FormSelectConfigSchema = FormFieldBaseConfigSchema.extend({
|
|
type: zod.z.literal("select"),
|
|
options: zod.z.array(FormOptionSchema)
|
|
});
|
|
const FormCheckboxGroupConfigSchema = FormFieldBaseConfigSchema.extend({
|
|
type: zod.z.literal("checkbox-group"),
|
|
options: zod.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: zod.z.literal("radio-group"),
|
|
options: zod.z.array(FormOptionSchema)
|
|
});
|
|
const FormItemConfigSchema = zod.z.union([
|
|
FormInputConfigSchema,
|
|
FormTextareaConfigSchema,
|
|
FormSelectConfigSchema,
|
|
FormCheckboxGroupConfigSchema,
|
|
FormRadioGroupConfigSchema
|
|
]);
|
|
const SingleFileConfigSchema = zod.z.object({
|
|
model: UserConfigSchema.shape.model,
|
|
title: zod.z.string().optional(),
|
|
userPrompt: zod.z.string().optional(),
|
|
systemPrompt: zod.z.string().optional(),
|
|
messages: zod.z.array(SingleChatMessageSchema).optional(),
|
|
forms: zod.z.record(FormItemConfigSchema).optional()
|
|
});
|
|
|
|
const ChatStreamReqParamsSchema = zod.z.object({
|
|
messages: zod.z.array(SingleChatMessageSchema),
|
|
prompt: zod.z.string(),
|
|
systemPrompt: zod.z.string().optional(),
|
|
appendSystemPrompt: zod.z.string().optional(),
|
|
systemPromptAsUserPrompt: zod.z.boolean().optional(),
|
|
singleFilePath: zod.z.string().optional(),
|
|
singleFileConfig: SingleFileConfigSchema.optional(),
|
|
overrideModelType: ChatModelTypeSchema.optional(),
|
|
overrideModelsConfig: PartialChatModelTypeMapSchema.optional(),
|
|
modelTypeVendorNameMap: zod.z.record(zod.z.string()).optional(),
|
|
contextFilePaths: zod.z.array(zod.z.string()).optional(),
|
|
editingFilePath: zod.z.string().optional(),
|
|
rootPath: zod.z.string().optional()
|
|
});
|
|
const GetModelNamesForChooseReqParamsSchema = zod.z.object({
|
|
rootPath: zod.z.string(),
|
|
modelType: ChatModelTypeSchema,
|
|
modelTypeVendorNameMap: zod.z.record(zod.z.string()).optional()
|
|
});
|
|
const GetGptFilesReqParamsSchema = zod.z.object({
|
|
rootPath: zod.z.string()
|
|
});
|
|
const GetGptFileInfoReqParamsSchema = zod.z.object({
|
|
rootPath: zod.z.string(),
|
|
filePath: zod.z.string()
|
|
});
|
|
const InitGptFilesReqParamsSchema = zod.z.object({
|
|
rootPath: zod.z.string(),
|
|
gptFilesNames: zod.z.array(zod.z.string())
|
|
});
|
|
const GetUserConfigReqParamsSchema = zod.z.object({
|
|
rootPath: zod.z.string()
|
|
});
|
|
const StorageGetItemReqParamsSchema = zod.z.object({
|
|
storageName: ServerStorageNameSchema,
|
|
key: zod.z.string()
|
|
});
|
|
const StorageSetItemReqParamsSchema = zod.z.object({
|
|
storageName: ServerStorageNameSchema,
|
|
key: zod.z.string(),
|
|
value: zod.z.record(zod.z.any()).nullable().optional()
|
|
});
|
|
const StorageRemoveItemReqParamsSchema = zod.z.object({
|
|
storageName: ServerStorageNameSchema,
|
|
key: zod.z.string()
|
|
});
|
|
const StorageClearReqParamsSchema = zod.z.object({
|
|
storageName: ServerStorageNameSchema
|
|
});
|
|
const GetCommonFilesReqParamsSchema = zod.z.object({
|
|
rootPath: zod.z.string(),
|
|
excludeExts: zod.z.array(zod.z.string()).optional()
|
|
});
|
|
const OpenEditorReqParamsSchema = zod.z.object({
|
|
rootPath: zod.z.string().optional(),
|
|
path: zod.z.string(),
|
|
matchContent: zod.z.string().optional()
|
|
});
|
|
const CreateFilePathReqParamsSchema = zod.z.object({
|
|
fileFullPath: zod.z.string(),
|
|
isDir: zod.z.boolean()
|
|
});
|
|
const RenameFilePathReqParamsSchema = zod.z.object({
|
|
oldFileFullPath: zod.z.string(),
|
|
newFileFullPath: zod.z.string()
|
|
});
|
|
const DeleteFilePathReqParamsSchema = zod.z.object({
|
|
fileFullPath: zod.z.string()
|
|
});
|
|
const GetFileInfoReqParamsSchema = zod.z.object({
|
|
fileFullPath: zod.z.string()
|
|
});
|
|
const SaveFileContentReqParamsSchema = zod.z.object({
|
|
fileFullPath: zod.z.string(),
|
|
content: zod.z.string()
|
|
});
|
|
const GetAppConfigReqParamsSchema = zod.z.object({
|
|
langId: LocaleLangSchema.optional()
|
|
});
|
|
const MarkAsVisitedAppConfigReqParamsSchema = zod.z.object({
|
|
types: zod.z.array(zod.z.union([
|
|
zod.z.literal("notificationDate"),
|
|
zod.z.literal("releaseDate")
|
|
]))
|
|
});
|
|
|
|
const userConfigJsonSchema = zodToJsonSchema.zodToJsonSchema(UserConfigForUserSchema);
|
|
const singleFileJsonSchema = zodToJsonSchema.zodToJsonSchema(SingleFileConfigSchema);
|
|
|
|
exports.AnthropicModelConfigSchema = AnthropicModelConfigSchema;
|
|
exports.AnthropicSecretsSchema = AnthropicSecretsSchema;
|
|
exports.BaseModelConfigSchema = BaseModelConfigSchema;
|
|
exports.BaseSecretsSchema = BaseSecretsSchema;
|
|
exports.ChatMessageStatus = ChatMessageStatus;
|
|
exports.ChatMessageStatusSchema = ChatMessageStatusSchema;
|
|
exports.ChatModelSchema = ChatModelSchema;
|
|
exports.ChatModelType = ChatModelType;
|
|
exports.ChatModelTypeSchema = ChatModelTypeSchema;
|
|
exports.ChatRole = ChatRole;
|
|
exports.ChatRoleSchema = ChatRoleSchema;
|
|
exports.ChatStreamReqParamsSchema = ChatStreamReqParamsSchema;
|
|
exports.ClientEventName = ClientEventName;
|
|
exports.ClientEventNameSchema = ClientEventNameSchema;
|
|
exports.CreateFilePathReqParamsSchema = CreateFilePathReqParamsSchema;
|
|
exports.DEFAULT_API_BASE_PATH = DEFAULT_API_BASE_PATH;
|
|
exports.DEFAULT_EXCLUDE_FILES = DEFAULT_EXCLUDE_FILES;
|
|
exports.DEFAULT_EXCLUDE_FILE_EXTS = DEFAULT_EXCLUDE_FILE_EXTS;
|
|
exports.DEFAULT_MODEL_NAMES_FOR_CHOOSE = DEFAULT_MODEL_NAMES_FOR_CHOOSE;
|
|
exports.Debug = Debug;
|
|
exports.DeleteFilePathReqParamsSchema = DeleteFilePathReqParamsSchema;
|
|
exports.EnvConfig = EnvConfig;
|
|
exports.FilterPatternSchema = FilterPatternSchema;
|
|
exports.FormCheckboxGroupConfigSchema = FormCheckboxGroupConfigSchema;
|
|
exports.FormFieldBaseConfigSchema = FormFieldBaseConfigSchema;
|
|
exports.FormInputConfigSchema = FormInputConfigSchema;
|
|
exports.FormItemConfigSchema = FormItemConfigSchema;
|
|
exports.FormOptionSchema = FormOptionSchema;
|
|
exports.FormRadioGroupConfigSchema = FormRadioGroupConfigSchema;
|
|
exports.FormSelectConfigSchema = FormSelectConfigSchema;
|
|
exports.FormTextareaConfigSchema = FormTextareaConfigSchema;
|
|
exports.GPT_RUNNER_OFFICIAL_FOLDER = GPT_RUNNER_OFFICIAL_FOLDER;
|
|
exports.GetAppConfigReqParamsSchema = GetAppConfigReqParamsSchema;
|
|
exports.GetCommonFilesReqParamsSchema = GetCommonFilesReqParamsSchema;
|
|
exports.GetFileInfoReqParamsSchema = GetFileInfoReqParamsSchema;
|
|
exports.GetGptFileInfoReqParamsSchema = GetGptFileInfoReqParamsSchema;
|
|
exports.GetGptFilesReqParamsSchema = GetGptFilesReqParamsSchema;
|
|
exports.GetModelNamesForChooseReqParamsSchema = GetModelNamesForChooseReqParamsSchema;
|
|
exports.GetUserConfigReqParamsSchema = GetUserConfigReqParamsSchema;
|
|
exports.GptFileTreeItemType = GptFileTreeItemType;
|
|
exports.GptFileTreeItemTypeSchema = GptFileTreeItemTypeSchema;
|
|
exports.HuggingFaceModelConfigSchema = HuggingFaceModelConfigSchema;
|
|
exports.HuggingFaceSecretsSchema = HuggingFaceSecretsSchema;
|
|
exports.InitGptFilesReqParamsSchema = InitGptFilesReqParamsSchema;
|
|
exports.LocaleLang = LocaleLang;
|
|
exports.LocaleLangSchema = LocaleLangSchema;
|
|
exports.MIN_NODE_VERSION = MIN_NODE_VERSION;
|
|
exports.MarkAsVisitedAppConfigReqParamsSchema = MarkAsVisitedAppConfigReqParamsSchema;
|
|
exports.OpenEditorReqParamsSchema = OpenEditorReqParamsSchema;
|
|
exports.OpenaiModelConfigSchema = OpenaiModelConfigSchema;
|
|
exports.OpenaiSecretsSchema = OpenaiSecretsSchema;
|
|
exports.PartialChatModelTypeMapSchema = PartialChatModelTypeMapSchema;
|
|
exports.RenameFilePathReqParamsSchema = RenameFilePathReqParamsSchema;
|
|
exports.SECRET_KEY_PLACEHOLDER = SECRET_KEY_PLACEHOLDER;
|
|
exports.STREAM_DONE_FLAG = STREAM_DONE_FLAG;
|
|
exports.SaveFileContentReqParamsSchema = SaveFileContentReqParamsSchema;
|
|
exports.SecretStorageKey = SecretStorageKey;
|
|
exports.ServerStorageName = ServerStorageName;
|
|
exports.ServerStorageNameSchema = ServerStorageNameSchema;
|
|
exports.SingleChatMessageSchema = SingleChatMessageSchema;
|
|
exports.SingleFileConfigSchema = SingleFileConfigSchema;
|
|
exports.StorageClearReqParamsSchema = StorageClearReqParamsSchema;
|
|
exports.StorageGetItemReqParamsSchema = StorageGetItemReqParamsSchema;
|
|
exports.StorageRemoveItemReqParamsSchema = StorageRemoveItemReqParamsSchema;
|
|
exports.StorageSetItemReqParamsSchema = StorageSetItemReqParamsSchema;
|
|
exports.UserConfigForUserSchema = UserConfigForUserSchema;
|
|
exports.UserConfigSchema = UserConfigSchema;
|
|
exports.VendorTag = VendorTag;
|
|
exports.WssActionName = WssActionName;
|
|
exports.WssUtils = WssUtils;
|
|
exports.buildFailResponse = buildFailResponse;
|
|
exports.buildSuccessResponse = buildSuccessResponse;
|
|
exports.createFilterByPattern = createFilterByPattern;
|
|
exports.debounce = debounce;
|
|
exports.formatSourceValue = formatSourceValue;
|
|
exports.getErrorMsg = getErrorMsg;
|
|
exports.getProcessCwd = getProcessCwd;
|
|
exports.hasOwn = hasOwn;
|
|
exports.isChineseCharacter = isChineseCharacter;
|
|
exports.objectToQueryString = objectToQueryString;
|
|
exports.runOnceByKey = runOnceByKey;
|
|
exports.singleFileJsonSchema = singleFileJsonSchema;
|
|
exports.sleep = sleep;
|
|
exports.toUnixPath = toUnixPath;
|
|
exports.travelTree = travelTree;
|
|
exports.travelTreeDeepFirst = travelTreeDeepFirst;
|
|
exports.tryParseJson = tryParseJson;
|
|
exports.tryStringifyJson = tryStringifyJson;
|
|
exports.urlRemoveLocalhost = urlRemoveLocalhost;
|
|
exports.userConfigJsonSchema = userConfigJsonSchema;
|
|
exports.verifyZod = verifyZod;
|
|
exports.waitForCondition = waitForCondition;
|