repo stringlengths 5 106 | file_url stringlengths 78 301 | file_path stringlengths 4 211 | content stringlengths 0 32.8k | language stringclasses 1
value | license stringclasses 7
values | commit_sha stringlengths 40 40 | retrieved_at stringdate 2026-01-04 14:56:49 2026-01-05 02:23:25 | truncated bool 2
classes |
|---|---|---|---|---|---|---|---|---|
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/files/multer.js | server/utils/files/multer.js | const multer = require("multer");
const path = require("path");
const fs = require("fs");
const { v4 } = require("uuid");
const { normalizePath } = require(".");
/**
* Handle File uploads for auto-uploading.
* Mostly used for internal GUI/API uploads.
*/
const fileUploadStorage = multer.diskStorage({
destination: function (_, __, cb) {
const uploadOutput =
process.env.NODE_ENV === "development"
? path.resolve(__dirname, `../../../collector/hotdir`)
: path.resolve(process.env.STORAGE_DIR, `../../collector/hotdir`);
cb(null, uploadOutput);
},
filename: function (_, file, cb) {
file.originalname = normalizePath(
Buffer.from(file.originalname, "latin1").toString("utf8")
);
cb(null, file.originalname);
},
});
/**
* Handle API file upload as documents - this does not manipulate the filename
* at all for encoding/charset reasons.
*/
const fileAPIUploadStorage = multer.diskStorage({
destination: function (_, __, cb) {
const uploadOutput =
process.env.NODE_ENV === "development"
? path.resolve(__dirname, `../../../collector/hotdir`)
: path.resolve(process.env.STORAGE_DIR, `../../collector/hotdir`);
cb(null, uploadOutput);
},
filename: function (_, file, cb) {
file.originalname = normalizePath(
Buffer.from(file.originalname, "latin1").toString("utf8")
);
cb(null, file.originalname);
},
});
// Asset storage for logos
const assetUploadStorage = multer.diskStorage({
destination: function (_, __, cb) {
const uploadOutput =
process.env.NODE_ENV === "development"
? path.resolve(__dirname, `../../storage/assets`)
: path.resolve(process.env.STORAGE_DIR, "assets");
fs.mkdirSync(uploadOutput, { recursive: true });
return cb(null, uploadOutput);
},
filename: function (_, file, cb) {
file.originalname = normalizePath(
Buffer.from(file.originalname, "latin1").toString("utf8")
);
cb(null, file.originalname);
},
});
/**
* Handle PFP file upload as logos
*/
const pfpUploadStorage = multer.diskStorage({
destination: function (_, __, cb) {
const uploadOutput =
process.env.NODE_ENV === "development"
? path.resolve(__dirname, `../../storage/assets/pfp`)
: path.resolve(process.env.STORAGE_DIR, "assets/pfp");
fs.mkdirSync(uploadOutput, { recursive: true });
return cb(null, uploadOutput);
},
filename: function (req, file, cb) {
const randomFileName = `${v4()}${path.extname(
normalizePath(file.originalname)
)}`;
req.randomFileName = randomFileName;
cb(null, randomFileName);
},
});
/**
* Handle Generic file upload as documents from the GUI
* @param {Request} request
* @param {Response} response
* @param {NextFunction} next
*/
function handleFileUpload(request, response, next) {
const upload = multer({ storage: fileUploadStorage }).single("file");
upload(request, response, function (err) {
if (err) {
response
.status(500)
.json({
success: false,
error: `Invalid file upload. ${err.message}`,
})
.end();
return;
}
next();
});
}
/**
* Handle API file upload as documents - this does not manipulate the filename
* at all for encoding/charset reasons.
* @param {Request} request
* @param {Response} response
* @param {NextFunction} next
*/
function handleAPIFileUpload(request, response, next) {
const upload = multer({ storage: fileAPIUploadStorage }).single("file");
upload(request, response, function (err) {
if (err) {
response
.status(500)
.json({
success: false,
error: `Invalid file upload. ${err.message}`,
})
.end();
return;
}
next();
});
}
/**
* Handle logo asset uploads
*/
function handleAssetUpload(request, response, next) {
const upload = multer({ storage: assetUploadStorage }).single("logo");
upload(request, response, function (err) {
if (err) {
response
.status(500)
.json({
success: false,
error: `Invalid file upload. ${err.message}`,
})
.end();
return;
}
next();
});
}
/**
* Handle PFP file upload as logos
*/
function handlePfpUpload(request, response, next) {
const upload = multer({ storage: pfpUploadStorage }).single("file");
upload(request, response, function (err) {
if (err) {
response
.status(500)
.json({
success: false,
error: `Invalid file upload. ${err.message}`,
})
.end();
return;
}
next();
});
}
module.exports = {
handleFileUpload,
handleAPIFileUpload,
handleAssetUpload,
handlePfpUpload,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/TextToSpeech/index.js | server/utils/TextToSpeech/index.js | function getTTSProvider() {
const provider = process.env.TTS_PROVIDER || "openai";
switch (provider) {
case "openai":
const { OpenAiTTS } = require("./openAi");
return new OpenAiTTS();
case "elevenlabs":
const { ElevenLabsTTS } = require("./elevenLabs");
return new ElevenLabsTTS();
case "generic-openai":
const { GenericOpenAiTTS } = require("./openAiGeneric");
return new GenericOpenAiTTS();
default:
throw new Error("ENV: No TTS_PROVIDER value found in environment!");
}
}
module.exports = { getTTSProvider };
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/TextToSpeech/openAiGeneric/index.js | server/utils/TextToSpeech/openAiGeneric/index.js | class GenericOpenAiTTS {
constructor() {
if (!process.env.TTS_OPEN_AI_COMPATIBLE_KEY)
this.#log(
"No OpenAI compatible API key was set. You might need to set this to use your OpenAI compatible TTS service."
);
if (!process.env.TTS_OPEN_AI_COMPATIBLE_MODEL)
this.#log(
"No OpenAI compatible TTS model was set. We will use the default voice model 'tts-1'. This may not exist or be valid your selected endpoint."
);
if (!process.env.TTS_OPEN_AI_COMPATIBLE_VOICE_MODEL)
this.#log(
"No OpenAI compatible voice model was set. We will use the default voice model 'alloy'. This may not exist for your selected endpoint."
);
if (!process.env.TTS_OPEN_AI_COMPATIBLE_ENDPOINT)
throw new Error(
"No OpenAI compatible endpoint was set. Please set this to use your OpenAI compatible TTS service."
);
const { OpenAI: OpenAIApi } = require("openai");
this.openai = new OpenAIApi({
apiKey: process.env.TTS_OPEN_AI_COMPATIBLE_KEY || null,
baseURL: process.env.TTS_OPEN_AI_COMPATIBLE_ENDPOINT,
});
this.model = process.env.TTS_OPEN_AI_COMPATIBLE_MODEL ?? "tts-1";
this.voice = process.env.TTS_OPEN_AI_COMPATIBLE_VOICE_MODEL ?? "alloy";
this.#log(
`Service (${process.env.TTS_OPEN_AI_COMPATIBLE_ENDPOINT}) with model: ${this.model} and voice: ${this.voice}`
);
}
#log(text, ...args) {
console.log(`\x1b[32m[OpenAiGenericTTS]\x1b[0m ${text}`, ...args);
}
/**
* Generates a buffer from the given text input using the OpenAI compatible TTS service.
* @param {string} textInput - The text to be converted to audio.
* @returns {Promise<Buffer>} A buffer containing the audio data.
*/
async ttsBuffer(textInput) {
try {
const result = await this.openai.audio.speech.create({
model: this.model,
voice: this.voice,
input: textInput,
});
return Buffer.from(await result.arrayBuffer());
} catch (e) {
console.error(e);
}
return null;
}
}
module.exports = {
GenericOpenAiTTS,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/TextToSpeech/openAi/index.js | server/utils/TextToSpeech/openAi/index.js | class OpenAiTTS {
constructor() {
if (!process.env.TTS_OPEN_AI_KEY)
throw new Error("No OpenAI API key was set.");
const { OpenAI: OpenAIApi } = require("openai");
this.openai = new OpenAIApi({
apiKey: process.env.TTS_OPEN_AI_KEY,
});
this.voice = process.env.TTS_OPEN_AI_VOICE_MODEL ?? "alloy";
}
async ttsBuffer(textInput) {
try {
const result = await this.openai.audio.speech.create({
model: "tts-1",
voice: this.voice,
input: textInput,
});
return Buffer.from(await result.arrayBuffer());
} catch (e) {
console.error(e);
}
return null;
}
}
module.exports = {
OpenAiTTS,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/TextToSpeech/elevenLabs/index.js | server/utils/TextToSpeech/elevenLabs/index.js | const { ElevenLabsClient, stream } = require("elevenlabs");
class ElevenLabsTTS {
constructor() {
if (!process.env.TTS_ELEVEN_LABS_KEY)
throw new Error("No ElevenLabs API key was set.");
this.elevenLabs = new ElevenLabsClient({
apiKey: process.env.TTS_ELEVEN_LABS_KEY,
});
// Rachel as default voice
// https://api.elevenlabs.io/v1/voices
this.voiceId =
process.env.TTS_ELEVEN_LABS_VOICE_MODEL ?? "21m00Tcm4TlvDq8ikWAM";
this.modelId = "eleven_multilingual_v2";
}
static async voices(apiKey = null) {
try {
const client = new ElevenLabsClient({
apiKey: apiKey ?? process.env.TTS_ELEVEN_LABS_KEY ?? null,
});
return (await client.voices.getAll())?.voices ?? [];
} catch {}
return [];
}
#stream2buffer(stream) {
return new Promise((resolve, reject) => {
const _buf = [];
stream.on("data", (chunk) => _buf.push(chunk));
stream.on("end", () => resolve(Buffer.concat(_buf)));
stream.on("error", (err) => reject(err));
});
}
async ttsBuffer(textInput) {
try {
const audio = await this.elevenLabs.generate({
voice: this.voiceId,
text: textInput,
model_id: "eleven_multilingual_v2",
});
return Buffer.from(await this.#stream2buffer(audio));
} catch (e) {
console.error(e);
}
return null;
}
}
module.exports = {
ElevenLabsTTS,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/PasswordRecovery/index.js | server/utils/PasswordRecovery/index.js | const bcrypt = require("bcryptjs");
const { v4, validate } = require("uuid");
const { User } = require("../../models/user");
const {
RecoveryCode,
PasswordResetToken,
} = require("../../models/passwordRecovery");
async function generateRecoveryCodes(userId) {
const newRecoveryCodes = [];
const plainTextCodes = [];
for (let i = 0; i < 4; i++) {
const code = v4();
const hashedCode = bcrypt.hashSync(code, 10);
newRecoveryCodes.push({
user_id: userId,
code_hash: hashedCode,
});
plainTextCodes.push(code);
}
const { error } = await RecoveryCode.createMany(newRecoveryCodes);
if (!!error) throw new Error(error);
const { user: success } = await User._update(userId, {
seen_recovery_codes: true,
});
if (!success) throw new Error("Failed to generate user recovery codes!");
return plainTextCodes;
}
async function recoverAccount(username = "", recoveryCodes = []) {
const user = await User.get({ username: String(username) });
if (!user) return { success: false, error: "Invalid recovery codes." };
// If hashes do not exist for a user
// because this is a user who has not logged out and back in since upgrade.
const allUserHashes = await RecoveryCode.hashesForUser(user.id);
if (allUserHashes.length < 4)
return { success: false, error: "Invalid recovery codes." };
// If they tried to send more than two unique codes, we only take the first two
const uniqueRecoveryCodes = [...new Set(recoveryCodes)]
.map((code) => code.trim())
.filter((code) => validate(code)) // we know that any provided code must be a uuid v4.
.slice(0, 2);
if (uniqueRecoveryCodes.length !== 2)
return { success: false, error: "Invalid recovery codes." };
const validCodes = uniqueRecoveryCodes.every((code) => {
let valid = false;
allUserHashes.forEach((hash) => {
if (bcrypt.compareSync(code, hash)) valid = true;
});
return valid;
});
if (!validCodes) return { success: false, error: "Invalid recovery codes." };
const { passwordResetToken, error } = await PasswordResetToken.create(
user.id
);
if (!!error) return { success: false, error };
return { success: true, resetToken: passwordResetToken.token };
}
async function resetPassword(token, _newPassword = "", confirmPassword = "") {
const newPassword = String(_newPassword).trim(); // No spaces in passwords
if (!newPassword) throw new Error("Invalid password.");
if (newPassword !== String(confirmPassword))
throw new Error("Passwords do not match");
const resetToken = await PasswordResetToken.findUnique({
token: String(token),
});
if (!resetToken || resetToken.expiresAt < new Date()) {
return { success: false, message: "Invalid reset token" };
}
// JOI password rules will be enforced inside .update.
const { error } = await User.update(resetToken.user_id, {
password: newPassword,
});
// seen_recovery_codes is not publicly writable
// so we have to do direct update here
await User._update(resetToken.user_id, {
seen_recovery_codes: false,
});
if (error) return { success: false, message: error };
await PasswordResetToken.deleteMany({ user_id: resetToken.user_id });
await RecoveryCode.deleteMany({ user_id: resetToken.user_id });
// New codes are provided on first new login.
return { success: true, message: "Password reset successful" };
}
module.exports = {
recoverAccount,
resetPassword,
generateRecoveryCodes,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/MCP/index.js | server/utils/MCP/index.js | const MCPHypervisor = require("./hypervisor");
class MCPCompatibilityLayer extends MCPHypervisor {
static _instance;
constructor() {
super();
if (MCPCompatibilityLayer._instance) return MCPCompatibilityLayer._instance;
MCPCompatibilityLayer._instance = this;
}
/**
* Get all of the active MCP servers as plugins we can load into agents.
* This will also boot all MCP servers if they have not been started yet.
* @returns {Promise<string[]>} Array of flow names in @@mcp_{name} format
*/
async activeMCPServers() {
await this.bootMCPServers();
return Object.keys(this.mcps).flatMap((name) => `@@mcp_${name}`);
}
/**
* Convert an MCP server name to an AnythingLLM Agent plugin
* @param {string} name - The base name of the MCP server to convert - not the tool name. eg: `docker-mcp` not `docker-mcp:list-containers`
* @param {Object} aibitat - The aibitat object to pass to the plugin
* @returns {Promise<{name: string, description: string, plugin: Function}[]|null>} Array of plugin configurations or null if not found
*/
async convertServerToolsToPlugins(name, _aibitat = null) {
const mcp = this.mcps[name];
if (!mcp) return null;
let tools;
try {
const response = await mcp.listTools();
tools = response.tools;
} catch (error) {
this.log(`Failed to list tools for MCP server ${name}:`, error);
return null;
}
if (!tools || !tools.length) return null;
const plugins = [];
for (const tool of tools) {
plugins.push({
name: `${name}-${tool.name}`,
description: tool.description,
plugin: function () {
return {
name: `${name}-${tool.name}`,
setup: (aibitat) => {
aibitat.function({
super: aibitat,
name: `${name}-${tool.name}`,
controller: new AbortController(),
description: tool.description,
isMCPTool: true,
examples: [],
parameters: {
$schema: "http://json-schema.org/draft-07/schema#",
...tool.inputSchema,
},
handler: async function (args = {}) {
try {
const mcpLayer = new MCPCompatibilityLayer();
const currentMcp = mcpLayer.mcps[name];
if (!currentMcp)
throw new Error(
`MCP server ${name} is not currently running`
);
aibitat.handlerProps.log(
`Executing MCP server: ${name}:${tool.name} with args:`,
args
);
aibitat.introspect(
`Executing MCP server: ${name} with ${JSON.stringify(args, null, 2)}`
);
const result = await currentMcp.callTool({
name: tool.name,
arguments: args,
});
aibitat.handlerProps.log(
`MCP server: ${name}:${tool.name} completed successfully`,
result
);
aibitat.introspect(
`MCP server: ${name}:${tool.name} completed successfully`
);
return MCPCompatibilityLayer.returnMCPResult(result);
} catch (error) {
aibitat.handlerProps.log(
`MCP server: ${name}:${tool.name} failed with error:`,
error
);
aibitat.introspect(
`MCP server: ${name}:${tool.name} failed with error:`,
error
);
return `The tool ${name}:${tool.name} failed with error: ${error?.message || "An unknown error occurred"}`;
}
},
});
},
};
},
toolName: `${name}:${tool.name}`,
});
}
return plugins;
}
/**
* Returns the MCP servers that were loaded or attempted to be loaded
* so that we can display them in the frontend for review or error logging.
* @returns {Promise<{
* name: string,
* running: boolean,
* tools: {name: string, description: string, inputSchema: Object}[],
* process: {pid: number, cmd: string}|null,
* error: string|null
* }[]>} - The active MCP servers
*/
async servers() {
await this.bootMCPServers();
const servers = [];
for (const [name, result] of Object.entries(this.mcpLoadingResults)) {
const config = this.mcpServerConfigs.find((s) => s.name === name);
if (result.status === "failed") {
servers.push({
name,
config: config?.server || null,
running: false,
tools: [],
error: result.message,
process: null,
});
continue;
}
const mcp = this.mcps[name];
if (!mcp) {
delete this.mcpLoadingResults[name];
delete this.mcps[name];
continue;
}
const online = !!(await mcp.ping());
const tools = (online ? (await mcp.listTools()).tools : []).filter(
(tool) => !tool.name.startsWith("handle_mcp_connection_mcp_")
);
servers.push({
name,
config: config?.server || null,
running: online,
tools,
error: null,
process: {
pid: mcp.transport?.process?.pid || null,
},
});
}
return servers;
}
/**
* Toggle the MCP server (start or stop)
* @param {string} name - The name of the MCP server to toggle
* @returns {Promise<{success: boolean, error: string | null}>}
*/
async toggleServerStatus(name) {
const server = this.mcpServerConfigs.find((s) => s.name === name);
if (!server)
return {
success: false,
error: `MCP server ${name} not found in config file.`,
};
const mcp = this.mcps[name];
const online = !!mcp ? !!(await mcp.ping()) : false; // If the server is not in the mcps object, it is not running
if (online) {
const killed = this.pruneMCPServer(name);
return {
success: killed,
error: killed ? null : `Failed to kill MCP server: ${name}`,
};
} else {
const startupResult = await this.startMCPServer(name);
return { success: startupResult.success, error: startupResult.error };
}
}
/**
* Delete the MCP server - will also remove it from the config file
* @param {string} name - The name of the MCP server to delete
* @returns {Promise<{success: boolean, error: string | null}>}
*/
async deleteServer(name) {
const server = this.mcpServerConfigs.find((s) => s.name === name);
if (!server)
return {
success: false,
error: `MCP server ${name} not found in config file.`,
};
const mcp = this.mcps[name];
const online = !!mcp ? !!(await mcp.ping()) : false; // If the server is not in the mcps object, it is not running
if (online) this.pruneMCPServer(name);
this.removeMCPServerFromConfig(name);
delete this.mcps[name];
delete this.mcpLoadingResults[name];
this.log(`MCP server was killed and removed from config file: ${name}`);
return { success: true, error: null };
}
/**
* Return the result of an MCP server call as a string
* This will handle circular references and bigints since an MCP server can return any type of data.
* @param {Object} result - The result to return
* @returns {string} The result as a string
*/
static returnMCPResult(result) {
if (typeof result !== "object" || result === null) return String(result);
const seen = new WeakSet();
try {
return JSON.stringify(result, (key, value) => {
if (typeof value === "bigint") return value.toString();
if (typeof value === "object" && value !== null) {
if (seen.has(value)) return "[Circular]";
seen.add(value);
}
return value;
});
} catch (e) {
return `[Unserializable: ${e.message}]`;
}
}
}
module.exports = MCPCompatibilityLayer;
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/MCP/hypervisor/index.js | server/utils/MCP/hypervisor/index.js | const { safeJsonParse } = require("../../http");
const path = require("path");
const fs = require("fs");
const { Client } = require("@modelcontextprotocol/sdk/client/index.js");
const {
StdioClientTransport,
} = require("@modelcontextprotocol/sdk/client/stdio.js");
const {
SSEClientTransport,
} = require("@modelcontextprotocol/sdk/client/sse.js");
const {
StreamableHTTPClientTransport,
} = require("@modelcontextprotocol/sdk/client/streamableHttp.js");
/**
* @typedef {'stdio' | 'http' | 'sse'} MCPServerTypes
*/
/**
* @class MCPHypervisor
* @description A class that manages MCP servers found in the storage/plugins/anythingllm_mcp_servers.json file.
* This class is responsible for booting, stopping, and reloading MCP servers - it is the user responsibility for the MCP server definitions
* to me correct and also functioning tools depending on their deployment (docker vs local) as well as the security of said tools
* since MCP is basically arbitrary code execution.
*
* @notice This class is a singleton.
* @notice Each MCP tool has dependencies specific to it and this call WILL NOT check for them.
* For example, if the tools requires `npx` then the context in which AnythingLLM mains process is running will need to access npx.
* This is typically not common in our pre-built image so may not function. But this is the case anywhere MCP is used.
*
* AnythingLLM will take care of porting MCP servers to agent-callable functions via @agent directive.
* @see MCPCompatibilityLayer.convertServerToolsToPlugins
*/
class MCPHypervisor {
static _instance;
/**
* The path to the JSON file containing the MCP server definitions.
* @type {string}
*/
mcpServerJSONPath;
/**
* The MCP servers currently running.
* @type { { [key: string]: Client & {transport: {_process: import('child_process').ChildProcess}, aibitatToolIds: string[]} } }
*/
mcps = {};
/**
* The results of the MCP server loading process.
* @type { { [key: string]: {status: 'success' | 'failed', message: string} } }
*/
mcpLoadingResults = {};
constructor() {
if (MCPHypervisor._instance) return MCPHypervisor._instance;
MCPHypervisor._instance = this;
this.className = "MCPHypervisor";
this.log("Initializing MCP Hypervisor - subsequent calls will boot faster");
this.#setupConfigFile();
return this;
}
/**
* Setup the MCP server definitions file.
* Will create the file/directory if it doesn't exist already in storage/plugins with blank options
*/
#setupConfigFile() {
this.mcpServerJSONPath =
process.env.NODE_ENV === "development"
? path.resolve(
__dirname,
`../../../storage/plugins/anythingllm_mcp_servers.json`
)
: path.resolve(
process.env.STORAGE_DIR ??
path.resolve(__dirname, `../../../storage`),
`plugins/anythingllm_mcp_servers.json`
);
if (!fs.existsSync(this.mcpServerJSONPath)) {
fs.mkdirSync(path.dirname(this.mcpServerJSONPath), { recursive: true });
fs.writeFileSync(
this.mcpServerJSONPath,
JSON.stringify({ mcpServers: {} }, null, 2),
{ encoding: "utf8" }
);
}
this.log(`MCP Config File: ${this.mcpServerJSONPath}`);
}
log(text, ...args) {
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
}
/**
* Get the MCP servers from the JSON file.
* @returns { { name: string, server: { command: string, args: string[], env: { [key: string]: string } } }[] } The MCP servers.
*/
get mcpServerConfigs() {
const servers = safeJsonParse(
fs.readFileSync(this.mcpServerJSONPath, "utf8"),
{ mcpServers: {} }
);
return Object.entries(servers.mcpServers).map(([name, server]) => ({
name,
server,
}));
}
/**
* Remove the MCP server from the config file
* @param {string} name - The name of the MCP server to remove
* @returns {boolean} - True if the MCP server was removed, false otherwise
*/
removeMCPServerFromConfig(name) {
const servers = safeJsonParse(
fs.readFileSync(this.mcpServerJSONPath, "utf8"),
{ mcpServers: {} }
);
if (!servers.mcpServers[name]) return false;
delete servers.mcpServers[name];
fs.writeFileSync(
this.mcpServerJSONPath,
JSON.stringify(servers, null, 2),
"utf8"
);
this.log(`MCP server ${name} removed from config file`);
return true;
}
/**
* Reload the MCP servers - can be used to reload the MCP servers without restarting the server or app
* and will also apply changes to the config file if any where made.
*/
async reloadMCPServers() {
this.pruneMCPServers();
await this.bootMCPServers();
}
/**
* Start a single MCP server by its server name - public method
* @param {string} name - The name of the MCP server to start
* @returns {Promise<{success: boolean, error: string | null}>}
*/
async startMCPServer(name) {
if (this.mcps[name])
return { success: false, error: `MCP server ${name} already running` };
const config = this.mcpServerConfigs.find((s) => s.name === name);
if (!config)
return {
success: false,
error: `MCP server ${name} not found in config file`,
};
try {
await this.#startMCPServer(config);
this.mcpLoadingResults[name] = {
status: "success",
message: `Successfully connected to MCP server: ${name}`,
};
return { success: true, message: `MCP server ${name} started` };
} catch (e) {
this.log(`Failed to start single MCP server: ${name}`, {
error: e.message,
code: e.code,
syscall: e.syscall,
path: e.path,
stack: e.stack,
});
this.mcpLoadingResults[name] = {
status: "failed",
message: `Failed to start MCP server: ${name} [${e.code || "NO_CODE"}] ${e.message}`,
};
// Clean up failed connection
if (this.mcps[name]) {
this.mcps[name].close();
delete this.mcps[name];
}
return { success: false, error: e.message };
}
}
/**
* Prune a single MCP server by its server name
* @param {string} name - The name of the MCP server to prune
* @returns {boolean} - True if the MCP server was pruned, false otherwise
*/
pruneMCPServer(name) {
if (!name || !this.mcps[name]) return true;
this.log(`Pruning MCP server: ${name}`);
const mcp = this.mcps[name];
if (!mcp.transport) return true;
const childProcess = mcp.transport._process;
if (childProcess) childProcess.kill("SIGTERM");
mcp.transport.close();
delete this.mcps[name];
this.mcpLoadingResults[name] = {
status: "failed",
message: `Server was stopped manually by the administrator.`,
};
return true;
}
/**
* Prune the MCP servers - pkills and forgets all MCP servers
* @returns {void}
*/
pruneMCPServers() {
this.log(`Pruning ${Object.keys(this.mcps).length} MCP servers...`);
for (const name of Object.keys(this.mcps)) {
if (!this.mcps[name]) continue;
const mcp = this.mcps[name];
if (!mcp.transport) continue;
const childProcess = mcp.transport._process;
if (childProcess)
this.log(`Killing MCP ${name} (PID: ${childProcess.pid})`, {
killed: childProcess.kill("SIGTERM"),
});
mcp.transport.close();
mcp.close();
}
this.mcps = {};
this.mcpLoadingResults = {};
}
/**
* Load shell environment for desktop applications.
* MacOS and Linux don't inherit login shell environment. So this function
* fixes the PATH and accessible commands when running AnythingLLM outside of Docker during development on Mac/Linux and in-container (Linux).
* @returns {Promise<{[key: string]: string}>} - Environment variables from shell
*/
async #loadShellEnvironment() {
try {
if (process.platform === "win32") return process.env;
const { default: fixPath } = await import("fix-path");
const { default: stripAnsi } = await import("strip-ansi");
fixPath();
// Due to node v20 requirement to have a minimum version of fix-path v5, we need to strip ANSI codes manually
// which was the only patch between v4 and v5. Here we just apply manually.
// https://github.com/sindresorhus/fix-path/issues/6
if (process.env.PATH) process.env.PATH = stripAnsi(process.env.PATH);
return process.env;
} catch (error) {
console.warn(
"Failed to load shell environment, using process.env:",
error.message
);
return process.env;
}
}
/**
* Build the MCP server environment variables - ensures proper PATH and NODE_PATH
* inheritance across all platforms and deployment scenarios.
* @param {Object} server - The server definition
* @returns {Promise<{env: { [key: string]: string } | {}}}> - The environment variables
*/
async #buildMCPServerENV(server) {
const shellEnv = await this.#loadShellEnvironment();
let baseEnv = {
PATH:
shellEnv.PATH ||
process.env.PATH ||
"/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin",
NODE_PATH:
shellEnv.NODE_PATH ||
process.env.NODE_PATH ||
"/usr/local/lib/node_modules",
...shellEnv, // Include all shell environment variables
};
// Docker-specific environment setup
if (process.env.ANYTHING_LLM_RUNTIME === "docker") {
baseEnv = {
// Fixed: NODE_PATH should point to modules directory, not node binary
NODE_PATH: "/usr/local/lib/node_modules",
PATH: "/usr/local/bin:/usr/bin:/bin",
...baseEnv, // Allow inheritance to override docker defaults if needed
};
}
// No custom environment specified - return base environment
if (!server?.env || Object.keys(server.env).length === 0) {
return { env: baseEnv };
}
// Merge user-specified environment with base environment
// User environment takes precedence over defaults
return {
env: {
...baseEnv,
...server.env,
},
};
}
/**
* Parse the server type from the server definition
* @param {Object} server - The server definition
* @returns {MCPServerTypes | null} - The server type
*/
#parseServerType(server) {
if (
server.type === "sse" ||
server.type === "streamable" ||
server.type === "http"
)
return "http";
if (Object.prototype.hasOwnProperty.call(server, "command")) return "stdio";
if (Object.prototype.hasOwnProperty.call(server, "url")) return "http";
return "sse";
}
/**
* Validate the server definition by type
* - Will throw an error if the server definition is invalid
* @param {string} name - The name of the MCP server
* @param {Object} server - The server definition
* @param {MCPServerTypes} type - The server type
* @returns {void}
*/
#validateServerDefinitionByType(name, server, type) {
if (
server.type === "sse" ||
server.type === "streamable" ||
server.type === "http"
) {
if (!server.url) {
throw new Error(
`MCP server "${name}": missing required "url" for ${server.type} transport`
);
}
try {
new URL(server.url);
} catch (error) {
throw new Error(`MCP server "${name}": invalid URL "${server.url}"`);
}
return;
}
if (type === "stdio") {
if (
Object.prototype.hasOwnProperty.call(server, "args") &&
!Array.isArray(server.args)
)
throw new Error("MCP server args must be an array");
}
if (type === "http") {
if (!["sse", "streamable"].includes(server?.type))
throw new Error("MCP server type must have sse or streamable value.");
}
if (type === "sse") return;
return;
}
/**
* Setup the server transport by type and server definition
* @param {Object} server - The server definition
* @param {MCPServerTypes} type - The server type
* @returns {Promise<StdioClientTransport | StreamableHTTPClientTransport | SSEClientTransport>} - The server transport
*/
async #setupServerTransport(server, type) {
// if not stdio then it is http or sse
if (type !== "stdio") return this.createHttpTransport(server);
return new StdioClientTransport({
command: server.command,
args: server?.args ?? [],
...(await this.#buildMCPServerENV(server)),
});
}
/**
* Create MCP client transport for http MCP server.
* @param {Object} server - The server definition
* @returns {StreamableHTTPClientTransport | SSEClientTransport} - The server transport
*/
createHttpTransport(server) {
const url = new URL(server.url);
// If the server block has a type property then use that to determine the transport type
switch (server.type) {
case "streamable":
case "http":
return new StreamableHTTPClientTransport(url, {
requestInit: {
headers: server.headers,
},
});
default:
return new SSEClientTransport(url, {
requestInit: {
headers: server.headers,
},
});
}
}
/**
* @private Start a single MCP server by its server definition from the JSON file
* @param {string} name - The name of the MCP server to start
* @param {Object} server - The server definition
* @returns {Promise<boolean>}
*/
async #startMCPServer({ name, server }) {
if (!name) throw new Error("MCP server name is required");
if (!server) throw new Error("MCP server definition is required");
const serverType = this.#parseServerType(server);
if (!serverType) throw new Error("MCP server command or url is required");
this.#validateServerDefinitionByType(name, server, serverType);
this.log(`Attempting to start MCP server: ${name}`);
const mcp = new Client({ name: name, version: "1.0.0" });
const transport = await this.#setupServerTransport(server, serverType);
// Add connection event listeners
transport.onclose = () => this.log(`${name} - Transport closed`);
transport.onerror = (error) =>
this.log(`${name} - Transport error:`, error);
transport.onmessage = (message) =>
this.log(`${name} - Transport message:`, message);
// Connect and await the connection with a timeout
this.mcps[name] = mcp;
const connectionPromise = mcp.connect(transport);
let timeoutId;
const timeoutPromise = new Promise((_, reject) => {
timeoutId = setTimeout(
() => reject(new Error("Connection timeout")),
30_000
); // 30 second timeout
});
try {
await Promise.race([connectionPromise, timeoutPromise]);
if (timeoutId) clearTimeout(timeoutId);
} catch (error) {
if (timeoutId) clearTimeout(timeoutId);
throw error;
}
return true;
}
/**
* Boot the MCP servers according to the server definitions.
* This function will skip booting MCP servers if they are already running.
* @returns { Promise<{ [key: string]: {status: string, message: string} }> } The results of the boot process.
*/
async bootMCPServers() {
if (Object.keys(this.mcps).length > 0) {
this.log("MCP Servers already running, skipping boot.");
return this.mcpLoadingResults;
}
const serverDefinitions = this.mcpServerConfigs;
for (const { name, server } of serverDefinitions) {
if (
server.anythingllm?.hasOwnProperty("autoStart") &&
server.anythingllm.autoStart === false
) {
this.log(
`MCP server ${name} has anythingllm.autoStart property set to false, skipping boot!`
);
this.mcpLoadingResults[name] = {
status: "failed",
message: `MCP server ${name} has anythingllm.autoStart property set to false, boot skipped!`,
};
continue;
}
try {
await this.#startMCPServer({ name, server });
// Verify the connection is alive?
// if (!(await mcp.ping())) throw new Error('Connection failed to establish');
this.mcpLoadingResults[name] = {
status: "success",
message: `Successfully connected to MCP server: ${name}`,
};
} catch (e) {
this.log(`Failed to start MCP server: ${name}`, {
error: e.message,
code: e.code,
syscall: e.syscall,
path: e.path,
stack: e.stack, // Adding stack trace for better debugging
});
this.mcpLoadingResults[name] = {
status: "failed",
message: `Failed to start MCP server: ${name} [${e.code || "NO_CODE"}] ${e.message}`,
};
// Clean up failed connection
if (this.mcps[name]) {
this.mcps[name].close();
delete this.mcps[name];
}
}
}
const runningServers = Object.keys(this.mcps);
this.log(
`Successfully started ${runningServers.length} MCP servers:`,
runningServers
);
return this.mcpLoadingResults;
}
}
module.exports = MCPHypervisor;
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/prisma/index.js | server/utils/prisma/index.js | const { PrismaClient } = require("@prisma/client");
// npx prisma introspect
// npx prisma generate
// npx prisma migrate dev --name init -> ensures that db is in sync with schema
// npx prisma migrate reset -> resets the db
const logLevels = ["error", "info", "warn"]; // add "query" to debug query logs
const prisma = new PrismaClient({
log: logLevels,
});
module.exports = prisma;
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/boot/eagerLoadContextWindows.js | server/utils/boot/eagerLoadContextWindows.js | /**
* Eagerly load the context windows for the current provider.
* This is done to ensure that the context windows are pre-cached when the server boots.
*
* This prevents us from having misreporting of the context window before a chat is ever sent.
* eg: when viewing the attachments in the workspace - the context window would be misreported if a chat
* has not been sent yet.
*/
async function eagerLoadContextWindows() {
const currentProvider = process.env.LLM_PROVIDER;
const log = (provider) => {
console.log(`⚡\x1b[32mPre-cached context windows for ${provider}\x1b[0m`);
};
switch (currentProvider) {
case "lmstudio":
const { LMStudioLLM } = require("../AiProviders/lmStudio");
await LMStudioLLM.cacheContextWindows(true);
log("LMStudio");
break;
case "ollama":
const { OllamaAILLM } = require("../AiProviders/ollama");
await OllamaAILLM.cacheContextWindows(true);
log("Ollama");
break;
case "foundry":
const { FoundryLLM } = require("../AiProviders/foundry");
await FoundryLLM.cacheContextWindows(true);
log("Foundry");
break;
}
}
module.exports = eagerLoadContextWindows;
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/boot/index.js | server/utils/boot/index.js | const { Telemetry } = require("../../models/telemetry");
const { BackgroundService } = require("../BackgroundWorkers");
const { EncryptionManager } = require("../EncryptionManager");
const { CommunicationKey } = require("../comKey");
const setupTelemetry = require("../telemetry");
const eagerLoadContextWindows = require("./eagerLoadContextWindows");
// Testing SSL? You can make a self signed certificate and point the ENVs to that location
// make a directory in server called 'sslcert' - cd into it
// - openssl genrsa -aes256 -passout pass:gsahdg -out server.pass.key 4096
// - openssl rsa -passin pass:gsahdg -in server.pass.key -out server.key
// - rm server.pass.key
// - openssl req -new -key server.key -out server.csr
// Update .env keys with the correct values and boot. These are temporary and not real SSL certs - only use for local.
// Test with https://localhost:3001/api/ping
// build and copy frontend to server/public with correct API_BASE and start server in prod model and all should be ok
function bootSSL(app, port = 3001) {
try {
console.log(
`\x1b[33m[SSL BOOT ENABLED]\x1b[0m Loading the certificate and key for HTTPS mode...`
);
const fs = require("fs");
const https = require("https");
const privateKey = fs.readFileSync(process.env.HTTPS_KEY_PATH);
const certificate = fs.readFileSync(process.env.HTTPS_CERT_PATH);
const credentials = { key: privateKey, cert: certificate };
const server = https.createServer(credentials, app);
server
.listen(port, async () => {
await setupTelemetry();
new CommunicationKey(true);
new EncryptionManager();
new BackgroundService().boot();
await eagerLoadContextWindows();
console.log(`Primary server in HTTPS mode listening on port ${port}`);
})
.on("error", catchSigTerms);
require("@mintplex-labs/express-ws").default(app, server);
return { app, server };
} catch (e) {
console.error(
`\x1b[31m[SSL BOOT FAILED]\x1b[0m ${e.message} - falling back to HTTP boot.`,
{
ENABLE_HTTPS: process.env.ENABLE_HTTPS,
HTTPS_KEY_PATH: process.env.HTTPS_KEY_PATH,
HTTPS_CERT_PATH: process.env.HTTPS_CERT_PATH,
stacktrace: e.stack,
}
);
return bootHTTP(app, port);
}
}
function bootHTTP(app, port = 3001) {
if (!app) throw new Error('No "app" defined - crashing!');
app
.listen(port, async () => {
await setupTelemetry();
new CommunicationKey(true);
new EncryptionManager();
new BackgroundService().boot();
await eagerLoadContextWindows();
console.log(`Primary server in HTTP mode listening on port ${port}`);
})
.on("error", catchSigTerms);
return { app, server: null };
}
function catchSigTerms() {
process.once("SIGUSR2", function () {
Telemetry.flush();
process.kill(process.pid, "SIGUSR2");
});
process.on("SIGINT", function () {
Telemetry.flush();
process.kill(process.pid, "SIGINT");
});
}
module.exports = {
bootHTTP,
bootSSL,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/boot/MetaGenerator.js | server/utils/boot/MetaGenerator.js | /**
* @typedef MetaTagDefinition
* @property {('link'|'meta')} tag - the type of meta tag element
* @property {{string:string}|null} props - the inner key/values of a meta tag
* @property {string|null} content - Text content to be injected between tags. If null self-closing.
*/
/**
* This class serves the default index.html page that is not present when built in production.
* and therefore this class should not be called when in development mode since it is unused.
* All this class does is basically emulate SSR for the meta-tag generation of the root index page.
* Since we are an SPA, we can just render the primary page and the known entrypoints for the index.{js,css}
* we can always start at the right place and dynamically load in lazy-loaded as we typically normally would
* and we dont have any of the overhead that would normally come with having the rewrite the whole app in next or something.
* Lastly, this class is singleton, so once instantiate the same reference is shared for as long as the server is alive.
* the main function is `.generate()` which will return the index HTML. These settings are stored in the #customConfig
* static property and will not be reloaded until the page is loaded AND #customConfig is explicitly null. So anytime a setting
* for meta-props is updated you should get this singleton class and call `.clearConfig` so the next page load will show the new props.
*/
class MetaGenerator {
name = "MetaGenerator";
/** @type {MetaGenerator|null} */
static _instance = null;
/** @type {MetaTagDefinition[]|null} */
#customConfig = null;
#defaultManifest = {
name: "AnythingLLM",
short_name: "AnythingLLM",
display: "standalone",
orientation: "portrait",
start_url: "/",
icons: [
{
src: "/favicon.png",
sizes: "any",
},
],
};
constructor() {
if (MetaGenerator._instance) return MetaGenerator._instance;
MetaGenerator._instance = this;
}
#log(text, ...args) {
console.log(`\x1b[36m[${this.name}]\x1b[0m ${text}`, ...args);
}
#defaultMeta() {
return [
{
tag: "link",
props: { type: "image/svg+xml", href: "/favicon.png" },
content: null,
},
{
tag: "title",
props: null,
content: "AnythingLLM | Your personal LLM trained on anything",
},
{
tag: "meta",
props: {
name: "title",
content: "AnythingLLM | Your personal LLM trained on anything",
},
},
{
tag: "meta",
props: {
description: "title",
content: "AnythingLLM | Your personal LLM trained on anything",
},
},
// <!-- Facebook -->
{ tag: "meta", props: { property: "og:type", content: "website" } },
{
tag: "meta",
props: { property: "og:url", content: "https://anythingllm.com" },
},
{
tag: "meta",
props: {
property: "og:title",
content: "AnythingLLM | Your personal LLM trained on anything",
},
},
{
tag: "meta",
props: {
property: "og:description",
content: "AnythingLLM | Your personal LLM trained on anything",
},
},
{
tag: "meta",
props: {
property: "og:image",
content:
"https://raw.githubusercontent.com/Mintplex-Labs/anything-llm/master/images/promo.png",
},
},
// <!-- Twitter -->
{
tag: "meta",
props: { property: "twitter:card", content: "summary_large_image" },
},
{
tag: "meta",
props: { property: "twitter:url", content: "https://anythingllm.com" },
},
{
tag: "meta",
props: {
property: "twitter:title",
content: "AnythingLLM | Your personal LLM trained on anything",
},
},
{
tag: "meta",
props: {
property: "twitter:description",
content: "AnythingLLM | Your personal LLM trained on anything",
},
},
{
tag: "meta",
props: {
property: "twitter:image",
content:
"https://raw.githubusercontent.com/Mintplex-Labs/anything-llm/master/images/promo.png",
},
},
{ tag: "link", props: { rel: "icon", href: "/favicon.png" } },
{ tag: "link", props: { rel: "apple-touch-icon", href: "/favicon.png" } },
// PWA specific tags
{
tag: "meta",
props: { name: "mobile-web-app-capable", content: "yes" },
},
{
tag: "meta",
props: { name: "apple-mobile-web-app-capable", content: "yes" },
},
{
tag: "meta",
props: {
name: "apple-mobile-web-app-status-bar-style",
content: "black-translucent",
},
},
{ tag: "link", props: { rel: "manifest", href: "/manifest.json" } },
];
}
/**
* Assembles Meta tags as one large string
* @param {MetaTagDefinition[]} tagArray
* @returns {string}
*/
#assembleMeta() {
const output = [];
for (const tag of this.#customConfig) {
let htmlString;
htmlString = `<${tag.tag} `;
if (tag.props !== null) {
for (const [key, value] of Object.entries(tag.props))
htmlString += `${key}="${value}" `;
}
if (tag.content) {
htmlString += `>${tag.content}</${tag.tag}>`;
} else {
htmlString += `>`;
}
output.push(htmlString);
}
return output.join("\n");
}
#validUrl(faviconUrl = null) {
if (faviconUrl === null) return "/favicon.png";
try {
const url = new URL(faviconUrl);
return url.toString();
} catch {
return "/favicon.png";
}
}
async #fetchConfg() {
this.#log(`fetching custom meta tag settings...`);
const { SystemSettings } = require("../../models/systemSettings");
const customTitle = await SystemSettings.getValueOrFallback(
{ label: "meta_page_title" },
null
);
const faviconURL = await SystemSettings.getValueOrFallback(
{ label: "meta_page_favicon" },
null
);
// If nothing defined - assume defaults.
if (customTitle === null && faviconURL === null) {
this.#customConfig = this.#defaultMeta();
} else {
// When custom settings exist, include all default meta tags but override specific ones
this.#customConfig = this.#defaultMeta().map((tag) => {
// Override favicon link
if (tag.tag === "link" && tag.props?.rel === "icon") {
return {
tag: "link",
props: { rel: "icon", href: this.#validUrl(faviconURL) },
};
}
// Override page title
if (tag.tag === "title") {
return {
tag: "title",
props: null,
content:
customTitle ??
"AnythingLLM | Your personal LLM trained on anything",
};
}
// Override meta title
if (tag.tag === "meta" && tag.props?.name === "title") {
return {
tag: "meta",
props: {
name: "title",
content:
customTitle ??
"AnythingLLM | Your personal LLM trained on anything",
},
};
}
// Override og:title
if (tag.tag === "meta" && tag.props?.property === "og:title") {
return {
tag: "meta",
props: {
property: "og:title",
content:
customTitle ??
"AnythingLLM | Your personal LLM trained on anything",
},
};
}
// Override twitter:title
if (tag.tag === "meta" && tag.props?.property === "twitter:title") {
return {
tag: "meta",
props: {
property: "twitter:title",
content:
customTitle ??
"AnythingLLM | Your personal LLM trained on anything",
},
};
}
// Override apple-touch-icon if custom favicon is set
if (
tag.tag === "link" &&
tag.props?.rel === "apple-touch-icon" &&
faviconURL
) {
return {
tag: "link",
props: {
rel: "apple-touch-icon",
href: this.#validUrl(faviconURL),
},
};
}
// Return original tag for everything else (including PWA tags)
return tag;
});
}
return this.#customConfig;
}
/**
* Clears the current config so it can be refetched on the server for next render.
*/
clearConfig() {
this.#customConfig = null;
}
/**
*
* @param {import('express').Response} response
* @param {number} code
*/
async generate(response, code = 200) {
if (this.#customConfig === null) await this.#fetchConfg();
response.status(code).send(`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
${this.#assembleMeta()}
<script type="module" crossorigin src="/index.js"></script>
<link rel="stylesheet" href="/index.css">
</head>
<body>
<div id="root" class="h-screen"></div>
</body>
</html>`);
}
/**
* Generates the manifest.json file for the PWA application on the fly.
* @param {import('express').Response} response
* @param {number} code
*/
async generateManifest(response) {
try {
const { SystemSettings } = require("../../models/systemSettings");
const manifestName = await SystemSettings.getValueOrFallback(
{ label: "meta_page_title" },
"AnythingLLM"
);
const faviconURL = await SystemSettings.getValueOrFallback(
{ label: "meta_page_favicon" },
null
);
let iconUrl = "/favicon.png";
if (faviconURL) {
try {
new URL(faviconURL);
iconUrl = faviconURL;
} catch {
iconUrl = "/favicon.png";
}
}
const manifest = {
name: manifestName,
short_name: manifestName,
display: "standalone",
orientation: "portrait",
start_url: "/",
icons: [
{
src: iconUrl,
sizes: "any",
},
],
};
response.type("application/json").status(200).send(manifest).end();
} catch (error) {
this.#log(`error generating manifest: ${error.message}`, error);
response
.type("application/json")
.status(200)
.send(this.#defaultManifest)
.end();
}
}
}
module.exports.MetaGenerator = MetaGenerator;
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/database/index.js | server/utils/database/index.js | const { getGitVersion } = require("../../endpoints/utils");
const { Telemetry } = require("../../models/telemetry");
function checkColumnTemplate(tablename = null, column = null) {
if (!tablename || !column)
throw new Error(`Migration Error`, { tablename, column });
return `SELECT COUNT(*) AS _exists FROM pragma_table_info('${tablename}') WHERE name='${column}'`;
}
// Note (tcarambat): Since there is no good way to track migrations in Node/SQLite we use this simple system
// Each model has a `migrations` method that will return an array like...
// { colName: 'stringColName', execCmd: `SQL Command to run when`, doif: boolean },
// colName = name of column
// execCmd = Command to run when doif matches the state of the DB
// doif = condition to match that determines if execCmd will run.
// eg: Table workspace has slug column.
// execCmd: ALTER TABLE DROP COLUMN slug;
// doif: true
// => Will drop the slug column if the workspace table has a column named 'slug' otherwise nothing happens.
// If you are adding a new table column if needs to exist in the Models `colsInit` and as a migration.
// So both new and existing DBs will get the column when code is pulled in.
async function checkForMigrations(model, db) {
if (model.migrations().length === 0) return;
const toMigrate = [];
for (const { colName, execCmd, doif } of model.migrations()) {
const { _exists } = await db.get(
checkColumnTemplate(model.tablename, colName)
);
const colExists = _exists !== 0;
if (colExists !== doif) continue;
toMigrate.push(execCmd);
}
if (toMigrate.length === 0) return;
console.log(`Running ${toMigrate.length} migrations`, toMigrate);
await db.exec(toMigrate.join(";\n"));
return;
}
// Note(tcarambat): When building in production via Docker the SQLite file will not exist
// and if this function tries to run on boot the file will not exist
// and the server will abort and the container will exit.
// This function will run each reload on dev but on production
// it will be stubbed until the /api/migrate endpoint is GET.
async function validateTablePragmas(force = false) {
try {
if (process.env.NODE_ENV !== "development" && force === false) {
console.log(
`\x1b[34m[MIGRATIONS STUBBED]\x1b[0m Please ping /migrate once server starts to run migrations`
);
return;
}
const { SystemSettings } = require("../../models/systemSettings");
const { User } = require("../../models/user");
const { Workspace } = require("../../models/workspace");
const { WorkspaceUser } = require("../../models/workspaceUsers");
const { Document } = require("../../models/documents");
const { DocumentVectors } = require("../../models/vectors");
const { WorkspaceChats } = require("../../models/workspaceChats");
const { Invite } = require("../../models/invite");
const { WelcomeMessages } = require("../../models/welcomeMessages");
const { ApiKey } = require("../../models/apiKeys");
await SystemSettings.migrateTable();
await User.migrateTable();
await Workspace.migrateTable();
await WorkspaceUser.migrateTable();
await Document.migrateTable();
await DocumentVectors.migrateTable();
await WorkspaceChats.migrateTable();
await Invite.migrateTable();
await WelcomeMessages.migrateTable();
await ApiKey.migrateTable();
} catch (e) {
console.error(`validateTablePragmas: Migrations failed`, e);
}
return;
}
// Telemetry is anonymized and your data is never read. This can be disabled by setting
// DISABLE_TELEMETRY=true in the `.env` of however you setup. Telemetry helps us determine use
// of how AnythingLLM is used and how to improve this product!
// You can see all Telemetry events by ctrl+f `Telemetry.sendTelemetry` calls to verify this claim.
async function setupTelemetry() {
if (process.env.DISABLE_TELEMETRY === "true") {
console.log(
`\x1b[31m[TELEMETRY DISABLED]\x1b[0m Telemetry is marked as disabled - no events will send. Telemetry helps Mintplex Labs Inc improve AnythingLLM.`
);
return true;
}
if (Telemetry.isDev()) {
console.log(
`\x1b[33m[TELEMETRY STUBBED]\x1b[0m Anonymous Telemetry stubbed in development.`
);
return;
}
console.log(
`\x1b[32m[TELEMETRY ENABLED]\x1b[0m Anonymous Telemetry enabled. Telemetry helps Mintplex Labs Inc improve AnythingLLM.`
);
await Telemetry.findOrCreateId();
await Telemetry.sendTelemetry("server_boot", {
commit: getGitVersion(),
});
return;
}
module.exports = {
checkForMigrations,
validateTablePragmas,
setupTelemetry,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/collectorApi/index.js | server/utils/collectorApi/index.js | const { EncryptionManager } = require("../EncryptionManager");
const { Agent } = require("undici");
/**
* @typedef {Object} CollectorOptions
* @property {string} whisperProvider - The provider to use for whisper, defaults to "local"
* @property {string} WhisperModelPref - The model to use for whisper if set.
* @property {string} openAiKey - The API key to use for OpenAI interfacing, mostly passed to OAI Whisper provider.
* @property {Object} ocr - The OCR options
* @property {{allowAnyIp: "true"|null|undefined}} runtimeSettings - The runtime settings that are passed to the collector. Persisted across requests.
*/
// When running locally will occupy the 0.0.0.0 hostname space but when deployed inside
// of docker this endpoint is not exposed so it is only on the Docker instances internal network
// so no additional security is needed on the endpoint directly. Auth is done however by the express
// middleware prior to leaving the node-side of the application so that is good enough >:)
class CollectorApi {
/** @type {number} - The maximum timeout for extension requests in milliseconds */
extensionRequestTimeout = 15 * 60_000; // 15 minutes
/** @type {Agent} - The agent for extension requests */
extensionRequestAgent = new Agent({
headersTimeout: this.extensionRequestTimeout,
bodyTimeout: this.extensionRequestTimeout,
});
constructor() {
const { CommunicationKey } = require("../comKey");
this.comkey = new CommunicationKey();
this.endpoint = `http://0.0.0.0:${process.env.COLLECTOR_PORT || 8888}`;
}
log(text, ...args) {
console.log(`\x1b[36m[CollectorApi]\x1b[0m ${text}`, ...args);
}
/**
* Attach options to the request passed to the collector API
* @returns {CollectorOptions}
*/
#attachOptions() {
return {
whisperProvider: process.env.WHISPER_PROVIDER || "local",
WhisperModelPref: process.env.WHISPER_MODEL_PREF,
openAiKey: process.env.OPEN_AI_KEY || null,
ocr: {
langList: process.env.TARGET_OCR_LANG || "eng",
},
runtimeSettings: {
allowAnyIp: process.env.COLLECTOR_ALLOW_ANY_IP ?? "false",
browserLaunchArgs: process.env.ANYTHINGLLM_CHROMIUM_ARGS ?? [],
},
};
}
async online() {
return await fetch(this.endpoint)
.then((res) => res.ok)
.catch(() => false);
}
async acceptedFileTypes() {
return await fetch(`${this.endpoint}/accepts`)
.then((res) => {
if (!res.ok) throw new Error("failed to GET /accepts");
return res.json();
})
.then((res) => res)
.catch((e) => {
this.log(e.message);
return null;
});
}
/**
* Process a document
* - Will append the options and optional metadata to the request body
* @param {string} filename - The filename of the document to process
* @param {Object} metadata - Optional metadata key:value pairs
* @returns {Promise<Object>} - The response from the collector API
*/
async processDocument(filename = "", metadata = {}) {
if (!filename) return false;
const data = JSON.stringify({
filename,
metadata,
options: this.#attachOptions(),
});
return await fetch(`${this.endpoint}/process`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Integrity": this.comkey.sign(data),
"X-Payload-Signer": this.comkey.encrypt(
new EncryptionManager().xPayload
),
},
body: data,
dispatcher: new Agent({ headersTimeout: 600000 }),
})
.then((res) => {
if (!res.ok) throw new Error("Response could not be completed");
return res.json();
})
.then((res) => res)
.catch((e) => {
this.log(e.message);
return { success: false, reason: e.message, documents: [] };
});
}
/**
* Process a link
* - Will append the options to the request body
* @param {string} link - The link to process
* @param {{[key: string]: string}} scraperHeaders - Custom headers to apply to the web-scraping request URL
* @param {[key: string]: string} metadata - Optional metadata to attach to the document
* @returns {Promise<Object>} - The response from the collector API
*/
async processLink(link = "", scraperHeaders = {}, metadata = {}) {
if (!link) return false;
const data = JSON.stringify({
link,
scraperHeaders,
options: this.#attachOptions(),
metadata: metadata,
});
return await fetch(`${this.endpoint}/process-link`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Integrity": this.comkey.sign(data),
"X-Payload-Signer": this.comkey.encrypt(
new EncryptionManager().xPayload
),
},
body: data,
})
.then((res) => {
if (!res.ok) throw new Error("Response could not be completed");
return res.json();
})
.then((res) => res)
.catch((e) => {
this.log(e.message);
return { success: false, reason: e.message, documents: [] };
});
}
/**
* Process raw text as a document for the collector
* - Will append the options to the request body
* @param {string} textContent - The text to process
* @param {[key: string]: string} metadata - The metadata to process
* @returns {Promise<Object>} - The response from the collector API
*/
async processRawText(textContent = "", metadata = {}) {
const data = JSON.stringify({
textContent,
metadata,
options: this.#attachOptions(),
});
return await fetch(`${this.endpoint}/process-raw-text`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Integrity": this.comkey.sign(data),
"X-Payload-Signer": this.comkey.encrypt(
new EncryptionManager().xPayload
),
},
body: data,
})
.then((res) => {
if (!res.ok) throw new Error("Response could not be completed");
return res.json();
})
.then((res) => res)
.catch((e) => {
this.log(e.message);
return { success: false, reason: e.message, documents: [] };
});
}
// We will not ever expose the document processor to the frontend API so instead we relay
// all requests through the server. You can use this function to directly expose a specific endpoint
// on the document processor.
async forwardExtensionRequest({ endpoint, method, body }) {
const data = typeof body === "string" ? body : JSON.stringify(body);
return await fetch(`${this.endpoint}${endpoint}`, {
method,
body: data,
headers: {
"Content-Type": "application/json",
"X-Integrity": this.comkey.sign(data),
"X-Payload-Signer": this.comkey.encrypt(
new EncryptionManager().xPayload
),
},
// Extensions do a lot of work, and may take a while to complete so we need to increase the timeout
// substantially so that they do not show a failure to the user early.
dispatcher: this.extensionRequestAgent,
})
.then((res) => {
if (!res.ok) throw new Error("Response could not be completed");
return res.json();
})
.then((res) => res)
.catch((e) => {
this.log(e.message);
return { success: false, data: {}, reason: e.message };
});
}
/**
* Get the content of a link only in a specific format
* - Will append the options to the request body
* @param {string} link - The link to get the content of
* @param {"text"|"html"} captureAs - The format to capture the content as
* @returns {Promise<Object>} - The response from the collector API
*/
async getLinkContent(link = "", captureAs = "text") {
if (!link) return false;
const data = JSON.stringify({
link,
captureAs,
options: this.#attachOptions(),
});
return await fetch(`${this.endpoint}/util/get-link`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Integrity": this.comkey.sign(data),
"X-Payload-Signer": this.comkey.encrypt(
new EncryptionManager().xPayload
),
},
body: data,
})
.then((res) => {
if (!res.ok) throw new Error("Response could not be completed");
return res.json();
})
.then((res) => res)
.catch((e) => {
this.log(e.message);
return { success: false, content: null };
});
}
/**
* Parse a document without processing it
* - Will append the options to the request body
* @param {string} filename - The filename of the document to parse
* @returns {Promise<Object>} - The response from the collector API
*/
async parseDocument(filename = "") {
if (!filename) return false;
const data = JSON.stringify({
filename,
options: this.#attachOptions(),
});
return await fetch(`${this.endpoint}/parse`, {
method: "POST",
headers: {
"Content-Type": "application/json",
"X-Integrity": this.comkey.sign(data),
"X-Payload-Signer": this.comkey.encrypt(
new EncryptionManager().xPayload
),
},
body: data,
})
.then((res) => {
if (!res.ok) throw new Error("Response could not be completed");
return res.json();
})
.then((res) => res)
.catch((e) => {
this.log(e.message);
return { success: false, reason: e.message, documents: [] };
});
}
}
module.exports.CollectorApi = CollectorApi;
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/native/index.js | server/utils/EmbeddingEngines/native/index.js | const path = require("path");
const fs = require("fs");
const { toChunks } = require("../../helpers");
const { v4 } = require("uuid");
const { SUPPORTED_NATIVE_EMBEDDING_MODELS } = require("./constants");
class NativeEmbedder {
static defaultModel = "Xenova/all-MiniLM-L6-v2";
/**
* Supported embedding models for native.
* @type {Record<string, {
* chunkPrefix: string;
* queryPrefix: string;
* apiInfo: {
* id: string;
* name: string;
* description: string;
* lang: string;
* size: string;
* modelCard: string;
* };
* }>}
*/
static supportedModels = SUPPORTED_NATIVE_EMBEDDING_MODELS;
// This is a folder that Mintplex Labs hosts for those who cannot capture the HF model download
// endpoint for various reasons. This endpoint is not guaranteed to be active or maintained
// and may go offline at any time at Mintplex Labs's discretion.
#fallbackHost = "https://cdn.anythingllm.com/support/models/";
constructor() {
this.className = "NativeEmbedder";
this.model = this.getEmbeddingModel();
this.modelInfo = this.getEmbedderInfo();
this.cacheDir = path.resolve(
process.env.STORAGE_DIR
? path.resolve(process.env.STORAGE_DIR, `models`)
: path.resolve(__dirname, `../../../storage/models`)
);
this.modelPath = path.resolve(this.cacheDir, ...this.model.split("/"));
this.modelDownloaded = fs.existsSync(this.modelPath);
// Limit of how many strings we can process in a single pass to stay with resource or network limits
this.maxConcurrentChunks = this.modelInfo.maxConcurrentChunks;
this.embeddingMaxChunkLength = this.modelInfo.embeddingMaxChunkLength;
// Make directory when it does not exist in existing installations
if (!fs.existsSync(this.cacheDir)) fs.mkdirSync(this.cacheDir);
this.log(`Initialized ${this.model}`);
}
log(text, ...args) {
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
}
/**
* Get the selected model from the environment variable.
* @returns {string}
*/
static _getEmbeddingModel() {
const envModel =
process.env.EMBEDDING_MODEL_PREF ?? NativeEmbedder.defaultModel;
if (NativeEmbedder.supportedModels?.[envModel]) return envModel;
return NativeEmbedder.defaultModel;
}
get embeddingPrefix() {
return NativeEmbedder.supportedModels[this.model]?.chunkPrefix || "";
}
get queryPrefix() {
return NativeEmbedder.supportedModels[this.model]?.queryPrefix || "";
}
/**
* Get the available models in an API response format
* we can use to populate the frontend dropdown.
* @returns {{id: string, name: string, description: string, lang: string, size: string, modelCard: string}[]}
*/
static availableModels() {
return Object.values(NativeEmbedder.supportedModels).map(
(model) => model.apiInfo
);
}
/**
* Get the embedding model to use.
* We only support a few models and will default to the default model if the environment variable is not set or not supported.
*
* Why only a few? Because we need to mirror them on the CDN so non-US users can download them.
* eg: "Xenova/all-MiniLM-L6-v2"
* eg: "Xenova/nomic-embed-text-v1"
* @returns {string}
*/
getEmbeddingModel() {
const envModel =
process.env.EMBEDDING_MODEL_PREF ?? NativeEmbedder.defaultModel;
if (NativeEmbedder.supportedModels?.[envModel]) return envModel;
return NativeEmbedder.defaultModel;
}
/**
* Get the embedding model info.
*
* Will always fallback to the default model if the model is not supported.
* @returns {Object}
*/
getEmbedderInfo() {
const model = this.getEmbeddingModel();
return NativeEmbedder.supportedModels[model];
}
#tempfilePath() {
const filename = `${v4()}.tmp`;
const tmpPath = process.env.STORAGE_DIR
? path.resolve(process.env.STORAGE_DIR, "tmp")
: path.resolve(__dirname, `../../../storage/tmp`);
if (!fs.existsSync(tmpPath)) fs.mkdirSync(tmpPath, { recursive: true });
return path.resolve(tmpPath, filename);
}
async #writeToTempfile(filePath, data) {
try {
await fs.promises.appendFile(filePath, data, { encoding: "utf8" });
} catch (e) {
console.error(`Error writing to tempfile: ${e}`);
}
}
async #fetchWithHost(hostOverride = null) {
try {
// Convert ESM to CommonJS via import so we can load this library.
const pipeline = (...args) =>
import("@xenova/transformers").then(({ pipeline, env }) => {
if (!this.modelDownloaded) {
// if model is not downloaded, we will log where we are fetching from.
if (hostOverride) {
env.remoteHost = hostOverride;
env.remotePathTemplate = "{model}/"; // Our S3 fallback url does not support revision File structure.
}
this.log(`Downloading ${this.model} from ${env.remoteHost}`);
}
return pipeline(...args);
});
return {
pipeline: await pipeline("feature-extraction", this.model, {
cache_dir: this.cacheDir,
...(!this.modelDownloaded
? {
// Show download progress if we need to download any files
progress_callback: (data) => {
if (!data.hasOwnProperty("progress")) return;
console.log(
`\x1b[36m[NativeEmbedder - Downloading model]\x1b[0m ${
data.file
} ${~~data?.progress}%`
);
},
}
: {}),
}),
retry: false,
error: null,
};
} catch (error) {
return {
pipeline: null,
retry: hostOverride === null ? this.#fallbackHost : false,
error,
};
}
}
// This function will do a single fallback attempt (not recursive on purpose) to try to grab the embedder model on first embed
// since at time, some clients cannot properly download the model from HF servers due to a number of reasons (IP, VPN, etc).
// Given this model is critical and nobody reads the GitHub issues before submitting the bug, we get the same bug
// report 20 times a day: https://github.com/Mintplex-Labs/anything-llm/issues/821
// So to attempt to monkey-patch this we have a single fallback URL to help alleviate duplicate bug reports.
async embedderClient() {
if (!this.modelDownloaded)
this.log(
"The native embedding model has never been run and will be downloaded right now. Subsequent runs will be faster. (~23MB)"
);
let fetchResponse = await this.#fetchWithHost();
if (fetchResponse.pipeline !== null) {
this.modelDownloaded = true;
return fetchResponse.pipeline;
}
this.log(
`Failed to download model from primary URL. Using fallback ${fetchResponse.retry}`
);
if (!!fetchResponse.retry)
fetchResponse = await this.#fetchWithHost(fetchResponse.retry);
if (fetchResponse.pipeline !== null) {
this.modelDownloaded = true;
return fetchResponse.pipeline;
}
throw fetchResponse.error;
}
/**
* Apply the query prefix to the text input if it is required by the model.
* eg: nomic-embed-text-v1 requires a query prefix for embedding/searching.
* @param {string|string[]} textInput - The text to embed.
* @returns {string|string[]} The text with the prefix applied.
*/
#applyQueryPrefix(textInput) {
if (!this.queryPrefix) return textInput;
if (Array.isArray(textInput))
textInput = textInput.map((text) => `${this.queryPrefix}${text}`);
else textInput = `${this.queryPrefix}${textInput}`;
return textInput;
}
/**
* Embed a single text input.
* @param {string|string[]} textInput - The text to embed.
* @returns {Promise<Array<number>>} The embedded text.
*/
async embedTextInput(textInput) {
textInput = this.#applyQueryPrefix(textInput);
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
// If you are thinking you want to edit this function - you probably don't.
// This process was benchmarked heavily on a t3.small (2GB RAM 1vCPU)
// and without careful memory management for the V8 garbage collector
// this function will likely result in an OOM on any resource-constrained deployment.
// To help manage very large documents we run a concurrent write-log each iteration
// to keep the embedding result out of memory. The `maxConcurrentChunk` is set to 25,
// as 50 seems to overflow no matter what. Given the above, memory use hovers around ~30%
// during a very large document (>100K words) but can spike up to 70% before gc.
// This seems repeatable for all document sizes.
// While this does take a while, it is zero set up and is 100% free and on-instance.
// It still may crash depending on other elements at play - so no promises it works under all conditions.
async embedChunks(textChunks = []) {
const tmpFilePath = this.#tempfilePath();
const chunks = toChunks(textChunks, this.maxConcurrentChunks);
const chunkLen = chunks.length;
for (let [idx, chunk] of chunks.entries()) {
if (idx === 0) await this.#writeToTempfile(tmpFilePath, "[");
let data;
let pipeline = await this.embedderClient();
let output = await pipeline(chunk, {
pooling: "mean",
normalize: true,
});
if (output.length === 0) {
pipeline = null;
output = null;
data = null;
continue;
}
data = JSON.stringify(output.tolist());
await this.#writeToTempfile(tmpFilePath, data);
this.log(`Embedded Chunk Group ${idx + 1} of ${chunkLen}`);
if (chunkLen - 1 !== idx) await this.#writeToTempfile(tmpFilePath, ",");
if (chunkLen - 1 === idx) await this.#writeToTempfile(tmpFilePath, "]");
pipeline = null;
output = null;
data = null;
}
const embeddingResults = JSON.parse(
fs.readFileSync(tmpFilePath, { encoding: "utf-8" })
);
fs.rmSync(tmpFilePath, { force: true });
return embeddingResults.length > 0 ? embeddingResults.flat() : null;
}
}
module.exports = {
NativeEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/native/constants.js | server/utils/EmbeddingEngines/native/constants.js | const SUPPORTED_NATIVE_EMBEDDING_MODELS = {
"Xenova/all-MiniLM-L6-v2": {
maxConcurrentChunks: 25,
// Right now, this is NOT the token length, and is instead the number of characters
// that can be processed in a single pass. So we override to 1,000 characters.
// roughtly the max number of tokens assuming 2 characters per token. (undershooting)
// embeddingMaxChunkLength: 512, (from the model card)
embeddingMaxChunkLength: 1_000,
chunkPrefix: "",
queryPrefix: "",
apiInfo: {
id: "Xenova/all-MiniLM-L6-v2",
name: "all-MiniLM-L6-v2",
description:
"A lightweight and fast model for embedding text. The default model for AnythingLLM.",
lang: "English",
size: "23MB",
modelCard: "https://huggingface.co/Xenova/all-MiniLM-L6-v2",
},
},
"Xenova/nomic-embed-text-v1": {
maxConcurrentChunks: 5,
// Right now, this is NOT the token length, and is instead the number of characters
// that can be processed in a single pass. So we override to 16,000 characters.
// roughtly the max number of tokens assuming 2 characters per token. (undershooting)
// embeddingMaxChunkLength: 8192, (from the model card)
embeddingMaxChunkLength: 16_000,
chunkPrefix: "search_document: ",
queryPrefix: "search_query: ",
apiInfo: {
id: "Xenova/nomic-embed-text-v1",
name: "nomic-embed-text-v1",
description:
"A high-performing open embedding model with a large token context window. Requires more processing power and memory.",
lang: "English",
size: "139MB",
modelCard: "https://huggingface.co/Xenova/nomic-embed-text-v1",
},
},
"MintplexLabs/multilingual-e5-small": {
maxConcurrentChunks: 5,
// Right now, this is NOT the token length, and is instead the number of characters
// that can be processed in a single pass. So we override to 1,000 characters.
// roughtly the max number of tokens assuming 2 characters per token. (undershooting)
// embeddingMaxChunkLength: 512, (from the model card)
embeddingMaxChunkLength: 1_000,
chunkPrefix: "passage: ",
queryPrefix: "query: ",
apiInfo: {
id: "MintplexLabs/multilingual-e5-small",
name: "multilingual-e5-small",
description:
"A larger multilingual embedding model that supports 100+ languages. Requires more processing power and memory.",
lang: "100+ languages",
size: "487MB",
modelCard: "https://huggingface.co/intfloat/multilingual-e5-small",
},
},
};
module.exports = {
SUPPORTED_NATIVE_EMBEDDING_MODELS,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/cohere/index.js | server/utils/EmbeddingEngines/cohere/index.js | const { toChunks } = require("../../helpers");
class CohereEmbedder {
constructor() {
if (!process.env.COHERE_API_KEY)
throw new Error("No Cohere API key was set.");
const { CohereClient } = require("cohere-ai");
const cohere = new CohereClient({
token: process.env.COHERE_API_KEY,
});
this.cohere = cohere;
this.model = process.env.EMBEDDING_MODEL_PREF || "embed-english-v3.0";
this.inputType = "search_document";
// Limit of how many strings we can process in a single pass to stay with resource or network limits
this.maxConcurrentChunks = 96; // Cohere's limit per request is 96
this.embeddingMaxChunkLength = 1945; // https://docs.cohere.com/docs/embed-2 - assume a token is roughly 4 letters with some padding
}
async embedTextInput(textInput) {
this.inputType = "search_query";
const result = await this.embedChunks([textInput]);
return result?.[0] || [];
}
async embedChunks(textChunks = []) {
const embeddingRequests = [];
this.inputType = "search_document";
for (const chunk of toChunks(textChunks, this.maxConcurrentChunks)) {
embeddingRequests.push(
new Promise((resolve) => {
this.cohere
.embed({
texts: chunk,
model: this.model,
inputType: this.inputType,
})
.then((res) => {
resolve({ data: res.embeddings, error: null });
})
.catch((e) => {
e.type =
e?.response?.data?.error?.code ||
e?.response?.status ||
"failed_to_embed";
e.message = e?.response?.data?.error?.message || e.message;
resolve({ data: [], error: e });
});
})
);
}
const { data = [], error = null } = await Promise.all(
embeddingRequests
).then((results) => {
const errors = results
.filter((res) => !!res.error)
.map((res) => res.error)
.flat();
if (errors.length > 0) {
let uniqueErrors = new Set();
errors.map((error) =>
uniqueErrors.add(`[${error.type}]: ${error.message}`)
);
return { data: [], error: Array.from(uniqueErrors).join(", ") };
}
return {
data: results.map((res) => res?.data || []).flat(),
error: null,
};
});
if (!!error) throw new Error(`Cohere Failed to embed: ${error}`);
return data.length > 0 ? data : null;
}
}
module.exports = {
CohereEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/lmstudio/index.js | server/utils/EmbeddingEngines/lmstudio/index.js | const { parseLMStudioBasePath } = require("../../AiProviders/lmStudio");
const { maximumChunkLength } = require("../../helpers");
class LMStudioEmbedder {
constructor() {
if (!process.env.EMBEDDING_BASE_PATH)
throw new Error("No embedding base path was set.");
if (!process.env.EMBEDDING_MODEL_PREF)
throw new Error("No embedding model was set.");
this.className = "LMStudioEmbedder";
const { OpenAI: OpenAIApi } = require("openai");
this.lmstudio = new OpenAIApi({
baseURL: parseLMStudioBasePath(process.env.EMBEDDING_BASE_PATH),
apiKey: null,
});
this.model = process.env.EMBEDDING_MODEL_PREF;
// Limit of how many strings we can process in a single pass to stay with resource or network limits
this.maxConcurrentChunks = 1;
this.embeddingMaxChunkLength = maximumChunkLength();
}
log(text, ...args) {
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
}
async #isAlive() {
return await this.lmstudio.models
.list()
.then((res) => res?.data?.length > 0)
.catch((e) => {
this.log(e.message);
return false;
});
}
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
async embedChunks(textChunks = []) {
if (!(await this.#isAlive()))
throw new Error(
`LMStudio service could not be reached. Is LMStudio running?`
);
this.log(
`Embedding ${textChunks.length} chunks of text with ${this.model}.`
);
// LMStudio will drop all queued requests now? So if there are many going on
// we need to do them sequentially or else only the first resolves and the others
// get dropped or go unanswered >:(
let results = [];
let hasError = false;
for (const chunk of textChunks) {
if (hasError) break; // If an error occurred don't continue and exit early.
results.push(
await this.lmstudio.embeddings
.create({
model: this.model,
input: chunk,
encoding_format: "base64",
})
.then((result) => {
const embedding = result.data?.[0]?.embedding;
if (!Array.isArray(embedding) || !embedding.length)
throw {
type: "EMPTY_ARR",
message: "The embedding was empty from LMStudio",
};
console.log(`Embedding length: ${embedding.length}`);
return { data: embedding, error: null };
})
.catch((e) => {
e.type =
e?.response?.data?.error?.code ||
e?.response?.status ||
"failed_to_embed";
e.message = e?.response?.data?.error?.message || e.message;
hasError = true;
return { data: [], error: e };
})
);
}
// Accumulate errors from embedding.
// If any are present throw an abort error.
const errors = results
.filter((res) => !!res.error)
.map((res) => res.error)
.flat();
if (errors.length > 0) {
let uniqueErrors = new Set();
console.log(errors);
errors.map((error) =>
uniqueErrors.add(`[${error.type}]: ${error.message}`)
);
if (errors.length > 0)
throw new Error(
`LMStudio Failed to embed: ${Array.from(uniqueErrors).join(", ")}`
);
}
const data = results.map((res) => res?.data || []);
return data.length > 0 ? data : null;
}
}
module.exports = {
LMStudioEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/localAi/index.js | server/utils/EmbeddingEngines/localAi/index.js | const { toChunks, maximumChunkLength } = require("../../helpers");
class LocalAiEmbedder {
constructor() {
if (!process.env.EMBEDDING_BASE_PATH)
throw new Error("No embedding base path was set.");
if (!process.env.EMBEDDING_MODEL_PREF)
throw new Error("No embedding model was set.");
const { OpenAI: OpenAIApi } = require("openai");
this.openai = new OpenAIApi({
baseURL: process.env.EMBEDDING_BASE_PATH,
apiKey: process.env.LOCAL_AI_API_KEY ?? null,
});
// Limit of how many strings we can process in a single pass to stay with resource or network limits
this.maxConcurrentChunks = 50;
this.embeddingMaxChunkLength = maximumChunkLength();
}
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
async embedChunks(textChunks = []) {
const embeddingRequests = [];
for (const chunk of toChunks(textChunks, this.maxConcurrentChunks)) {
embeddingRequests.push(
new Promise((resolve) => {
this.openai.embeddings
.create({
model: process.env.EMBEDDING_MODEL_PREF,
input: chunk,
})
.then((result) => {
resolve({ data: result?.data, error: null });
})
.catch((e) => {
e.type =
e?.response?.data?.error?.code ||
e?.response?.status ||
"failed_to_embed";
e.message = e?.response?.data?.error?.message || e.message;
resolve({ data: [], error: e });
});
})
);
}
const { data = [], error = null } = await Promise.all(
embeddingRequests
).then((results) => {
// If any errors were returned from LocalAI abort the entire sequence because the embeddings
// will be incomplete.
const errors = results
.filter((res) => !!res.error)
.map((res) => res.error)
.flat();
if (errors.length > 0) {
let uniqueErrors = new Set();
errors.map((error) =>
uniqueErrors.add(`[${error.type}]: ${error.message}`)
);
return {
data: [],
error: Array.from(uniqueErrors).join(", "),
};
}
return {
data: results.map((res) => res?.data || []).flat(),
error: null,
};
});
if (!!error) throw new Error(`LocalAI Failed to embed: ${error}`);
return data.length > 0 &&
data.every((embd) => embd.hasOwnProperty("embedding"))
? data.map((embd) => embd.embedding)
: null;
}
}
module.exports = {
LocalAiEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/genericOpenAi/index.js | server/utils/EmbeddingEngines/genericOpenAi/index.js | const { toChunks, maximumChunkLength } = require("../../helpers");
class GenericOpenAiEmbedder {
constructor() {
if (!process.env.EMBEDDING_BASE_PATH)
throw new Error(
"GenericOpenAI must have a valid base path to use for the api."
);
this.className = "GenericOpenAiEmbedder";
const { OpenAI: OpenAIApi } = require("openai");
this.basePath = process.env.EMBEDDING_BASE_PATH;
this.openai = new OpenAIApi({
baseURL: this.basePath,
apiKey: process.env.GENERIC_OPEN_AI_EMBEDDING_API_KEY ?? null,
});
this.model = process.env.EMBEDDING_MODEL_PREF ?? null;
this.embeddingMaxChunkLength = maximumChunkLength();
// this.maxConcurrentChunks is delegated to the getter below.
// Refer to your specific model and provider you use this class with to determine a valid maxChunkLength
this.log(`Initialized ${this.model}`, {
baseURL: this.basePath,
maxConcurrentChunks: this.maxConcurrentChunks,
embeddingMaxChunkLength: this.embeddingMaxChunkLength,
});
}
log(text, ...args) {
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
}
/**
* returns the `GENERIC_OPEN_AI_EMBEDDING_API_DELAY_MS` env variable as a number or null if the env variable is not set or is not a number.
* The minimum delay is 500ms.
*
* For some implementation this is necessary to avoid 429 errors due to rate limiting or
* hardware limitations where a single-threaded process is not able to handle the requests fast enough.
* @returns {number}
*/
get apiRequestDelay() {
if (!("GENERIC_OPEN_AI_EMBEDDING_API_DELAY_MS" in process.env)) return null;
if (isNaN(Number(process.env.GENERIC_OPEN_AI_EMBEDDING_API_DELAY_MS)))
return null;
const delayTimeout = Number(
process.env.GENERIC_OPEN_AI_EMBEDDING_API_DELAY_MS
);
if (delayTimeout < 500) return 500; // minimum delay of 500ms
return delayTimeout;
}
/**
* runs the delay if it is set and valid.
* @returns {Promise<void>}
*/
async runDelay() {
if (!this.apiRequestDelay) return;
this.log(`Delaying new batch request for ${this.apiRequestDelay}ms`);
await new Promise((resolve) => setTimeout(resolve, this.apiRequestDelay));
}
/**
* returns the `GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS` env variable as a number
* or 500 if the env variable is not set or is not a number.
* @returns {number}
*/
get maxConcurrentChunks() {
if (!process.env.GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS)
return 500;
if (
isNaN(Number(process.env.GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS))
)
return 500;
return Number(process.env.GENERIC_OPEN_AI_EMBEDDING_MAX_CONCURRENT_CHUNKS);
}
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
async embedChunks(textChunks = []) {
// Because there is a hard POST limit on how many chunks can be sent at once to OpenAI (~8mb)
// we sequentially execute each max batch of text chunks possible.
// Refer to constructor maxConcurrentChunks for more info.
const allResults = [];
for (const chunk of toChunks(textChunks, this.maxConcurrentChunks)) {
const { data = [], error = null } = await new Promise((resolve) => {
this.openai.embeddings
.create({
model: this.model,
input: chunk,
})
.then((result) => resolve({ data: result?.data, error: null }))
.catch((e) => {
e.type =
e?.response?.data?.error?.code ||
e?.response?.status ||
"failed_to_embed";
e.message = e?.response?.data?.error?.message || e.message;
resolve({ data: [], error: e });
});
});
// If any errors were returned from OpenAI abort the entire sequence because the embeddings
// will be incomplete.
if (error)
throw new Error(`GenericOpenAI Failed to embed: ${error.message}`);
allResults.push(...(data || []));
if (this.apiRequestDelay) await this.runDelay();
}
return allResults.length > 0 &&
allResults.every((embd) => embd.hasOwnProperty("embedding"))
? allResults.map((embd) => embd.embedding)
: null;
}
}
module.exports = {
GenericOpenAiEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/openRouter/index.js | server/utils/EmbeddingEngines/openRouter/index.js | const { toChunks } = require("../../helpers");
class OpenRouterEmbedder {
constructor() {
if (!process.env.OPENROUTER_API_KEY)
throw new Error("No OpenRouter API key was set.");
this.className = "OpenRouterEmbedder";
const { OpenAI: OpenAIApi } = require("openai");
this.openai = new OpenAIApi({
baseURL: "https://openrouter.ai/api/v1",
apiKey: process.env.OPENROUTER_API_KEY,
defaultHeaders: {
"HTTP-Referer": "https://anythingllm.com",
"X-Title": "AnythingLLM",
},
});
this.model = process.env.EMBEDDING_MODEL_PREF || "baai/bge-m3";
// Limit of how many strings we can process in a single pass to stay with resource or network limits
this.maxConcurrentChunks = 500;
// https://openrouter.ai/docs/api/reference/embeddings
this.embeddingMaxChunkLength = 8_191;
}
log(text, ...args) {
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
}
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
async embedChunks(textChunks = []) {
this.log(`Embedding ${textChunks.length} document chunks...`);
const embeddingRequests = [];
for (const chunk of toChunks(textChunks, this.maxConcurrentChunks)) {
embeddingRequests.push(
new Promise((resolve) => {
this.openai.embeddings
.create({
model: this.model,
input: chunk,
})
.then((result) => {
resolve({ data: result?.data, error: null });
})
.catch((e) => {
e.type =
e?.response?.data?.error?.code ||
e?.response?.status ||
"failed_to_embed";
e.message = e?.response?.data?.error?.message || e.message;
resolve({ data: [], error: e });
});
})
);
}
const { data = [], error = null } = await Promise.all(
embeddingRequests
).then((results) => {
// If any errors were returned from OpenAI abort the entire sequence because the embeddings
// will be incomplete.
const errors = results
.filter((res) => !!res.error)
.map((res) => res.error)
.flat();
if (errors.length > 0) {
let uniqueErrors = new Set();
errors.map((error) =>
uniqueErrors.add(`[${error.type}]: ${error.message}`)
);
return {
data: [],
error: Array.from(uniqueErrors).join(", "),
};
}
return {
data: results.map((res) => res?.data || []).flat(),
error: null,
};
});
if (!!error) throw new Error(`OpenRouter Failed to embed: ${error}`);
return data.length > 0 &&
data.every((embd) => embd.hasOwnProperty("embedding"))
? data.map((embd) => embd.embedding)
: null;
}
}
async function fetchOpenRouterEmbeddingModels() {
return await fetch(`https://openrouter.ai/api/v1/embeddings/models`, {
method: "GET",
headers: { "Content-Type": "application/json" },
})
.then((res) => res.json())
.then(({ data = [] }) => {
const models = {};
data.forEach((model) => {
models[model.id] = {
id: model.id,
name: model.name || model.id,
organization:
model.id.split("/")[0].charAt(0).toUpperCase() +
model.id.split("/")[0].slice(1),
maxLength: model.context_length,
};
});
return models;
})
.catch((e) => {
console.error("OpenRouter:fetchEmbeddingModels", e.message);
return {};
});
}
module.exports = {
OpenRouterEmbedder,
fetchOpenRouterEmbeddingModels,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/liteLLM/index.js | server/utils/EmbeddingEngines/liteLLM/index.js | const { toChunks, maximumChunkLength } = require("../../helpers");
class LiteLLMEmbedder {
constructor() {
const { OpenAI: OpenAIApi } = require("openai");
if (!process.env.LITE_LLM_BASE_PATH)
throw new Error(
"LiteLLM must have a valid base path to use for the api."
);
this.basePath = process.env.LITE_LLM_BASE_PATH;
this.openai = new OpenAIApi({
baseURL: this.basePath,
apiKey: process.env.LITE_LLM_API_KEY ?? null,
});
this.model = process.env.EMBEDDING_MODEL_PREF || "text-embedding-ada-002";
// Limit of how many strings we can process in a single pass to stay with resource or network limits
this.maxConcurrentChunks = 500;
this.embeddingMaxChunkLength = maximumChunkLength();
}
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
async embedChunks(textChunks = []) {
// Because there is a hard POST limit on how many chunks can be sent at once to LiteLLM (~8mb)
// we concurrently execute each max batch of text chunks possible.
// Refer to constructor maxConcurrentChunks for more info.
const embeddingRequests = [];
for (const chunk of toChunks(textChunks, this.maxConcurrentChunks)) {
embeddingRequests.push(
new Promise((resolve) => {
this.openai.embeddings
.create({
model: this.model,
input: chunk,
})
.then((result) => {
resolve({ data: result?.data, error: null });
})
.catch((e) => {
e.type =
e?.response?.data?.error?.code ||
e?.response?.status ||
"failed_to_embed";
e.message = e?.response?.data?.error?.message || e.message;
resolve({ data: [], error: e });
});
})
);
}
const { data = [], error = null } = await Promise.all(
embeddingRequests
).then((results) => {
// If any errors were returned from LiteLLM abort the entire sequence because the embeddings
// will be incomplete.
const errors = results
.filter((res) => !!res.error)
.map((res) => res.error)
.flat();
if (errors.length > 0) {
let uniqueErrors = new Set();
errors.map((error) =>
uniqueErrors.add(`[${error.type}]: ${error.message}`)
);
return {
data: [],
error: Array.from(uniqueErrors).join(", "),
};
}
return {
data: results.map((res) => res?.data || []).flat(),
error: null,
};
});
if (!!error) throw new Error(`LiteLLM Failed to embed: ${error}`);
return data.length > 0 &&
data.every((embd) => embd.hasOwnProperty("embedding"))
? data.map((embd) => embd.embedding)
: null;
}
}
module.exports = {
LiteLLMEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/azureOpenAi/index.js | server/utils/EmbeddingEngines/azureOpenAi/index.js | const { toChunks } = require("../../helpers");
class AzureOpenAiEmbedder {
constructor() {
const { AzureOpenAI } = require("openai");
if (!process.env.AZURE_OPENAI_ENDPOINT)
throw new Error("No Azure API endpoint was set.");
if (!process.env.AZURE_OPENAI_KEY)
throw new Error("No Azure API key was set.");
this.className = "AzureOpenAiEmbedder";
this.apiVersion = "2024-12-01-preview";
const openai = new AzureOpenAI({
apiKey: process.env.AZURE_OPENAI_KEY,
endpoint: process.env.AZURE_OPENAI_ENDPOINT,
apiVersion: this.apiVersion,
});
// We cannot assume the model fallback since the model is based on the deployment name
// and not the model name - so this will throw on embedding if the model is not defined.
this.model = process.env.EMBEDDING_MODEL_PREF;
this.openai = openai;
// Limit of how many strings we can process in a single pass to stay with resource or network limits
// https://learn.microsoft.com/en-us/azure/ai-services/openai/faq#i-am-trying-to-use-embeddings-and-received-the-error--invalidrequesterror--too-many-inputs--the-max-number-of-inputs-is-1---how-do-i-fix-this-:~:text=consisting%20of%20up%20to%2016%20inputs%20per%20API%20request
this.maxConcurrentChunks = 16;
// https://learn.microsoft.com/en-us/answers/questions/1188074/text-embedding-ada-002-token-context-length
this.embeddingMaxChunkLength = 2048;
}
log(text, ...args) {
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
}
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
async embedChunks(textChunks = []) {
if (!this.model) throw new Error("No Embedding Model preference defined.");
this.log(`Embedding ${textChunks.length} chunks...`);
// Because there is a limit on how many chunks can be sent at once to Azure OpenAI
// we concurrently execute each max batch of text chunks possible.
// Refer to constructor maxConcurrentChunks for more info.
const embeddingRequests = [];
for (const chunk of toChunks(textChunks, this.maxConcurrentChunks)) {
embeddingRequests.push(
new Promise((resolve) => {
this.openai.embeddings
.create({
model: this.model,
input: chunk,
})
.then((res) => {
resolve({ data: res.data, error: null });
})
.catch((e) => {
e.type =
e?.response?.data?.error?.code ||
e?.response?.status ||
"failed_to_embed";
e.message = e?.response?.data?.error?.message || e.message;
resolve({ data: [], error: e });
});
})
);
}
const { data = [], error = null } = await Promise.all(
embeddingRequests
).then((results) => {
// If any errors were returned from Azure abort the entire sequence because the embeddings
// will be incomplete.
const errors = results
.filter((res) => !!res.error)
.map((res) => res.error)
.flat();
if (errors.length > 0) {
let uniqueErrors = new Set();
errors.map((error) =>
uniqueErrors.add(`[${error.type}]: ${error.message}`)
);
return {
data: [],
error: Array.from(uniqueErrors).join(", "),
};
}
return {
data: results.map((res) => res?.data || []).flat(),
error: null,
};
});
if (!!error) throw new Error(`Azure OpenAI Failed to embed: ${error}`);
return data.length > 0 &&
data.every((embd) => embd.hasOwnProperty("embedding"))
? data.map((embd) => embd.embedding)
: null;
}
}
module.exports = {
AzureOpenAiEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/ollama/index.js | server/utils/EmbeddingEngines/ollama/index.js | const { maximumChunkLength } = require("../../helpers");
const { Ollama } = require("ollama");
class OllamaEmbedder {
constructor() {
if (!process.env.EMBEDDING_BASE_PATH)
throw new Error("No embedding base path was set.");
if (!process.env.EMBEDDING_MODEL_PREF)
throw new Error("No embedding model was set.");
this.className = "OllamaEmbedder";
this.basePath = process.env.EMBEDDING_BASE_PATH;
this.model = process.env.EMBEDDING_MODEL_PREF;
this.maxConcurrentChunks = process.env.OLLAMA_EMBEDDING_BATCH_SIZE
? Number(process.env.OLLAMA_EMBEDDING_BATCH_SIZE)
: 1;
this.embeddingMaxChunkLength = maximumChunkLength();
this.authToken = process.env.OLLAMA_AUTH_TOKEN;
const headers = this.authToken
? { Authorization: `Bearer ${this.authToken}` }
: {};
this.client = new Ollama({ host: this.basePath, headers });
this.log(
`initialized with model ${this.model} at ${this.basePath}. Batch size: ${this.maxConcurrentChunks}, num_ctx: ${this.embeddingMaxChunkLength}`
);
}
log(text, ...args) {
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
}
/**
* Checks if the Ollama service is alive by pinging the base path.
* @returns {Promise<boolean>} - A promise that resolves to true if the service is alive, false otherwise.
*/
async #isAlive() {
return await fetch(this.basePath)
.then((res) => res.ok)
.catch((e) => {
this.log(e.message);
return false;
});
}
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
/**
* This function takes an array of text chunks and embeds them using the Ollama API.
* Chunks are processed in batches based on the maxConcurrentChunks setting to balance
* resource usage on the Ollama endpoint.
*
* We will use the num_ctx option to set the maximum context window to the max chunk length defined by the user in the settings
* so that the maximum context window is used and content is not truncated.
*
* We also assume the default keep alive option. This could cause issues with models being unloaded and reloaded
* on low memory machines, but that is simply a user-end issue we cannot control. If the LLM and embedder are
* constantly being loaded and unloaded, the user should use another LLM or Embedder to avoid this issue.
* @param {string[]} textChunks - An array of text chunks to embed.
* @returns {Promise<Array<number[]>>} - A promise that resolves to an array of embeddings.
*/
async embedChunks(textChunks = []) {
if (!(await this.#isAlive()))
throw new Error(
`Ollama service could not be reached. Is Ollama running?`
);
this.log(
`Embedding ${textChunks.length} chunks of text with ${this.model} in batches of ${this.maxConcurrentChunks}.`
);
let data = [];
let error = null;
// Process chunks in batches based on maxConcurrentChunks
const totalBatches = Math.ceil(
textChunks.length / this.maxConcurrentChunks
);
let currentBatch = 0;
for (let i = 0; i < textChunks.length; i += this.maxConcurrentChunks) {
const batch = textChunks.slice(i, i + this.maxConcurrentChunks);
currentBatch++;
try {
// Use input param instead of prompt param to support batch processing
const res = await this.client.embed({
model: this.model,
input: batch,
options: {
// Always set the num_ctx to the max chunk length defined by the user in the settings
// so that the maximum context window is used and content is not truncated.
num_ctx: this.embeddingMaxChunkLength,
},
});
const { embeddings } = res;
if (!Array.isArray(embeddings) || embeddings.length === 0)
throw new Error("Ollama returned empty embeddings for batch!");
// Using prompt param in embed() would return a single embedding (number[])
// but input param returns an array of embeddings (number[][]) for batch processing.
// This is why we spread the embeddings array into the data array.
data.push(...embeddings);
this.log(
`Batch ${currentBatch}/${totalBatches}: Embedded ${embeddings.length} chunks. Total: ${data.length}/${textChunks.length}`
);
} catch (err) {
this.log(err.message);
error = err.message;
data = [];
break;
}
}
if (!!error) throw new Error(`Ollama Failed to embed: ${error}`);
return data.length > 0 ? data : null;
}
}
module.exports = {
OllamaEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/openAi/index.js | server/utils/EmbeddingEngines/openAi/index.js | const { toChunks } = require("../../helpers");
class OpenAiEmbedder {
constructor() {
if (!process.env.OPEN_AI_KEY) throw new Error("No OpenAI API key was set.");
this.className = "OpenAiEmbedder";
const { OpenAI: OpenAIApi } = require("openai");
this.openai = new OpenAIApi({
apiKey: process.env.OPEN_AI_KEY,
});
this.model = process.env.EMBEDDING_MODEL_PREF || "text-embedding-ada-002";
// Limit of how many strings we can process in a single pass to stay with resource or network limits
this.maxConcurrentChunks = 500;
// https://platform.openai.com/docs/guides/embeddings/embedding-models
this.embeddingMaxChunkLength = 8_191;
}
log(text, ...args) {
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
}
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
async embedChunks(textChunks = []) {
this.log(`Embedding ${textChunks.length} chunks...`);
// Because there is a hard POST limit on how many chunks can be sent at once to OpenAI (~8mb)
// we concurrently execute each max batch of text chunks possible.
// Refer to constructor maxConcurrentChunks for more info.
const embeddingRequests = [];
for (const chunk of toChunks(textChunks, this.maxConcurrentChunks)) {
embeddingRequests.push(
new Promise((resolve) => {
this.openai.embeddings
.create({
model: this.model,
input: chunk,
})
.then((result) => {
resolve({ data: result?.data, error: null });
})
.catch((e) => {
e.type =
e?.response?.data?.error?.code ||
e?.response?.status ||
"failed_to_embed";
e.message = e?.response?.data?.error?.message || e.message;
resolve({ data: [], error: e });
});
})
);
}
const { data = [], error = null } = await Promise.all(
embeddingRequests
).then((results) => {
// If any errors were returned from OpenAI abort the entire sequence because the embeddings
// will be incomplete.
const errors = results
.filter((res) => !!res.error)
.map((res) => res.error)
.flat();
if (errors.length > 0) {
let uniqueErrors = new Set();
errors.map((error) =>
uniqueErrors.add(`[${error.type}]: ${error.message}`)
);
return {
data: [],
error: Array.from(uniqueErrors).join(", "),
};
}
return {
data: results.map((res) => res?.data || []).flat(),
error: null,
};
});
if (!!error) throw new Error(`OpenAI Failed to embed: ${error}`);
return data.length > 0 &&
data.every((embd) => embd.hasOwnProperty("embedding"))
? data.map((embd) => embd.embedding)
: null;
}
}
module.exports = {
OpenAiEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/mistral/index.js | server/utils/EmbeddingEngines/mistral/index.js | class MistralEmbedder {
constructor() {
if (!process.env.MISTRAL_API_KEY)
throw new Error("No Mistral API key was set.");
const { OpenAI: OpenAIApi } = require("openai");
this.openai = new OpenAIApi({
baseURL: "https://api.mistral.ai/v1",
apiKey: process.env.MISTRAL_API_KEY ?? null,
});
this.model = process.env.EMBEDDING_MODEL_PREF || "mistral-embed";
}
async embedTextInput(textInput) {
try {
const response = await this.openai.embeddings.create({
model: this.model,
input: textInput,
});
return response?.data[0]?.embedding || [];
} catch (error) {
console.error("Failed to get embedding from Mistral.", error.message);
return [];
}
}
async embedChunks(textChunks = []) {
try {
const response = await this.openai.embeddings.create({
model: this.model,
input: textChunks,
});
return response?.data?.map((emb) => emb.embedding) || [];
} catch (error) {
console.error("Failed to get embeddings from Mistral.", error.message);
return new Array(textChunks.length).fill([]);
}
}
}
module.exports = {
MistralEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/voyageAi/index.js | server/utils/EmbeddingEngines/voyageAi/index.js | class VoyageAiEmbedder {
constructor() {
if (!process.env.VOYAGEAI_API_KEY)
throw new Error("No Voyage AI API key was set.");
const {
VoyageEmbeddings,
} = require("@langchain/community/embeddings/voyage");
this.model = process.env.EMBEDDING_MODEL_PREF || "voyage-3-lite";
this.voyage = new VoyageEmbeddings({
apiKey: process.env.VOYAGEAI_API_KEY,
modelName: this.model,
// Voyage AI's limit per request is 128 https://docs.voyageai.com/docs/rate-limits#use-larger-batches
batchSize: 128,
});
this.embeddingMaxChunkLength = this.#getMaxEmbeddingLength();
}
// https://docs.voyageai.com/docs/embeddings
#getMaxEmbeddingLength() {
switch (this.model) {
case "voyage-finance-2":
case "voyage-multilingual-2":
case "voyage-3":
case "voyage-3-lite":
case "voyage-3-large":
case "voyage-code-3":
return 32_000;
case "voyage-large-2-instruct":
case "voyage-law-2":
case "voyage-code-2":
case "voyage-large-2":
return 16_000;
case "voyage-2":
return 4_000;
default:
return 4_000;
}
}
async embedTextInput(textInput) {
const result = await this.voyage.embedDocuments(
Array.isArray(textInput) ? textInput : [textInput]
);
// If given an array return the native Array[Array] format since that should be the outcome.
// But if given a single string, we need to flatten it so that we have a 1D array.
return (Array.isArray(textInput) ? result : result.flat()) || [];
}
async embedChunks(textChunks = []) {
try {
const embeddings = await this.voyage.embedDocuments(textChunks);
return embeddings;
} catch (error) {
console.error("Voyage AI Failed to embed:", error);
if (
error.message.includes(
"Cannot read properties of undefined (reading '0')"
)
)
throw new Error("Voyage AI failed to embed: Rate limit reached");
throw error;
}
}
}
module.exports = {
VoyageAiEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingEngines/gemini/index.js | server/utils/EmbeddingEngines/gemini/index.js | const { toChunks } = require("../../helpers");
const MODEL_MAP = {
"embedding-001": 2048,
"text-embedding-004": 2048,
"gemini-embedding-exp-03-07": 8192,
};
class GeminiEmbedder {
constructor() {
if (!process.env.GEMINI_EMBEDDING_API_KEY)
throw new Error("No Gemini API key was set.");
this.className = "GeminiEmbedder";
const { OpenAI: OpenAIApi } = require("openai");
this.model = process.env.EMBEDDING_MODEL_PREF || "text-embedding-004";
this.openai = new OpenAIApi({
apiKey: process.env.GEMINI_EMBEDDING_API_KEY,
// Even models that are v1 in gemini API can be used with v1beta/openai/ endpoint and nobody knows why.
baseURL: "https://generativelanguage.googleapis.com/v1beta/openai/",
});
this.maxConcurrentChunks = 4;
// https://ai.google.dev/gemini-api/docs/models/gemini#text-embedding-and-embedding
this.embeddingMaxChunkLength = MODEL_MAP[this.model] || 2_048;
this.log(
`Initialized with ${this.model} - Max Size: ${this.embeddingMaxChunkLength}`
);
}
log(text, ...args) {
console.log(`\x1b[36m[${this.className}]\x1b[0m ${text}`, ...args);
}
/**
* Embeds a single text input
* @param {string|string[]} textInput - The text to embed
* @returns {Promise<Array<number>>} The embedding values
*/
async embedTextInput(textInput) {
const result = await this.embedChunks(
Array.isArray(textInput) ? textInput : [textInput]
);
return result?.[0] || [];
}
/**
* Embeds a list of text inputs
* @param {string[]} textChunks - The list of text to embed
* @returns {Promise<Array<Array<number>>>} The embedding values
*/
async embedChunks(textChunks = []) {
this.log(`Embedding ${textChunks.length} chunks...`);
// Because there is a hard POST limit on how many chunks can be sent at once to OpenAI (~8mb)
// we concurrently execute each max batch of text chunks possible.
// Refer to constructor maxConcurrentChunks for more info.
const embeddingRequests = [];
for (const chunk of toChunks(textChunks, this.maxConcurrentChunks)) {
embeddingRequests.push(
new Promise((resolve) => {
this.openai.embeddings
.create({
model: this.model,
input: chunk,
})
.then((result) => {
resolve({ data: result?.data, error: null });
})
.catch((e) => {
e.type =
e?.response?.data?.error?.code ||
e?.response?.status ||
"failed_to_embed";
e.message = e?.response?.data?.error?.message || e.message;
resolve({ data: [], error: e });
});
})
);
}
const { data = [], error = null } = await Promise.all(
embeddingRequests
).then((results) => {
// If any errors were returned from OpenAI abort the entire sequence because the embeddings
// will be incomplete.
const errors = results
.filter((res) => !!res.error)
.map((res) => res.error)
.flat();
if (errors.length > 0) {
let uniqueErrors = new Set();
errors.map((error) =>
uniqueErrors.add(`[${error.type}]: ${error.message}`)
);
return {
data: [],
error: Array.from(uniqueErrors).join(", "),
};
}
return {
data: results.map((res) => res?.data || []).flat(),
error: null,
};
});
if (!!error) throw new Error(`Gemini Failed to embed: ${error}`);
return data.length > 0 &&
data.every((embd) => embd.hasOwnProperty("embedding"))
? data.map((embd) => embd.embedding)
: null;
}
}
module.exports = {
GeminiEmbedder,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/EmbeddingRerankers/native/index.js | server/utils/EmbeddingRerankers/native/index.js | const path = require("path");
const fs = require("fs");
class NativeEmbeddingReranker {
static #model = null;
static #tokenizer = null;
static #transformers = null;
static #initializationPromise = null;
// This is a folder that Mintplex Labs hosts for those who cannot capture the HF model download
// endpoint for various reasons. This endpoint is not guaranteed to be active or maintained
// and may go offline at any time at Mintplex Labs's discretion.
#fallbackHost = "https://cdn.anythingllm.com/support/models/";
constructor() {
// An alternative model to the mixedbread-ai/mxbai-rerank-xsmall-v1 model (speed on CPU is much slower for this model @ 18docs = 6s)
// Model Card: https://huggingface.co/Xenova/ms-marco-MiniLM-L-6-v2 (speed on CPU is much faster @ 18docs = 1.6s)
this.model = "Xenova/ms-marco-MiniLM-L-6-v2";
this.cacheDir = path.resolve(
process.env.STORAGE_DIR
? path.resolve(process.env.STORAGE_DIR, `models`)
: path.resolve(__dirname, `../../../storage/models`)
);
this.modelPath = path.resolve(this.cacheDir, ...this.model.split("/"));
// Make directory when it does not exist in existing installations
if (!fs.existsSync(this.cacheDir)) fs.mkdirSync(this.cacheDir);
this.modelDownloaded = fs.existsSync(
path.resolve(this.cacheDir, this.model)
);
this.log("Initialized");
}
log(text, ...args) {
console.log(`\x1b[36m[NativeEmbeddingReranker]\x1b[0m ${text}`, ...args);
}
/**
* This function will return the host of the current reranker suite.
* If the reranker suite is not initialized, it will return the default HF host.
* @returns {string} The host of the current reranker suite.
*/
get host() {
if (!NativeEmbeddingReranker.#transformers) return "https://huggingface.co";
try {
return new URL(NativeEmbeddingReranker.#transformers.env.remoteHost).host;
} catch (e) {
return this.#fallbackHost;
}
}
/**
* This function will preload the reranker suite and tokenizer.
* This is useful for reducing the latency of the first rerank call and pre-downloading the models and such
* to avoid having to wait for the models to download on the first rerank call.
*/
async preload() {
try {
this.log(`Preloading reranker suite...`);
await this.initClient();
this.log(
`Preloaded reranker suite. Reranking is available as a service now.`
);
return;
} catch (e) {
console.error(e);
this.log(
`Failed to preload reranker suite. Reranking will be available on the first rerank call.`
);
return;
}
}
async initClient() {
if (
NativeEmbeddingReranker.#transformers &&
NativeEmbeddingReranker.#model &&
NativeEmbeddingReranker.#tokenizer
) {
this.log(`Reranker suite already fully initialized - reusing.`);
return;
}
if (NativeEmbeddingReranker.#initializationPromise) {
this.log(`Waiting for existing initialization to complete...`);
await NativeEmbeddingReranker.#initializationPromise;
return;
}
NativeEmbeddingReranker.#initializationPromise = (async () => {
try {
const { AutoModelForSequenceClassification, AutoTokenizer, env } =
await import("@xenova/transformers");
this.log(`Loading reranker suite...`);
NativeEmbeddingReranker.#transformers = {
AutoModelForSequenceClassification,
AutoTokenizer,
env,
};
// Attempt to load the model and tokenizer in this order:
// 1. From local file system cache
// 2. Download and cache from remote host (hf.co)
// 3. Download and cache from fallback host (cdn.anythingllm.com)
await this.#getPreTrainedModel();
await this.#getPreTrainedTokenizer();
} finally {
NativeEmbeddingReranker.#initializationPromise = null;
}
})();
await NativeEmbeddingReranker.#initializationPromise;
}
/**
* This function will load the model from the local file system cache, or download and cache it from the remote host.
* If the model is not found in the local file system cache, it will download and cache it from the remote host.
* If the model is not found in the remote host, it will download and cache it from the fallback host.
* @returns {Promise<any>} The loaded model.
*/
async #getPreTrainedModel() {
if (NativeEmbeddingReranker.#model) {
this.log(`Loading model from singleton...`);
return NativeEmbeddingReranker.#model;
}
try {
const model =
await NativeEmbeddingReranker.#transformers.AutoModelForSequenceClassification.from_pretrained(
this.model,
{
progress_callback: (p) => {
if (!this.modelDownloaded && p.status === "progress") {
this.log(
`[${this.host}] Loading model ${this.model}... ${p?.progress}%`
);
}
},
cache_dir: this.cacheDir,
}
);
this.log(`Loaded model ${this.model}`);
NativeEmbeddingReranker.#model = model;
return model;
} catch (e) {
this.log(
`Failed to load model ${this.model} from ${this.host}.`,
e.message,
e.stack
);
if (
NativeEmbeddingReranker.#transformers.env.remoteHost ===
this.#fallbackHost
) {
this.log(`Failed to load model ${this.model} from fallback host.`);
throw e;
}
this.log(`Falling back to fallback host. ${this.#fallbackHost}`);
NativeEmbeddingReranker.#transformers.env.remoteHost = this.#fallbackHost;
NativeEmbeddingReranker.#transformers.env.remotePathTemplate = "{model}/";
return await this.#getPreTrainedModel();
}
}
/**
* This function will load the tokenizer from the local file system cache, or download and cache it from the remote host.
* If the tokenizer is not found in the local file system cache, it will download and cache it from the remote host.
* If the tokenizer is not found in the remote host, it will download and cache it from the fallback host.
* @returns {Promise<any>} The loaded tokenizer.
*/
async #getPreTrainedTokenizer() {
if (NativeEmbeddingReranker.#tokenizer) {
this.log(`Loading tokenizer from singleton...`);
return NativeEmbeddingReranker.#tokenizer;
}
try {
const tokenizer =
await NativeEmbeddingReranker.#transformers.AutoTokenizer.from_pretrained(
this.model,
{
progress_callback: (p) => {
if (!this.modelDownloaded && p.status === "progress") {
this.log(
`[${this.host}] Loading tokenizer ${this.model}... ${p?.progress}%`
);
}
},
cache_dir: this.cacheDir,
}
);
this.log(`Loaded tokenizer ${this.model}`);
NativeEmbeddingReranker.#tokenizer = tokenizer;
return tokenizer;
} catch (e) {
this.log(
`Failed to load tokenizer ${this.model} from ${this.host}.`,
e.message,
e.stack
);
if (
NativeEmbeddingReranker.#transformers.env.remoteHost ===
this.#fallbackHost
) {
this.log(`Failed to load tokenizer ${this.model} from fallback host.`);
throw e;
}
this.log(`Falling back to fallback host. ${this.#fallbackHost}`);
NativeEmbeddingReranker.#transformers.env.remoteHost = this.#fallbackHost;
NativeEmbeddingReranker.#transformers.env.remotePathTemplate = "{model}/";
return await this.#getPreTrainedTokenizer();
}
}
/**
* Reranks a list of documents based on the query.
* @param {string} query - The query to rerank the documents against.
* @param {{text: string}[]} documents - The list of document text snippets to rerank. Should be output from a vector search.
* @param {Object} options - The options for the reranking.
* @param {number} options.topK - The number of top documents to return.
* @returns {Promise<any[]>} - The reranked list of documents.
*/
async rerank(query, documents, options = { topK: 4 }) {
await this.initClient();
const model = NativeEmbeddingReranker.#model;
const tokenizer = NativeEmbeddingReranker.#tokenizer;
const start = Date.now();
this.log(`Reranking ${documents.length} documents...`);
const inputs = tokenizer(new Array(documents.length).fill(query), {
text_pair: documents.map((doc) => doc.text),
padding: true,
truncation: true,
});
const { logits } = await model(inputs);
const reranked = logits
.sigmoid()
.tolist()
.map(([score], i) => ({
rerank_corpus_id: i,
rerank_score: score,
...documents[i],
}))
.sort((a, b) => b.rerank_score - a.rerank_score)
.slice(0, options.topK);
this.log(
`Reranking ${documents.length} documents to top ${options.topK} took ${Date.now() - start}ms`
);
return reranked;
}
}
module.exports = {
NativeEmbeddingReranker,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/telemetry/index.js | server/utils/telemetry/index.js | const { getGitVersion } = require("../../endpoints/utils");
const { Telemetry } = require("../../models/telemetry");
// Telemetry is anonymized and your data is never read. This can be disabled by setting
// DISABLE_TELEMETRY=true in the `.env` of however you setup. Telemetry helps us determine use
// of how AnythingLLM is used and how to improve this product!
// You can see all Telemetry events by ctrl+f `Telemetry.sendTelemetry` calls to verify this claim.
async function setupTelemetry() {
if (process.env.DISABLE_TELEMETRY === "true") {
console.log(
`\x1b[31m[TELEMETRY DISABLED]\x1b[0m Telemetry is marked as disabled - no events will send. Telemetry helps Mintplex Labs Inc improve AnythingLLM.`
);
return true;
}
if (Telemetry.isDev()) {
console.log(
`\x1b[33m[TELEMETRY STUBBED]\x1b[0m Anonymous Telemetry stubbed in development.`
);
return;
}
console.log(
`\x1b[32m[TELEMETRY ENABLED]\x1b[0m Anonymous Telemetry enabled. Telemetry helps Mintplex Labs Inc improve AnythingLLM.`
);
await Telemetry.findOrCreateId();
await Telemetry.sendTelemetry("server_boot", {
commit: getGitVersion(),
});
return;
}
module.exports = setupTelemetry;
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/http/index.js | server/utils/http/index.js | process.env.NODE_ENV === "development"
? require("dotenv").config({ path: `.env.${process.env.NODE_ENV}` })
: require("dotenv").config();
const JWT = require("jsonwebtoken");
const { User } = require("../../models/user");
const { jsonrepair } = require("jsonrepair");
const extract = require("extract-json-from-string");
function reqBody(request) {
return typeof request.body === "string"
? JSON.parse(request.body)
: request.body;
}
function queryParams(request) {
return request.query;
}
/**
* Creates a JWT with the given info and expiry
* @param {object} info - The info to include in the JWT
* @param {string} expiry - The expiry time for the JWT (default: 30 days)
* @returns {string} The JWT
*/
function makeJWT(info = {}, expiry = "30d") {
if (!process.env.JWT_SECRET)
throw new Error("Cannot create JWT as JWT_SECRET is unset.");
return JWT.sign(info, process.env.JWT_SECRET, { expiresIn: expiry });
}
// Note: Only valid for finding users in multi-user mode
// as single-user mode with password is not a "user"
async function userFromSession(request, response = null) {
if (!!response && !!response.locals?.user) {
return response.locals.user;
}
const auth = request.header("Authorization");
const token = auth ? auth.split(" ")[1] : null;
if (!token) {
return null;
}
const valid = decodeJWT(token);
if (!valid || !valid.id) {
return null;
}
const user = await User.get({ id: valid.id });
return user;
}
function decodeJWT(jwtToken) {
try {
return JWT.verify(jwtToken, process.env.JWT_SECRET);
} catch {}
return { p: null, id: null, username: null };
}
function multiUserMode(response) {
return response?.locals?.multiUserMode;
}
function parseAuthHeader(headerValue = null, apiKey = null) {
if (headerValue === null || apiKey === null) return {};
if (headerValue === "Authorization")
return { Authorization: `Bearer ${apiKey}` };
return { [headerValue]: apiKey };
}
function safeJsonParse(jsonString, fallback = null) {
if (jsonString === null) return fallback;
try {
return JSON.parse(jsonString);
} catch {}
if (jsonString?.startsWith("[") || jsonString?.startsWith("{")) {
try {
const repairedJson = jsonrepair(jsonString);
return JSON.parse(repairedJson);
} catch {}
}
try {
return extract(jsonString)?.[0] || fallback;
} catch {}
return fallback;
}
function isValidUrl(urlString = "") {
try {
const url = new URL(urlString);
if (!["http:", "https:"].includes(url.protocol)) return false;
return true;
} catch (e) {}
return false;
}
function toValidNumber(number = null, fallback = null) {
if (isNaN(Number(number))) return fallback;
return Number(number);
}
module.exports = {
reqBody,
multiUserMode,
queryParams,
makeJWT,
decodeJWT,
userFromSession,
parseAuthHeader,
safeJsonParse,
isValidUrl,
toValidNumber,
};
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/utils/TextSplitter/index.js | server/utils/TextSplitter/index.js | /**
* @typedef {object} DocumentMetadata
* @property {string} id - eg; "123e4567-e89b-12d3-a456-426614174000"
* @property {string} url - eg; "file://example.com/index.html"
* @property {string} title - eg; "example.com/index.html"
* @property {string} docAuthor - eg; "no author found"
* @property {string} description - eg; "No description found."
* @property {string} docSource - eg; "URL link uploaded by the user."
* @property {string} chunkSource - eg; link://https://example.com
* @property {string} published - ISO 8601 date string
* @property {number} wordCount - Number of words in the document
* @property {string} pageContent - The raw text content of the document
* @property {number} token_count_estimate - Number of tokens in the document
*/
function isNullOrNaN(value) {
if (value === null) return true;
return isNaN(value);
}
class TextSplitter {
#splitter;
/**
* Creates a new TextSplitter instance.
* @param {Object} config
* @param {string} [config.chunkPrefix = ""] - Prefix to be added to the start of each chunk.
* @param {number} [config.chunkSize = 1000] - The size of each chunk.
* @param {number} [config.chunkOverlap = 20] - The overlap between chunks.
* @param {Object} [config.chunkHeaderMeta = null] - Metadata to be added to the start of each chunk - will come after the prefix.
*/
constructor(config = {}) {
this.config = config;
this.#splitter = this.#setSplitter(config);
}
log(text, ...args) {
console.log(`\x1b[35m[TextSplitter]\x1b[0m ${text}`, ...args);
}
/**
* Does a quick check to determine the text chunk length limit.
* Embedder models have hard-set limits that cannot be exceeded, just like an LLM context
* so here we want to allow override of the default 1000, but up to the models maximum, which is
* sometimes user defined.
*/
static determineMaxChunkSize(preferred = null, embedderLimit = 1000) {
const prefValue = isNullOrNaN(preferred)
? Number(embedderLimit)
: Number(preferred);
const limit = Number(embedderLimit);
if (prefValue > limit)
console.log(
`\x1b[43m[WARN]\x1b[0m Text splitter chunk length of ${prefValue} exceeds embedder model max of ${embedderLimit}. Will use ${embedderLimit}.`
);
return prefValue > limit ? limit : prefValue;
}
/**
* Creates a string of metadata to be prepended to each chunk.
* @param {DocumentMetadata} metadata - Metadata to be prepended to each chunk.
* @returns {{[key: ('title' | 'published' | 'source')]: string}} Object of metadata that will be prepended to each chunk.
*/
static buildHeaderMeta(metadata = {}) {
if (!metadata || Object.keys(metadata).length === 0) return null;
const PLUCK_MAP = {
title: {
as: "sourceDocument",
pluck: (metadata) => {
return metadata?.title || null;
},
},
published: {
as: "published",
pluck: (metadata) => {
return metadata?.published || null;
},
},
chunkSource: {
as: "source",
pluck: (metadata) => {
const validPrefixes = ["link://", "youtube://"];
// If the chunkSource is a link or youtube link, we can add the URL
// as its source in the metadata so the LLM can use it for context.
// eg prompt: Where did you get this information? -> answer: "from https://example.com"
if (
!metadata?.chunkSource || // Exists
!metadata?.chunkSource.length || // Is not empty
typeof metadata.chunkSource !== "string" || // Is a string
!validPrefixes.some(
(prefix) => metadata.chunkSource.startsWith(prefix) // Has a valid prefix we respect
)
)
return null;
// We know a prefix is present, so we can split on it and return the rest.
// If nothing is found, return null and it will not be added to the metadata.
let source = null;
for (const prefix of validPrefixes) {
source = metadata.chunkSource.split(prefix)?.[1] || null;
if (source) break;
}
return source;
},
},
};
const pluckedData = {};
Object.entries(PLUCK_MAP).forEach(([key, value]) => {
if (!(key in metadata)) return; // Skip if the metadata key is not present.
const pluckedValue = value.pluck(metadata);
if (!pluckedValue) return; // Skip if the plucked value is null/empty.
pluckedData[value.as] = pluckedValue;
});
return pluckedData;
}
/**
* Apply the chunk prefix to the text if it is present.
* @param {string} text - The text to apply the prefix to.
* @returns {string} The text with the embedder model prefix applied.
*/
#applyPrefix(text = "") {
if (!this.config.chunkPrefix) return text;
return `${this.config.chunkPrefix}${text}`;
}
/**
* Creates a string of metadata to be prepended to each chunk.
* Will additionally prepend a prefix to the text if it was provided (requirement for some embedders).
* @returns {string} The text with the embedder model prefix applied.
*/
stringifyHeader() {
let content = "";
if (!this.config.chunkHeaderMeta) return this.#applyPrefix(content);
Object.entries(this.config.chunkHeaderMeta).map(([key, value]) => {
if (!key || !value) return;
content += `${key}: ${value}\n`;
});
if (!content) return this.#applyPrefix(content);
return this.#applyPrefix(
`<document_metadata>\n${content}</document_metadata>\n\n`
);
}
/**
* Sets the splitter to use a defined config passes to other subclasses.
* @param {Object} config
* @param {string} [config.chunkPrefix = ""] - Prefix to be added to the start of each chunk.
* @param {number} [config.chunkSize = 1000] - The size of each chunk.
* @param {number} [config.chunkOverlap = 20] - The overlap between chunks.
*/
#setSplitter(config = {}) {
// if (!config?.splitByFilename) {// TODO do something when specific extension is present? }
return new RecursiveSplitter({
chunkSize: isNaN(config?.chunkSize) ? 1_000 : Number(config?.chunkSize),
chunkOverlap: isNaN(config?.chunkOverlap)
? 20
: Number(config?.chunkOverlap),
chunkHeader: this.stringifyHeader(),
});
}
async splitText(documentText) {
return this.#splitter._splitText(documentText);
}
}
// Wrapper for Langchain default RecursiveCharacterTextSplitter class.
class RecursiveSplitter {
constructor({ chunkSize, chunkOverlap, chunkHeader = null }) {
const {
RecursiveCharacterTextSplitter,
} = require("@langchain/textsplitters");
this.log(`Will split with`, {
chunkSize,
chunkOverlap,
chunkHeader: chunkHeader ? `${chunkHeader?.slice(0, 50)}...` : null,
});
this.chunkHeader = chunkHeader;
this.engine = new RecursiveCharacterTextSplitter({
chunkSize,
chunkOverlap,
});
}
log(text, ...args) {
console.log(`\x1b[35m[RecursiveSplitter]\x1b[0m ${text}`, ...args);
}
async _splitText(documentText) {
if (!this.chunkHeader) return this.engine.splitText(documentText);
const strings = await this.engine.splitText(documentText);
const documents = await this.engine.createDocuments(strings, [], {
chunkHeader: this.chunkHeader,
});
return documents
.filter((doc) => !!doc.pageContent)
.map((doc) => doc.pageContent);
}
}
module.exports.TextSplitter = TextSplitter;
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/models/systemPromptVariables.test.js | server/__tests__/models/systemPromptVariables.test.js | const { SystemPromptVariables } = require("../../models/systemPromptVariables");
const prisma = require("../../utils/prisma");
const mockUser = {
id: 1,
username: "john.doe",
bio: "I am a test user",
};
const mockWorkspace = {
id: 1,
name: "Test Workspace",
slug: 'test-workspace',
};
const mockSystemPromptVariables = [
{
id: 1,
key: "mystaticvariable",
value: "AnythingLLM testing runtime",
description: "A test variable",
type: "static",
userId: null,
},
];
describe("SystemPromptVariables.expandSystemPromptVariables", () => {
beforeEach(() => {
jest.clearAllMocks();
// Mock just the Prisma actions since that is what is used by default values
prisma.system_prompt_variables.findMany = jest.fn().mockResolvedValue(mockSystemPromptVariables);
prisma.workspaces.findUnique = jest.fn().mockResolvedValue(mockWorkspace);
prisma.users.findUnique = jest.fn().mockResolvedValue(mockUser);
});
it("should expand user-defined system prompt variables", async () => {
const variables = await SystemPromptVariables.expandSystemPromptVariables("Hello {mystaticvariable}");
expect(variables).toBe(`Hello ${mockSystemPromptVariables[0].value}`);
});
it("should expand workspace-defined system prompt variables", async () => {
const variables = await SystemPromptVariables.expandSystemPromptVariables("Hello {workspace.name}", null, mockWorkspace.id);
expect(variables).toBe(`Hello ${mockWorkspace.name}`);
});
it("should expand user-defined system prompt variables", async () => {
const variables = await SystemPromptVariables.expandSystemPromptVariables("Hello {user.name}", mockUser.id);
expect(variables).toBe(`Hello ${mockUser.username}`);
});
it("should work with any combination of variables", async () => {
const variables = await SystemPromptVariables.expandSystemPromptVariables("Hello {mystaticvariable} {workspace.name} {user.name}", mockUser.id, mockWorkspace.id);
expect(variables).toBe(`Hello ${mockSystemPromptVariables[0].value} ${mockWorkspace.name} ${mockUser.username}`);
});
it('should fail gracefully with invalid variables that are undefined for any reason', async () => {
// Undefined sub-fields on valid classes are push to a placeholder [Class prop]. This is expected behavior.
const variables = await SystemPromptVariables.expandSystemPromptVariables("Hello {invalid.variable} {user.password} the current user is {user.name} on workspace id #{workspace.id}", null, null);
expect(variables).toBe("Hello {invalid.variable} [User password] the current user is [User name] on workspace id #[Workspace ID]");
});
}); | javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/helpers/convertTo.test.js | server/__tests__/utils/helpers/convertTo.test.js | /* eslint-env jest */
const { prepareChatsForExport } = require("../../../utils/helpers/chat/convertTo");
// Mock the database models
jest.mock("../../../models/workspaceChats");
jest.mock("../../../models/embedChats");
const { WorkspaceChats } = require("../../../models/workspaceChats");
const { EmbedChats } = require("../../../models/embedChats");
const mockChat = (withImages = false) => {
return {
id: 1,
prompt: "Test prompt",
response: JSON.stringify({
text: "Test response",
attachments: withImages ? [
{ mime: "image/png", name: "image.png", contentString: "data:image/png;base64,iVBORw0KGg....=" },
{ mime: "image/jpeg", name: "image2.jpeg", contentString: "data:image/jpeg;base64,iVBORw0KGg....=" }
] : [],
sources: [],
metrics: {},
}),
createdAt: new Date(),
workspace: { name: "Test Workspace", openAiPrompt: "Test OpenAI Prompt" },
user: { username: "testuser" },
feedbackScore: 1,
}
};
describe("prepareChatsForExport", () => {
beforeEach(() => {
jest.clearAllMocks();
WorkspaceChats.whereWithData = jest.fn().mockResolvedValue([]);
EmbedChats.whereWithEmbedAndWorkspace = jest.fn().mockResolvedValue([]);
});
test("should throw error for invalid chat type", async () => {
await expect(prepareChatsForExport("json", "invalid"))
.rejects
.toThrow("Invalid chat type: invalid");
});
test("should throw error for invalid export type", async () => {
await expect(prepareChatsForExport("invalid", "workspace"))
.rejects
.toThrow("Invalid export type: invalid");
});
// CSV and JSON are the same format, so we can test them together
test("should return prepared data in csv and json format for workspace chat type", async () => {
const chatExample = mockChat();
WorkspaceChats.whereWithData.mockResolvedValue([chatExample]);
const result = await prepareChatsForExport("json", "workspace");
const responseJson = JSON.parse(chatExample.response);
expect(result).toBeDefined();
expect(result).toEqual([{
id: chatExample.id,
prompt: chatExample.prompt,
response: responseJson.text,
sent_at: chatExample.createdAt,
rating: chatExample.feedbackScore ? "GOOD" : "BAD",
username: chatExample.user.username,
workspace: chatExample.workspace.name,
attachments: [],
}]);
});
test("Should handle attachments for workspace chat type when json format is selected", async () => {
const chatExample = mockChat(true);
WorkspaceChats.whereWithData.mockResolvedValue([chatExample]);
const result = await prepareChatsForExport("json", "workspace");
const responseJson = JSON.parse(chatExample.response);
expect(result).toBeDefined();
expect(result).toEqual([{
id: chatExample.id,
prompt: chatExample.prompt,
response: responseJson.text,
sent_at: chatExample.createdAt,
rating: chatExample.feedbackScore ? "GOOD" : "BAD",
username: chatExample.user.username,
workspace: chatExample.workspace.name,
attachments: [
{
type: "image",
image: responseJson.attachments[0].contentString,
},
{
type: "image",
image: responseJson.attachments[1].contentString,
},
]
}]);
});
test("Should ignore attachments for workspace chat type when csv format is selected", async () => {
const chatExample = mockChat(true);
WorkspaceChats.whereWithData.mockResolvedValue([chatExample]);
const result = await prepareChatsForExport("csv", "workspace");
const responseJson = JSON.parse(chatExample.response);
expect(result).toBeDefined();
expect(result.attachments).not.toBeDefined();
expect(result).toEqual([{
id: chatExample.id,
prompt: chatExample.prompt,
response: responseJson.text,
sent_at: chatExample.createdAt,
rating: chatExample.feedbackScore ? "GOOD" : "BAD",
username: chatExample.user.username,
workspace: chatExample.workspace.name,
}]);
});
test("should return prepared data in jsonAlpaca format for workspace chat type", async () => {
const chatExample = mockChat();
const imageChatExample = mockChat(true);
WorkspaceChats.whereWithData.mockResolvedValue([chatExample, imageChatExample]);
const result = await prepareChatsForExport("jsonAlpaca", "workspace");
const responseJson1 = JSON.parse(chatExample.response);
const responseJson2 = JSON.parse(imageChatExample.response);
expect(result).toBeDefined();
// Alpaca format does not support attachments - so they are not included
expect(result[0].attachments).not.toBeDefined();
expect(result[1].attachments).not.toBeDefined();
expect(result).toEqual([{
instruction: chatExample.workspace.openAiPrompt,
input: chatExample.prompt,
output: responseJson1.text,
},
{
instruction: chatExample.workspace.openAiPrompt,
input: imageChatExample.prompt,
output: responseJson2.text,
}]);
});
test("should return prepared data in jsonl format for workspace chat type", async () => {
const chatExample = mockChat();
const responseJson = JSON.parse(chatExample.response);
WorkspaceChats.whereWithData.mockResolvedValue([chatExample]);
const result = await prepareChatsForExport("jsonl", "workspace");
expect(result).toBeDefined();
expect(result).toEqual(
{
[chatExample.workspace.id]: {
messages: [
{
role: "system",
content: [{
type: "text",
text: chatExample.workspace.openAiPrompt,
}],
},
{
role: "user",
content: [{
type: "text",
text: chatExample.prompt,
}],
},
{
role: "assistant",
content: [{
type: "text",
text: responseJson.text,
}],
},
],
},
},
);
});
test("should return prepared data in jsonl format for workspace chat type with attachments", async () => {
const chatExample = mockChat();
const imageChatExample = mockChat(true);
const responseJson = JSON.parse(chatExample.response);
const imageResponseJson = JSON.parse(imageChatExample.response);
WorkspaceChats.whereWithData.mockResolvedValue([chatExample, imageChatExample]);
const result = await prepareChatsForExport("jsonl", "workspace");
expect(result).toBeDefined();
expect(result).toEqual(
{
[chatExample.workspace.id]: {
messages: [
{
role: "system",
content: [{
type: "text",
text: chatExample.workspace.openAiPrompt,
}],
},
{
role: "user",
content: [{
type: "text",
text: chatExample.prompt,
}],
},
{
role: "assistant",
content: [{
type: "text",
text: responseJson.text,
}],
},
{
role: "user",
content: [{
type: "text",
text: imageChatExample.prompt,
}, {
type: "image",
image: imageResponseJson.attachments[0].contentString,
}, {
type: "image",
image: imageResponseJson.attachments[1].contentString,
}],
},
{
role: "assistant",
content: [{
type: "text",
text: imageResponseJson.text,
}],
},
],
},
},
);
});
}); | javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/agents/defaults.test.js | server/__tests__/utils/agents/defaults.test.js | // Set required env vars before requiring modules
process.env.STORAGE_DIR = __dirname;
process.env.NODE_ENV = "test";
const { SystemPromptVariables } = require("../../../models/systemPromptVariables");
const Provider = require("../../../utils/agents/aibitat/providers/ai-provider");
jest.mock("../../../models/systemPromptVariables");
jest.mock("../../../models/systemSettings");
jest.mock("../../../utils/agents/imported", () => ({
activeImportedPlugins: jest.fn().mockReturnValue([]),
}));
jest.mock("../../../utils/agentFlows", () => ({
AgentFlows: {
activeFlowPlugins: jest.fn().mockReturnValue([]),
},
}));
jest.mock("../../../utils/MCP", () => {
return jest.fn().mockImplementation(() => ({
activeMCPServers: jest.fn().mockResolvedValue([]),
}));
});
const { WORKSPACE_AGENT } = require("../../../utils/agents/defaults");
describe("WORKSPACE_AGENT.getDefinition", () => {
beforeEach(() => {
jest.clearAllMocks();
// Mock SystemSettings to return empty arrays for agent skills
const { SystemSettings } = require("../../../models/systemSettings");
SystemSettings.getValueOrFallback = jest.fn().mockResolvedValue("[]");
});
it("should use provider default system prompt when workspace has no openAiPrompt", async () => {
const workspace = {
id: 1,
name: "Test Workspace",
openAiPrompt: null,
};
const user = { id: 1 };
const provider = "openai";
const expectedPrompt = await Provider.systemPrompt({ provider, workspace, user });
const definition = await WORKSPACE_AGENT.getDefinition(
provider,
workspace,
user
);
expect(definition.role).toBe(expectedPrompt);
expect(SystemPromptVariables.expandSystemPromptVariables).not.toHaveBeenCalled();
});
it("should use workspace system prompt with variable expansion when openAiPrompt exists", async () => {
const workspace = {
id: 1,
name: "Test Workspace",
openAiPrompt: "You are a helpful assistant for {workspace.name}. The current user is {user.name}.",
};
const user = { id: 1 };
const provider = "openai";
const expandedPrompt = "You are a helpful assistant for Test Workspace. The current user is John Doe.";
SystemPromptVariables.expandSystemPromptVariables.mockResolvedValue(expandedPrompt);
const definition = await WORKSPACE_AGENT.getDefinition(
provider,
workspace,
user
);
expect(SystemPromptVariables.expandSystemPromptVariables).toHaveBeenCalledWith(
workspace.openAiPrompt,
user.id,
workspace.id
);
expect(definition.role).toBe(expandedPrompt);
});
it("should handle workspace system prompt without user context", async () => {
const workspace = {
id: 1,
name: "Test Workspace",
openAiPrompt: "You are a helpful assistant. Today is {date}.",
};
const user = null;
const provider = "lmstudio";
const expandedPrompt = "You are a helpful assistant. Today is January 1, 2024.";
SystemPromptVariables.expandSystemPromptVariables.mockResolvedValue(expandedPrompt);
const definition = await WORKSPACE_AGENT.getDefinition(
provider,
workspace,
user
);
expect(SystemPromptVariables.expandSystemPromptVariables).toHaveBeenCalledWith(
workspace.openAiPrompt,
null,
workspace.id
);
expect(definition.role).toBe(expandedPrompt);
});
it("should return functions array in definition", async () => {
const workspace = { id: 1, openAiPrompt: null };
const provider = "openai";
const definition = await WORKSPACE_AGENT.getDefinition(
provider,
workspace,
null
);
expect(definition).toHaveProperty("functions");
expect(Array.isArray(definition.functions)).toBe(true);
});
it("should use LMStudio specific prompt when workspace has no openAiPrompt", async () => {
const workspace = { id: 1, openAiPrompt: null };
const user = null;
const provider = "lmstudio";
const definition = await WORKSPACE_AGENT.getDefinition(
provider,
workspace,
null
);
expect(definition.role).toBe(await Provider.systemPrompt({ provider, workspace, user }));
expect(definition.role).toContain("helpful ai assistant");
});
});
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/agents/aibitat/providers/helpers/untooled.test.js | server/__tests__/utils/agents/aibitat/providers/helpers/untooled.test.js | const UnTooled = require("../../../../../../utils/agents/aibitat/providers/helpers/untooled");
describe("UnTooled: validFuncCall", () => {
const untooled = new UnTooled();
const validFunc = {
"name": "brave-search-brave_web_search",
"description": "Example function",
"parameters": {
"$schema": "http://json-schema.org/draft-07/schema#",
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query (max 400 chars, 50 words)"
},
"count": {
"type": "number",
"description": "Number of results (1-20, default 10)",
"default": 10
},
"offset": {
"type": "number",
"description": "Pagination offset (max 9, default 0)",
"default": 0
}
},
"required": [
"query"
]
}
};
it("Be truthy if the function call is valid and has all required arguments", () => {
const result = untooled.validFuncCall(
{
name: validFunc.name,
arguments: { query: "test" },
}, [validFunc]);
expect(result.valid).toBe(true);
expect(result.reason).toBe(null);
});
it("Be falsey if the function call has no name or arguments", () => {
const result = untooled.validFuncCall(
{ arguments: {} }, [validFunc]);
expect(result.valid).toBe(false);
expect(result.reason).toBe("Missing name or arguments in function call.");
const result2 = untooled.validFuncCall(
{ name: validFunc.name }, [validFunc]);
expect(result2.valid).toBe(false);
expect(result2.reason).toBe("Missing name or arguments in function call.");
});
it("Be falsey if the function call references an unknown function definition", () => {
const result = untooled.validFuncCall(
{
name: "unknown-function",
arguments: {},
}, [validFunc]);
expect(result.valid).toBe(false);
expect(result.reason).toBe("Function name does not exist.");
});
it("Be falsey if the function call is valid but missing any required arguments", () => {
const result = untooled.validFuncCall(
{
name: validFunc.name,
arguments: {},
}, [validFunc]);
expect(result.valid).toBe(false);
expect(result.reason).toBe("Missing required argument: query");
});
it("Be falsey if the function call is valid but has an unknown argument defined (required or not)", () => {
const result = untooled.validFuncCall(
{
name: validFunc.name,
arguments: {
query: "test",
unknown: "unknown",
},
}, [validFunc]);
expect(result.valid).toBe(false);
expect(result.reason).toBe("Unknown argument: unknown provided but not in schema.");
});
}); | javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/agentFlows/executor.test.js | server/__tests__/utils/agentFlows/executor.test.js | const { FlowExecutor } = require("../../../utils/agentFlows/executor");
describe("FlowExecutor: getValueFromPath", () => {
const executor = new FlowExecutor();
it("can handle invalid objects", () => {
expect(executor.getValueFromPath(null, "a.b.c")).toBe("");
expect(executor.getValueFromPath(undefined, "a.b.c")).toBe("");
expect(executor.getValueFromPath(1, "a.b.c")).toBe("");
expect(executor.getValueFromPath("string", "a.b.c")).toBe("");
expect(executor.getValueFromPath(true, "a.b.c")).toBe("");
});
it("can handle invalid paths", () => {
const obj = { a: { b: { c: "answer" } } };
expect(executor.getValueFromPath(obj, -1)).toBe("");
expect(executor.getValueFromPath(obj, undefined)).toBe("");
expect(executor.getValueFromPath(obj, [1, 2, 3])).toBe("");
expect(executor.getValueFromPath(obj, () => { })).toBe("");
});
it("should be able to resolve a value from a dot path at various levels", () => {
let obj = {
a: {
prop: "top-prop",
b: {
c: "answer",
num: 100,
arr: [1, 2, 3],
subarr: [
{ id: 1, name: "answer2" },
{ id: 2, name: "answer3" },
{ id: 3, name: "answer4" },
]
}
}
};
expect(executor.getValueFromPath(obj, "a.prop")).toBe("top-prop");
expect(executor.getValueFromPath(obj, "a.b.c")).toBe("answer");
expect(executor.getValueFromPath(obj, "a.b.num")).toBe(100);
expect(executor.getValueFromPath(obj, "a.b.arr[0]")).toBe(1);
expect(executor.getValueFromPath(obj, "a.b.arr[1]")).toBe(2);
expect(executor.getValueFromPath(obj, "a.b.arr[2]")).toBe(3);
expect(executor.getValueFromPath(obj, "a.b.subarr[0].id")).toBe(1);
expect(executor.getValueFromPath(obj, "a.b.subarr[0].name")).toBe("answer2");
expect(executor.getValueFromPath(obj, "a.b.subarr[1].id")).toBe(2);
expect(executor.getValueFromPath(obj, "a.b.subarr[2].name")).toBe("answer4");
expect(executor.getValueFromPath(obj, "a.b.subarr[2].id")).toBe(3);
});
it("should return empty string if the path is invalid", () => {
const result = executor.getValueFromPath({}, "a.b.c");
expect(result).toBe("");
});
it("should return empty string if the object is invalid", () => {
const result = executor.getValueFromPath(null, "a.b.c");
expect(result).toBe("");
});
it("can return a stringified item if the path target is not an object or array", () => {
const obj = { a: { b: { c: "answer", numbers: [1, 2, 3] } } };
expect(executor.getValueFromPath(obj, "a.b")).toEqual(JSON.stringify(obj.a.b));
expect(executor.getValueFromPath(obj, "a.b.numbers")).toEqual(JSON.stringify(obj.a.b.numbers));
expect(executor.getValueFromPath(obj, "a.b.c")).toBe("answer");
});
it("can return a stringified object if the path target is an array", () => {
const obj = { a: { b: [1, 2, 3] } };
expect(executor.getValueFromPath(obj, "a.b")).toEqual(JSON.stringify(obj.a.b));
expect(executor.getValueFromPath(obj, "a.b[0]")).toBe(1);
expect(executor.getValueFromPath(obj, "a.b[1]")).toBe(2);
expect(executor.getValueFromPath(obj, "a.b[2]")).toBe(3);
});
it("can find a value by string key traversal", () => {
const obj = {
a: {
items: [
{
'my-long-key': [
{ id: 1, name: "answer1" },
{ id: 2, name: "answer2" },
{ id: 3, name: "answer3" },
]
},
],
}
};
expect(executor.getValueFromPath(obj, "a.items[0]['my-long-key'][1].id")).toBe(2);
expect(executor.getValueFromPath(obj, "a.items[0]['my-long-key'][1].name")).toBe("answer2");
});
}); | javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/vectorDbProviders/pgvector/index.test.js | server/__tests__/utils/vectorDbProviders/pgvector/index.test.js | const { PGVector } = require("../../../../utils/vectorDbProviders/pgvector");
describe("PGVector.sanitizeForJsonb", () => {
it("returns null/undefined as-is", () => {
expect(PGVector.sanitizeForJsonb(null)).toBeNull();
expect(PGVector.sanitizeForJsonb(undefined)).toBeUndefined();
});
it("keeps safe whitespace (tab, LF, CR) and removes disallowed C0 controls", () => {
const input = "a\u0000\u0001\u0002\tline\ncarriage\rreturn\u001Fend";
const result = PGVector.sanitizeForJsonb(input);
// Expect all < 0x20 except 9,10,13 removed; keep letters and allowed whitespace
expect(result).toBe("a\tline\ncarriage\rreturnend");
});
it("removes only disallowed control chars; keeps normal printable chars", () => {
const input = "Hello\u0000, World! \u0007\u0008\u000B\u000C\u001F";
const result = PGVector.sanitizeForJsonb(input);
expect(result).toBe("Hello, World! ");
});
it("deeply sanitizes objects", () => {
const input = {
plain: "ok",
bad: "has\u0000nul",
nested: {
arr: ["fine", "bad\u0001", { deep: "\u0002oops" }],
},
};
const result = PGVector.sanitizeForJsonb(input);
expect(result).toEqual({
plain: "ok",
bad: "hasnul",
nested: { arr: ["fine", "bad", { deep: "oops" }] },
});
});
it("deeply sanitizes arrays", () => {
const input = ["\u0000", 1, true, { s: "bad\u0003" }, ["ok", "\u0004bad"]];
const result = PGVector.sanitizeForJsonb(input);
expect(result).toEqual(["", 1, true, { s: "bad" }, ["ok", "bad"]]);
});
it("converts Date to ISO string", () => {
const d = new Date("2020-01-02T03:04:05.000Z");
expect(PGVector.sanitizeForJsonb(d)).toBe(d.toISOString());
});
it("returns primitives unchanged (number, boolean, bigint)", () => {
expect(PGVector.sanitizeForJsonb(42)).toBe(42);
expect(PGVector.sanitizeForJsonb(3.14)).toBe(3.14);
expect(PGVector.sanitizeForJsonb(true)).toBe(true);
expect(PGVector.sanitizeForJsonb(false)).toBe(false);
expect(PGVector.sanitizeForJsonb(BigInt(1))).toBe(BigInt(1));
});
it("returns symbol unchanged", () => {
const sym = Symbol("x");
expect(PGVector.sanitizeForJsonb(sym)).toBe(sym);
});
it("does not mutate original objects/arrays", () => {
const obj = { a: "bad\u0000", nested: { b: "ok" } };
const arr = ["\u0001", { c: "bad\u0002" }];
const objCopy = JSON.parse(JSON.stringify(obj));
const arrCopy = JSON.parse(JSON.stringify(arr));
const resultObj = PGVector.sanitizeForJsonb(obj);
const resultArr = PGVector.sanitizeForJsonb(arr);
// Original inputs remain unchanged
expect(obj).toEqual(objCopy);
expect(arr).toEqual(arrCopy);
// Results are sanitized copies
expect(resultObj).toEqual({ a: "bad", nested: { b: "ok" } });
expect(resultArr).toEqual(["", { c: "bad" }]);
});
});
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/SQLConnectors/connectionParser.test.js | server/__tests__/utils/SQLConnectors/connectionParser.test.js | /* eslint-env jest */
const { ConnectionStringParser } = require("../../../utils/agents/aibitat/plugins/sql-agent/SQLConnectors/utils");
describe("ConnectionStringParser", () => {
describe("Basic Parsing", () => {
test("should parse a basic connection string without options", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
const result = parser.parse("mssql://user:pass@localhost:1433/mydb");
expect(result).toEqual({
scheme: "mssql",
username: "user",
password: "pass",
hosts: [{ host: "localhost", port: 1433 }],
endpoint: "mydb",
options: undefined
});
});
test("should parse a connection string with options", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
const result = parser.parse("mssql://user:pass@localhost:1433/mydb?encrypt=true&trustServerCertificate=true");
expect(result).toEqual({
scheme: "mssql",
username: "user",
password: "pass",
hosts: [{ host: "localhost", port: 1433 }],
endpoint: "mydb",
options: {
encrypt: "true",
trustServerCertificate: "true"
}
});
});
test("should handle empty passwords", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
const result = parser.parse("mssql://user@localhost:1433/mydb");
expect(result).toEqual({
scheme: "mssql",
username: "user",
password: undefined,
hosts: [{ host: "localhost", port: 1433 }],
endpoint: "mydb",
options: undefined
});
});
});
describe("Error Handling", () => {
test("should throw error for invalid scheme", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
expect(() => parser.parse("mysql://user:pass@localhost:3306/mydb"))
.toThrow("URI must start with 'mssql://'");
});
test("should throw error for missing scheme", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
expect(() => parser.parse("user:pass@localhost:1433/mydb"))
.toThrow("No scheme found in URI");
});
});
describe("Special Characters", () => {
test("should handle special characters in username and password", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
const result = parser.parse("mssql://user%40domain:p%40ssw%3Ard@localhost:1433/mydb");
expect(result).toEqual({
scheme: "mssql",
username: "user@domain",
password: "p@ssw:rd",
hosts: [{ host: "localhost", port: 1433 }],
endpoint: "mydb",
options: undefined
});
});
test("should handle special characters in database name", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
const result = parser.parse("mssql://user:pass@localhost:1433/my%20db");
expect(result).toEqual({
scheme: "mssql",
username: "user",
password: "pass",
hosts: [{ host: "localhost", port: 1433 }],
endpoint: "my db",
options: undefined
});
});
});
describe("Multiple Hosts", () => {
test("should parse multiple hosts", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
const result = parser.parse("mssql://user:pass@host1:1433,host2:1434/mydb");
expect(result).toEqual({
scheme: "mssql",
username: "user",
password: "pass",
hosts: [
{ host: "host1", port: 1433 },
{ host: "host2", port: 1434 }
],
endpoint: "mydb",
options: undefined
});
});
test("should handle hosts without ports", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
const result = parser.parse("mssql://user:pass@host1,host2/mydb");
expect(result).toEqual({
scheme: "mssql",
username: "user",
password: "pass",
hosts: [
{ host: "host1" },
{ host: "host2" }
],
endpoint: "mydb",
options: undefined
});
});
});
describe("Provider-Specific Tests", () => {
test("should parse MySQL connection string", () => {
const parser = new ConnectionStringParser({ scheme: "mysql" });
const result = parser.parse("mysql://user:pass@localhost:3306/mydb?ssl=true");
expect(result).toEqual({
scheme: "mysql",
username: "user",
password: "pass",
hosts: [{ host: "localhost", port: 3306 }],
endpoint: "mydb",
options: { ssl: "true" }
});
});
test("should parse PostgreSQL connection string", () => {
const parser = new ConnectionStringParser({ scheme: "postgresql" });
const result = parser.parse("postgresql://user:pass@localhost:5432/mydb?sslmode=require");
expect(result).toEqual({
scheme: "postgresql",
username: "user",
password: "pass",
hosts: [{ host: "localhost", port: 5432 }],
endpoint: "mydb",
options: { sslmode: "require" }
});
});
test("should parse MSSQL connection string with encryption options", () => {
const parser = new ConnectionStringParser({ scheme: "mssql" });
const result = parser.parse("mssql://user:pass@localhost:1433/mydb?encrypt=true&trustServerCertificate=true");
expect(result).toEqual({
scheme: "mssql",
username: "user",
password: "pass",
hosts: [{ host: "localhost", port: 1433 }],
endpoint: "mydb",
options: {
encrypt: "true",
trustServerCertificate: "true"
}
});
});
});
}); | javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/chats/openaiHelpers.test.js | server/__tests__/utils/chats/openaiHelpers.test.js | /* eslint-env jest, node */
const { extractTextContent, extractAttachments } = require('../../../endpoints/api/openai/helpers');
describe('OpenAI Helper Functions', () => {
describe('extractTextContent', () => {
test('should return string content as-is when not an array', () => {
const content = 'Hello world';
expect(extractTextContent(content)).toBe('Hello world');
});
test('should extract text from multi-modal content array', () => {
const content = [
{
type: 'text',
text: 'What do you see in this image?'
},
{
type: 'image_url',
image_url: {
url: 'data:image/png;base64,abc123',
detail: 'low'
}
},
{
type: 'text',
text: 'And what about this part?'
}
];
expect(extractTextContent(content)).toBe('What do you see in this image?\nAnd what about this part?');
});
test('should handle empty array', () => {
expect(extractTextContent([])).toBe('');
});
test('should handle array with no text content', () => {
const content = [
{
type: 'image_url',
image_url: {
url: 'data:image/png;base64,abc123',
detail: 'low'
}
}
];
expect(extractTextContent(content)).toBe('');
});
});
describe('extractAttachments', () => {
test('should return empty array for string content', () => {
const content = 'Hello world';
expect(extractAttachments(content)).toEqual([]);
});
test('should extract image attachments with correct mime types', () => {
const content = [
{
type: 'image_url',
image_url: {
url: 'data:image/png;base64,abc123',
detail: 'low'
}
},
{
type: 'text',
text: 'Between images'
},
{
type: 'image_url',
image_url: {
url: 'data:image/jpeg;base64,def456',
detail: 'high'
}
}
];
expect(extractAttachments(content)).toEqual([
{
name: 'uploaded_image_0',
mime: 'image/png',
contentString: 'data:image/png;base64,abc123'
},
{
name: 'uploaded_image_1',
mime: 'image/jpeg',
contentString: 'data:image/jpeg;base64,def456'
}
]);
});
test('should handle invalid data URLs with PNG fallback', () => {
const content = [
{
type: 'image_url',
image_url: {
url: 'invalid-data-url',
detail: 'low'
}
}
];
expect(extractAttachments(content)).toEqual([
{
name: 'uploaded_image_0',
mime: 'image/png',
contentString: 'invalid-data-url'
}
]);
});
test('should handle empty array', () => {
expect(extractAttachments([])).toEqual([]);
});
test('should handle array with no image content', () => {
const content = [
{
type: 'text',
text: 'Just some text'
},
{
type: 'text',
text: 'More text'
}
];
expect(extractAttachments(content)).toEqual([]);
});
});
}); | javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/chats/openaiCompatible.test.js | server/__tests__/utils/chats/openaiCompatible.test.js | /* eslint-env jest, node */
const { OpenAICompatibleChat } = require('../../../utils/chats/openaiCompatible');
const { WorkspaceChats } = require('../../../models/workspaceChats');
const { getVectorDbClass, getLLMProvider } = require('../../../utils/helpers');
const { extractTextContent, extractAttachments } = require('../../../endpoints/api/openai/helpers');
// Mock dependencies
jest.mock('../../../models/workspaceChats');
jest.mock('../../../utils/helpers');
jest.mock('../../../utils/DocumentManager', () => ({
DocumentManager: class {
constructor() {
this.pinnedDocs = jest.fn().mockResolvedValue([]);
}
}
}));
describe('OpenAICompatibleChat', () => {
let mockWorkspace;
let mockVectorDb;
let mockLLMConnector;
let mockResponse;
beforeEach(() => {
// Reset all mocks
jest.clearAllMocks();
// Setup mock workspace
mockWorkspace = {
id: 1,
slug: 'test-workspace',
chatMode: 'chat',
chatProvider: 'openai',
chatModel: 'gpt-4',
};
// Setup mock VectorDb
mockVectorDb = {
hasNamespace: jest.fn().mockResolvedValue(true),
namespaceCount: jest.fn().mockResolvedValue(1),
performSimilaritySearch: jest.fn().mockResolvedValue({
contextTexts: [],
sources: [],
message: null,
}),
};
getVectorDbClass.mockReturnValue(mockVectorDb);
// Setup mock LLM connector
mockLLMConnector = {
promptWindowLimit: jest.fn().mockReturnValue(4000),
compressMessages: jest.fn().mockResolvedValue([]),
getChatCompletion: jest.fn().mockResolvedValue({
textResponse: 'Mock response',
metrics: {},
}),
streamingEnabled: jest.fn().mockReturnValue(true),
streamGetChatCompletion: jest.fn().mockResolvedValue({
metrics: {},
}),
handleStream: jest.fn().mockResolvedValue('Mock streamed response'),
defaultTemp: 0.7,
};
getLLMProvider.mockReturnValue(mockLLMConnector);
// Setup WorkspaceChats mock
WorkspaceChats.new.mockResolvedValue({ chat: { id: 'mock-chat-id' } });
// Setup mock response object for streaming
mockResponse = {
write: jest.fn(),
};
});
describe('chatSync', () => {
test('should handle OpenAI vision multimodal messages', async () => {
const multiModalPrompt = [
{
type: 'text',
text: 'What do you see in this image?'
},
{
type: 'image_url',
image_url: {
url: 'data:image/png;base64,abc123',
detail: 'low'
}
}
];
const prompt = extractTextContent(multiModalPrompt);
const attachments = extractAttachments(multiModalPrompt);
const result = await OpenAICompatibleChat.chatSync({
workspace: mockWorkspace,
prompt,
attachments,
systemPrompt: 'You are a helpful assistant',
history: [
{ role: 'user', content: 'Previous message' },
{ role: 'assistant', content: 'Previous response' }
],
temperature: 0.7
});
// Verify chat was saved with correct format
expect(WorkspaceChats.new).toHaveBeenCalledWith(
expect.objectContaining({
workspaceId: mockWorkspace.id,
prompt: multiModalPrompt[0].text,
response: expect.objectContaining({
text: 'Mock response',
attachments: [{
name: 'uploaded_image_0',
mime: 'image/png',
contentString: multiModalPrompt[1].image_url.url
}]
})
})
);
// Verify response format
expect(result).toEqual(
expect.objectContaining({
object: 'chat.completion',
choices: expect.arrayContaining([
expect.objectContaining({
message: expect.objectContaining({
role: 'assistant',
content: 'Mock response',
}),
}),
]),
})
);
});
test('should handle regular text messages in OpenAI format', async () => {
const promptString = 'Hello world';
const result = await OpenAICompatibleChat.chatSync({
workspace: mockWorkspace,
prompt: promptString,
systemPrompt: 'You are a helpful assistant',
history: [
{ role: 'user', content: 'Previous message' },
{ role: 'assistant', content: 'Previous response' }
],
temperature: 0.7
});
// Verify chat was saved without attachments
expect(WorkspaceChats.new).toHaveBeenCalledWith(
expect.objectContaining({
workspaceId: mockWorkspace.id,
prompt: promptString,
response: expect.objectContaining({
text: 'Mock response',
attachments: []
})
})
);
expect(result).toBeTruthy();
});
});
describe('streamChat', () => {
test('should handle OpenAI vision multimodal messages in streaming mode', async () => {
const multiModalPrompt = [
{
type: 'text',
text: 'What do you see in this image?'
},
{
type: 'image_url',
image_url: {
url: 'data:image/png;base64,abc123',
detail: 'low'
}
}
];
const prompt = extractTextContent(multiModalPrompt);
const attachments = extractAttachments(multiModalPrompt);
await OpenAICompatibleChat.streamChat({
workspace: mockWorkspace,
response: mockResponse,
prompt,
attachments,
systemPrompt: 'You are a helpful assistant',
history: [
{ role: 'user', content: 'Previous message' },
{ role: 'assistant', content: 'Previous response' }
],
temperature: 0.7
});
// Verify streaming was handled
expect(mockLLMConnector.streamGetChatCompletion).toHaveBeenCalled();
expect(mockLLMConnector.handleStream).toHaveBeenCalled();
// Verify chat was saved with attachments
expect(WorkspaceChats.new).toHaveBeenCalledWith(
expect.objectContaining({
workspaceId: mockWorkspace.id,
prompt: multiModalPrompt[0].text,
response: expect.objectContaining({
text: 'Mock streamed response',
attachments: [{
name: 'uploaded_image_0',
mime: 'image/png',
contentString: multiModalPrompt[1].image_url.url
}]
})
})
);
});
test('should handle regular text messages in streaming mode', async () => {
const promptString = 'Hello world';
await OpenAICompatibleChat.streamChat({
workspace: mockWorkspace,
response: mockResponse,
prompt: promptString,
systemPrompt: 'You are a helpful assistant',
history: [
{ role: 'user', content: 'Previous message' },
{ role: 'assistant', content: 'Previous response' }
],
temperature: 0.7
});
// Verify streaming was handled
expect(mockLLMConnector.streamGetChatCompletion).toHaveBeenCalled();
expect(mockLLMConnector.handleStream).toHaveBeenCalled();
// Verify chat was saved without attachments
expect(WorkspaceChats.new).toHaveBeenCalledWith(
expect.objectContaining({
workspaceId: mockWorkspace.id,
prompt: promptString,
response: expect.objectContaining({
text: 'Mock streamed response',
attachments: []
})
})
);
});
});
}); | javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/safeJSONStringify/safeJSONStringify.test.js | server/__tests__/utils/safeJSONStringify/safeJSONStringify.test.js | /* eslint-env jest */
const { safeJSONStringify } = require("../../../utils/helpers/chat/responses");
describe("safeJSONStringify", () => {
test("handles regular objects without BigInt", () => {
const obj = { a: 1, b: "test", c: true, d: null };
expect(safeJSONStringify(obj)).toBe(JSON.stringify(obj));
});
test("converts BigInt to string", () => {
const bigInt = BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1);
expect(safeJSONStringify(bigInt)).toBe(`"${bigInt.toString()}"`);
});
test("handles nested BigInt values", () => {
const obj = {
metrics: {
tokens: BigInt(123),
nested: { moreBigInt: BigInt(456) }
},
normal: "value"
};
expect(safeJSONStringify(obj)).toBe(
'{"metrics":{"tokens":"123","nested":{"moreBigInt":"456"}},"normal":"value"}'
);
});
test("handles arrays with BigInt", () => {
const arr = [BigInt(1), 2, BigInt(3)];
expect(safeJSONStringify(arr)).toBe('["1",2,"3"]');
});
test("handles mixed complex objects", () => {
const obj = {
id: 1,
bigNums: [BigInt(123), BigInt(456)],
nested: {
more: { huge: BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1) }
},
normal: { str: "test", num: 42, bool: true, nil: null, sub_arr: ["alpha", "beta", "gamma", 1, 2, BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1), { map: { a: BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1) } }] }
};
const result = JSON.parse(safeJSONStringify(obj)); // Should parse back without errors
expect(typeof result.bigNums[0]).toBe("string");
expect(result.bigNums[0]).toEqual("123");
expect(typeof result.nested.more.huge).toBe("string");
expect(result.normal).toEqual({ str: "test", num: 42, bool: true, nil: null, sub_arr: ["alpha", "beta", "gamma", 1, 2, (BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)).toString(), { map: { a: (BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)).toString() } }] });
expect(result.normal.sub_arr[6].map.a).toEqual((BigInt(Number.MAX_SAFE_INTEGER) + BigInt(1)).toString());
});
test("handles invariants", () => {
expect(safeJSONStringify({})).toBe("{}");
expect(safeJSONStringify(null)).toBe("null");
expect(safeJSONStringify(undefined)).toBe(undefined);
expect(safeJSONStringify(true)).toBe("true");
expect(safeJSONStringify(false)).toBe("false");
expect(safeJSONStringify(0)).toBe("0");
expect(safeJSONStringify(1)).toBe("1");
expect(safeJSONStringify(-1)).toBe("-1");
});
}); | javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/__tests__/utils/TextSplitter/index.test.js | server/__tests__/utils/TextSplitter/index.test.js | const { TextSplitter } = require("../../../utils/TextSplitter");
const _ = require("lodash");
describe("TextSplitter", () => {
test("should split long text into n sized chunks", async () => {
const text = "This is a test text to be split into chunks".repeat(2);
const textSplitter = new TextSplitter({
chunkSize: 20,
chunkOverlap: 0,
});
const chunks = await textSplitter.splitText(text);
expect(chunks.length).toEqual(5);
});
test("applies chunk overlap of 20 characters on invalid chunkOverlap", async () => {
const text = "This is a test text to be split into chunks".repeat(2);
const textSplitter = new TextSplitter({
chunkSize: 30,
});
const chunks = await textSplitter.splitText(text);
expect(chunks.length).toEqual(6);
});
test("does not allow chunkOverlap to be greater than chunkSize", async () => {
expect(() => {
new TextSplitter({
chunkSize: 20,
chunkOverlap: 21,
});
}).toThrow();
});
test("applies specific metadata to stringifyHeader to each chunk", async () => {
const metadata = {
id: "123e4567-e89b-12d3-a456-426614174000",
url: "https://example.com",
title: "Example",
docAuthor: "John Doe",
published: "2021-01-01",
chunkSource: "link://https://example.com",
description: "This is a test text to be split into chunks",
};
const chunkHeaderMeta = TextSplitter.buildHeaderMeta(metadata);
expect(chunkHeaderMeta).toEqual({
sourceDocument: metadata.title,
source: metadata.url,
published: metadata.published,
});
});
test("applies a valid chunkPrefix to each chunk", async () => {
const text = "This is a test text to be split into chunks".repeat(2);
let textSplitter = new TextSplitter({
chunkSize: 20,
chunkOverlap: 0,
chunkPrefix: "testing: ",
});
let chunks = await textSplitter.splitText(text);
expect(chunks.length).toEqual(5);
expect(chunks.every(chunk => chunk.startsWith("testing: "))).toBe(true);
textSplitter = new TextSplitter({
chunkSize: 20,
chunkOverlap: 0,
chunkPrefix: "testing2: ",
});
chunks = await textSplitter.splitText(text);
expect(chunks.length).toEqual(5);
expect(chunks.every(chunk => chunk.startsWith("testing2: "))).toBe(true);
textSplitter = new TextSplitter({
chunkSize: 20,
chunkOverlap: 0,
chunkPrefix: undefined,
});
chunks = await textSplitter.splitText(text);
expect(chunks.length).toEqual(5);
expect(chunks.every(chunk => !chunk.startsWith(": "))).toBe(true);
textSplitter = new TextSplitter({
chunkSize: 20,
chunkOverlap: 0,
chunkPrefix: "",
});
chunks = await textSplitter.splitText(text);
expect(chunks.length).toEqual(5);
expect(chunks.every(chunk => !chunk.startsWith(": "))).toBe(true);
// Applied chunkPrefix with chunkHeaderMeta
textSplitter = new TextSplitter({
chunkSize: 20,
chunkOverlap: 0,
chunkHeaderMeta: TextSplitter.buildHeaderMeta({
title: "Example",
url: "https://example.com",
published: "2021-01-01",
}),
chunkPrefix: "testing3: ",
});
chunks = await textSplitter.splitText(text);
expect(chunks.length).toEqual(5);
expect(chunks.every(chunk => chunk.startsWith("testing3: <document_metadata>"))).toBe(true);
});
});
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
Mintplex-Labs/anything-llm | https://github.com/Mintplex-Labs/anything-llm/blob/e287fab56089cf8fcea9ba579a3ecdeca0daa313/server/prisma/seed.js | server/prisma/seed.js | const { PrismaClient } = require("@prisma/client");
const prisma = new PrismaClient();
async function main() {
const settings = [
{ label: "multi_user_mode", value: "false" },
{ label: "logo_filename", value: "anything-llm.png" },
];
for (let setting of settings) {
const existing = await prisma.system_settings.findUnique({
where: { label: setting.label },
});
// Only create the setting if it doesn't already exist
if (!existing) {
await prisma.system_settings.create({
data: setting,
});
}
}
}
main()
.catch((e) => {
console.error(e);
process.exit(1);
})
.finally(async () => {
await prisma.$disconnect();
});
| javascript | MIT | e287fab56089cf8fcea9ba579a3ecdeca0daa313 | 2026-01-04T14:57:11.963777Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/.eslintrc.js | .eslintrc.js | module.exports = {
root: true,
parserOptions: {
parser: '@babel/eslint-parser',
ecmaVersion: 11,
ecmaFeatures: {
impliedStrict: true
},
sourceType: 'module'
},
env: {
browser: true,
es6: true,
node: true
},
extends: [
'standard',
'eslint:recommended',
'plugin:vue/base',
'plugin:import/errors',
'plugin:import/warnings'
],
globals: {
__static: true
},
plugins: ['html', 'vue'],
rules: {
// Two spaces but disallow semicolons
indent: ['error', 2, { 'SwitchCase': 1, 'ignoreComments': true }],
semi: [2, 'never'],
'no-return-await': 'error',
'no-return-assign': 'error',
'no-new': 'error',
// allow paren-less arrow functions
'arrow-parens': 'off',
// allow console
'no-console': 'off',
// allow debugger during development
'no-debugger': process.env.NODE_ENV === 'production' ? 'error' : 'off',
'require-atomic-updates': 'off',
// TODO: fix these errors someday
'prefer-const': 'off',
'no-mixed-operators': 'off',
'no-prototype-builtins': 'off'
},
settings: {
'import/resolver': {
alias: {
map: [
['common', './src/common'],
// Normally only valid for renderer/
['@', './src/renderer'],
['muya', './src/muya']
],
extensions: ['.js', '.vue', '.json', '.css', '.node']
}
}
},
ignorePatterns: [
'node_modules',
'src/muya/dist/**/*',
'src/muya/webpack.config.js'
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/babel.config.js | babel.config.js | const proposalClassProperties = require('@babel/plugin-proposal-class-properties')
const syntaxClassProperties = require('@babel/plugin-syntax-class-properties')
const transformRuntime = require('@babel/plugin-transform-runtime')
const syntaxDynamicImport = require('@babel/plugin-syntax-dynamic-import')
const functionBind = require('@babel/plugin-proposal-function-bind')
const exportDefault = require('@babel/plugin-proposal-export-default-from')
const isTanbul = require('babel-plugin-istanbul')
const component = require('babel-plugin-component')
const presetEnv = require('@babel/preset-env')
const presetsHash = {
test: [
[presetEnv,
{
targets: { 'node': 16 }
}]
],
main: [
[presetEnv,
{
targets: { 'node': 16 }
}]
],
renderer: [
[presetEnv,
{
useBuiltIns: false,
targets: {
electron: require('electron/package.json').version,
node: 16
}
}]
]
}
module.exports = function (api) {
const plugins = [ proposalClassProperties, syntaxClassProperties, transformRuntime, syntaxDynamicImport, functionBind, exportDefault ]
const env = api.env()
const presets = presetsHash[env]
if (env === 'test') {
plugins.push(isTanbul)
} else if (env === 'renderer') {
plugins.push(
[component, {
style: false,
libraryName: 'element-ui'
}
])
}
return {
presets,
plugins
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/vetur.config.js | vetur.config.js | module.exports = {
projects: [
{
root: './src/renderer',
package: '../../package.json',
tsconfig: './jsconfig.json'
}
]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/tools/validateLicenses.js | tools/validateLicenses.js | 'use strict'
const path = require('path')
const thirdPartyChecker = require('../.electron-vue/thirdPartyChecker.js')
const rootDir = path.resolve(__dirname, '..')
thirdPartyChecker.validateLicenses(rootDir)
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/tools/deobfuscateStackTrace.js | tools/deobfuscateStackTrace.js | const fs = require('fs')
const readline = require('readline')
const arg = require('arg')
const sourceMap = require('source-map')
const stackTraceParser = require('stacktrace-parser')
const spec = {
'--map': String,
'-m': '--map'
}
const args = arg(spec, { argv: process.argv.slice(1), permissive: true })
const mapPath = args['--map']
if (!mapPath) {
console.log('ERROR: -m is a required argument.\n')
console.log('USAGE:\n yarn deobfuscateStackTrace -m <path_to_source_map>')
process.exit(1)
} else if (!fs.existsSync(mapPath)) {
console.log(`ERROR: Invalid source map path: "${mapPath}".`)
process.exit(1)
}
const deobfuscateStackTrace = stackTraceStr => {
const smc = new sourceMap.SourceMapConsumer(fs.readFileSync(mapPath, 'utf8'))
const stack = stackTraceParser.parse(stackTraceStr)
if (stack.length === 0) {
throw new Error('Invalid stack trace.')
}
const errorMessage = stackTraceStr.split('\n').find(line => line.trim().length > 0)
if (errorMessage) {
console.log(errorMessage)
}
stack.forEach(({ methodName, lineNumber, column }) => {
try {
if (lineNumber == null || lineNumber < 1) {
console.log(` at ${methodName || ''}`)
} else {
const pos = smc.originalPositionFor({ line: lineNumber, column })
if (pos && pos.line != null) {
console.log(` at ${pos.name || ''} (${pos.source}:${pos.line}:${pos.column})`)
}
}
} catch (err) {
console.log(` Failed to parse line ${lineNumber} on column ${column}.`)
}
})
}
console.log('Please paste the stack trace and continue with double Enter:')
const lines = []
readline.createInterface({
input: process.stdin,
terminal: false
}).on('line', line => {
if (!line || line === '') {
console.log('Deobfuscated stack trace:')
deobfuscateStackTrace(lines.join('\n'))
process.exit(0)
}
lines.push(line)
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/tools/generateThirdPartyLicense.js | tools/generateThirdPartyLicense.js | 'use strict'
const path = require('path')
const fs = require('fs')
const thirdPartyChecker = require('../.electron-vue/thirdPartyChecker.js')
const rootDir = path.resolve(__dirname, '..')
const additionalPackages = {
hunspell: {
packageName: 'Hunspell',
licenses: 'LGPL 2.1',
licenseText: fs.readFileSync(path.join(rootDir, 'resources/hunspell_dictionaries/LICENSE-hunspell.txt'))
}
}
thirdPartyChecker.getLicenses(rootDir, (err, packages, checker) => {
if (err) {
console.log(`[ERROR] ${err}`)
return
}
Object.assign(packages, additionalPackages)
let summary = ''
let licenseList = ''
let index = 1
const addedKeys = {}
Object.keys(packages).forEach(key => {
if (/^babel-helper-vue-jsx-merge-props/.test(key) ||
/^marktext/.test(key)) {
// babel-helper-vue-jsx-merge-props: MIT licensed used by element-ui
return
}
let packageName = key
const nameRegex = /(^.+)(?:@)/.exec(key)
if (nameRegex && nameRegex[1]) {
packageName = nameRegex[1]
}
// Check if we already added this package
if (addedKeys.hasOwnProperty(packageName)) {
return
}
addedKeys[packageName] = 1
const { licenses, licenseText } = packages[key]
summary += `${index++}. ${packageName} (${licenses})\n`
licenseList += `# ${packageName} (${licenses})
-------------------------------------------------\
${licenseText}
\n\n
`
})
const output = `# Third Party Notices
-------------------------------------------------
This file contains all third-party packages that are bundled and shipped with MarkText.
-------------------------------------------------
# Summary
-------------------------------------------------
${summary}
-------------------------------------------------
# Licenses
-------------------------------------------------
${licenseList}
`
fs.writeFileSync(path.resolve(rootDir, 'resources', 'THIRD-PARTY-LICENSES.txt'), output)
})
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/main.js | src/renderer/main.js | import Vue from 'vue'
import VueElectron from 'vue-electron'
import sourceMapSupport from 'source-map-support'
import bootstrapRenderer from './bootstrap'
import VueRouter from 'vue-router'
import lang from 'element-ui/lib/locale/lang/en'
import locale from 'element-ui/lib/locale'
import axios from './axios'
import store from './store'
import './assets/symbolIcon'
import {
Dialog,
Form,
FormItem,
InputNumber,
Button,
Tooltip,
Upload,
Slider,
Checkbox,
ColorPicker,
Col,
Row,
Tree,
Autocomplete,
Switch,
Select,
Option,
Radio,
RadioGroup,
Table,
TableColumn,
Tabs,
TabPane,
Input
} from 'element-ui'
import services from './services'
import routes from './router'
import { addElementStyle } from '@/util/theme'
import './assets/styles/index.css'
import './assets/styles/printService.css'
// -----------------------------------------------
// Decode source map in production - must be registered first
sourceMapSupport.install({
environment: 'node',
handleUncaughtExceptions: false,
hookRequire: false
})
global.marktext = {}
bootstrapRenderer()
addElementStyle()
// -----------------------------------------------
// Be careful when changing code before this line!
// Configure Vue
locale.use(lang)
Vue.use(Dialog)
Vue.use(Form)
Vue.use(FormItem)
Vue.use(InputNumber)
Vue.use(Button)
Vue.use(Tooltip)
Vue.use(Upload)
Vue.use(Slider)
Vue.use(Checkbox)
Vue.use(ColorPicker)
Vue.use(Col)
Vue.use(Row)
Vue.use(Tree)
Vue.use(Autocomplete)
Vue.use(Switch)
Vue.use(Select)
Vue.use(Option)
Vue.use(Radio)
Vue.use(RadioGroup)
Vue.use(Table)
Vue.use(TableColumn)
Vue.use(Tabs)
Vue.use(TabPane)
Vue.use(Input)
Vue.use(VueRouter)
Vue.use(VueElectron)
Vue.http = Vue.prototype.$http = axios
Vue.config.productionTip = false
services.forEach(s => {
Vue.prototype['$' + s.name] = s[s.name]
})
const router = new VueRouter({
routes: routes(global.marktext.env.type)
})
/* eslint-disable no-new */
new Vue({
store,
router,
template: '<router-view class="view"></router-view>'
}).$mount('#app')
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/config.js | src/renderer/config.js | import path from 'path'
export const PATH_SEPARATOR = path.sep
export const THEME_STYLE_ID = 'ag-theme'
export const COMMON_STYLE_ID = 'ag-common-style'
export const DEFAULT_EDITOR_FONT_FAMILY = '"Open Sans", "Clear Sans", "Helvetica Neue", Helvetica, Arial, sans-serif, Segoe UI Emoji, Apple Color Emoji, "Noto Color Emoji"'
export const DEFAULT_CODE_FONT_FAMILY = '"DejaVu Sans Mono", "Source Code Pro", "Droid Sans Mono", monospace'
export const DEFAULT_STYLE = Object.freeze({
codeFontFamily: DEFAULT_CODE_FONT_FAMILY,
codeFontSize: '14px',
hideScrollbar: false,
theme: 'light'
})
export const railscastsThemes = Object.freeze(['dark', 'material-dark'])
export const oneDarkThemes = Object.freeze(['one-dark'])
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/bootstrap.js | src/renderer/bootstrap.js | import path from 'path'
import { ipcRenderer } from 'electron'
import log from 'electron-log'
import RendererPaths from './node/paths'
let exceptionLogger = s => console.error(s)
const configureLogger = () => {
const { debug, paths, windowId } = global.marktext.env
log.transports.console.level = process.env.NODE_ENV === 'development' ? 'info' : false // mirror to window console
log.transports.mainConsole = null
log.transports.file.resolvePath = () => path.join(paths.logPath, `editor-${windowId}.log`)
log.transports.file.level = debug ? 'debug' : 'info'
log.transports.file.sync = false
exceptionLogger = log.error
}
const parseUrlArgs = () => {
const params = new URLSearchParams(window.location.search)
const codeFontFamily = params.get('cff')
const codeFontSize = params.get('cfs')
const debug = params.get('debug') === '1'
const hideScrollbar = params.get('hsb') === '1'
const theme = params.get('theme')
const titleBarStyle = params.get('tbs')
const userDataPath = params.get('udp')
const windowId = Number(params.get('wid'))
const type = params.get('type')
if (Number.isNaN(windowId)) {
throw new Error('Error while parsing URL arguments: windowId!')
}
return {
type,
debug,
userDataPath,
windowId,
initialState: {
codeFontFamily,
codeFontSize,
hideScrollbar,
theme,
titleBarStyle
}
}
}
const bootstrapRenderer = () => {
// Register renderer exception handler
window.addEventListener('error', event => {
if (event.error) {
const { message, name, stack } = event.error
const copy = {
message,
name,
stack
}
exceptionLogger(event.error)
// Pass exception to main process exception handler to show a error dialog.
ipcRenderer.send('mt::handle-renderer-error', copy)
} else {
console.error(event)
}
})
const {
debug,
initialState,
userDataPath,
windowId,
type
} = parseUrlArgs()
const paths = new RendererPaths(userDataPath)
const marktext = {
initialState,
env: {
debug,
paths,
windowId,
type
},
paths
}
global.marktext = marktext
configureLogger()
}
export default bootstrapRenderer
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/services/index.js | src/renderer/services/index.js | import notification from './notification'
export default [
notification
]
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/services/printService.js | src/renderer/services/printService.js | import { getImageInfo } from 'muya/lib/utils'
class MarkdownPrint {
/**
* Prepare document export and append a hidden print container to the window.
*
* @param {string} html HTML string
* @param {boolean} [renderStatic] Render for static files like PDF documents
*/
renderMarkdown (html, renderStatic = false) {
this.clearup()
const printContainer = document.createElement('article')
printContainer.classList.add('print-container')
this.container = printContainer
printContainer.innerHTML = html
// Fix images when rendering for static files like PDF (GH#678).
if (renderStatic) {
// Traverse through the DOM tree and fix all relative image sources.
const images = printContainer.getElementsByTagName('img')
for (const image of images) {
const rawSrc = image.getAttribute('src')
image.src = getImageInfo(rawSrc).src
}
}
document.body.appendChild(printContainer)
}
/**
* Remove the print container from the window.
*/
clearup () {
if (this.container) {
this.container.remove()
}
}
}
export default MarkdownPrint
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/services/notification/index.js | src/renderer/services/notification/index.js | import template from './index.html'
import { getUniqueId } from '../../util'
import { sanitize, EXPORT_DOMPURIFY_CONFIG } from '../../util/dompurify'
import './index.css'
const INON_HASH = {
primary: 'icon-message',
error: 'icon-error',
warning: 'icon-warn',
info: 'icon-info'
}
const TYPE_HASH = {
primary: 'mt-primary',
error: 'mt-error',
warning: 'mt-warn',
info: 'mt-info'
}
const fillTemplate = (type, title, message) => {
return template
.replace(/\{\{icon\}\}/, INON_HASH[type])
.replace(/\{\{title\}\}/, sanitize(title, EXPORT_DOMPURIFY_CONFIG))
.replace(/\{\{message\}\}/, sanitize(message, EXPORT_DOMPURIFY_CONFIG))
}
const notification = {
name: 'notify',
noticeCache: {},
clear () {
Object.keys(this.noticeCache).forEach(key => {
this.noticeCache[key].remove()
})
},
notify ({
time = 10000,
title = '',
message = '',
type = 'primary', // primary, error, warning or info
showConfirm = false
}) {
let rs
let rj
let timer = null
const id = getUniqueId()
const fragment = document.createElement('div')
fragment.innerHTML = fillTemplate(type, title, message)
const noticeContainer = fragment.querySelector('.mt-notification')
const bgNotice = noticeContainer.querySelector('.notice-bg')
const contentContainer = noticeContainer.querySelector('.content')
const fluent = noticeContainer.querySelector('.fluent')
const close = noticeContainer.querySelector('.close')
const { offsetHeight } = noticeContainer
let target = noticeContainer
if (showConfirm) {
noticeContainer.classList.add('mt-confirm')
target = noticeContainer.querySelector('.confirm')
}
noticeContainer.classList.add(TYPE_HASH[type])
contentContainer.classList.add(TYPE_HASH[type])
bgNotice.classList.add(TYPE_HASH[type])
fluent.style.height = offsetHeight * 2 + 'px'
fluent.style.width = offsetHeight * 2 + 'px'
const setCloseTimer = () => {
if (typeof time === 'number' && time > 0) {
timer = setTimeout(() => {
remove()
}, time)
}
}
const mousemoveHandler = event => {
const { left, top } = noticeContainer.getBoundingClientRect()
const x = event.pageX
const y = event.pageY
fluent.style.left = x - left + 'px'
fluent.style.top = y - top + 'px'
fluent.style.opacity = '1'
fluent.style.height = noticeContainer.offsetHeight * 2 + 'px'
fluent.style.width = noticeContainer.offsetHeight * 2 + 'px'
if (timer) clearTimeout(timer)
}
const mouseleaveHandler = event => {
fluent.style.opacity = '0'
fluent.style.height = noticeContainer.offsetHeight * 4 + 'px'
fluent.style.width = noticeContainer.offsetHeight * 4 + 'px'
if (timer) clearTimeout(timer)
setCloseTimer()
}
const clickHandler = event => {
event.preventDefault()
event.stopPropagation()
remove()
rs && rs()
}
const closeHandler = event => {
event.preventDefault()
event.stopPropagation()
remove()
rj && rj()
}
const rePositionNotices = () => {
const notices = document.querySelectorAll('.mt-notification')
let i
let hx = 0
const len = notices.length
for (i = 0; i < len; i++) {
notices[i].style.transform = `translate(0, -${hx}px)`
notices[i].style.zIndex = 10000 - i
hx += notices[i].offsetHeight + 10
}
}
const remove = () => {
fluent.style.filter = 'blur(10px)'
fluent.style.opacity = '0'
fluent.style.height = noticeContainer.offsetHeight * 5 + 'px'
fluent.style.width = noticeContainer.offsetHeight * 5 + 'px'
noticeContainer.style.opacity = '0'
noticeContainer.style.right = '-400px'
setTimeout(() => {
noticeContainer.removeEventListener('mousemove', mousemoveHandler)
noticeContainer.removeEventListener('mouseleave', mouseleaveHandler)
target.removeEventListener('click', clickHandler)
close.removeEventListener('click', closeHandler)
noticeContainer.remove()
rePositionNotices()
if (this.noticeCache[id]) {
delete this.noticeCache[id]
}
}, 100)
}
this.noticeCache[id] = { remove }
noticeContainer.addEventListener('mousemove', mousemoveHandler)
noticeContainer.addEventListener('mouseleave', mouseleaveHandler)
target.addEventListener('click', clickHandler)
close.addEventListener('click', closeHandler)
setTimeout(() => {
bgNotice.style.width = noticeContainer.offsetWidth * 3.5 + 'px'
bgNotice.style.height = noticeContainer.offsetWidth * 3.5 + 'px'
rePositionNotices()
}, 50)
setCloseTimer()
document.body.prepend(noticeContainer, document.body.firstChild)
return new Promise((resolve, reject) => {
rs = resolve
rj = reject
})
}
}
export default notification
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/pdf.js | src/renderer/util/pdf.js | import fs from 'fs'
import path from 'path'
import Slugger from 'muya/lib/parser/marked/slugger'
import { isFile } from 'common/filesystem'
import { escapeHTML, unescapeHTML } from 'muya/lib/utils'
import academicTheme from '@/assets/themes/export/academic.theme.css'
import liberTheme from '@/assets/themes/export/liber.theme.css'
import { cloneObj } from '../util'
import { sanitize, EXPORT_DOMPURIFY_CONFIG } from '../util/dompurify'
export const getCssForOptions = options => {
const {
type,
pageMarginTop,
pageMarginRight,
pageMarginBottom,
pageMarginLeft,
fontFamily,
fontSize,
lineHeight,
autoNumberingHeadings,
showFrontMatter,
theme,
headerFooterFontSize
} = options
const isPrintable = type !== 'styledHtml'
let output = ''
if (isPrintable) {
output += `@media print{@page{
margin: ${pageMarginTop}mm ${pageMarginRight}mm ${pageMarginBottom}mm ${pageMarginLeft}mm;}`
}
// Font options
output += '.markdown-body{'
if (fontFamily) {
output += `font-family:"${fontFamily}",${FALLBACK_FONT_FAMILIES};`
output = `.hf-container{font-family:"${fontFamily}",${FALLBACK_FONT_FAMILIES};}${output}`
}
if (fontSize) {
output += `font-size:${fontSize}px;`
}
if (lineHeight) {
output += `line-height:${lineHeight};`
}
output += '}'
// Auto numbering headings via CSS
if (autoNumberingHeadings) {
output += autoNumberingHeadingsCss
}
// Hide front matter
if (!showFrontMatter) {
output += 'pre.front-matter{display:none!important;}'
}
if (theme) {
if (theme === 'academic') {
output += academicTheme
} else if (theme === 'liber') {
output += liberTheme
} else {
// Read theme from disk
const { userDataPath } = global.marktext.paths
const themePath = path.join(userDataPath, 'themes/export', theme)
if (isFile(themePath)) {
try {
const themeCSS = fs.readFileSync(themePath, 'utf8')
output += themeCSS
} catch (_) {
// No-op
}
}
}
}
if (headerFooterFontSize) {
output += `.page-header .hf-container,
.page-footer-fake .hf-container,
.page-footer .hf-container {
font-size: ${headerFooterFontSize}px;
}`
}
if (isPrintable) {
// Close @page
output += '}'
}
return unescapeHTML(sanitize(escapeHTML(output), EXPORT_DOMPURIFY_CONFIG))
}
const generateHtmlToc = (tocList, slugger, currentLevel, options) => {
if (!tocList || tocList.length === 0) {
return ''
}
const topLevel = tocList[0].lvl
if (!options.tocIncludeTopHeading && topLevel <= 1) {
tocList.shift()
return generateHtmlToc(tocList, slugger, currentLevel, options)
} else if (topLevel <= currentLevel) {
return ''
}
const { content, lvl } = tocList.shift()
const slug = slugger.slug(content)
let html = `<li><span><a class="toc-h${lvl}" href="#${slug}">${content}</a><span class="dots"></span></span>`
// Generate sub-items
if (tocList.length !== 0 && tocList[0].lvl > lvl) {
html += '<ul>' + generateHtmlToc(tocList, slugger, lvl, options) + '</ul>'
}
html += '</li>' + generateHtmlToc(tocList, slugger, currentLevel, options)
return html
}
export const getHtmlToc = (toc, options = {}) => {
const list = cloneObj(toc)
const slugger = new Slugger()
const tocList = generateHtmlToc(list, slugger, 0, options)
if (!tocList) {
return ''
}
const title = options.tocTitle ? options.tocTitle : 'Table of Contents'
const html = `<div class="toc-container"><p class="toc-title">${title}</p><ul class="toc-list">${tocList}</ul></div>`
return sanitize(html, EXPORT_DOMPURIFY_CONFIG)
}
// Don't use "Noto Color Emoji" because it will result in PDF files with multiple MB and weird looking emojis.
const FALLBACK_FONT_FAMILIES = '"Open Sans","Segoe UI","Helvetica Neue",Helvetica,Arial,sans-serif,"Apple Color Emoji","Segoe UI Emoji"'
const autoNumberingHeadingsCss = `body {counter-reset: h2}
h2 {counter-reset: h3}
h3 {counter-reset: h4}
h4 {counter-reset: h5}
h5 {counter-reset: h6}
h2:before {counter-increment: h2; content: counter(h2) ". "}
h3:before {counter-increment: h3; content: counter(h2) "." counter(h3) ". "}
h4:before {counter-increment: h4; content: counter(h2) "." counter(h3) "." counter(h4) ". "}
h5:before {counter-increment: h5; content: counter(h2) "." counter(h3) "." counter(h4) "." counter(h5) ". "}
h6:before {counter-increment: h6; content: counter(h2) "." counter(h3) "." counter(h4) "." counter(h5) "." counter(h6) ". "}
h2.nocount:before, h3.nocount:before, h4.nocount:before, h5.nocount:before, h6.nocount:before { content: ""; counter-increment: none }`
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/markdownToHtml.js | src/renderer/util/markdownToHtml.js | import ExportHtml from 'muya/lib/utils/exportHtml'
const markdownToHtml = async markdown => {
const html = await new ExportHtml(markdown).renderHtml()
return `<article class="markdown-body">${html}</article>`
}
export default markdownToHtml
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/themeColor.js | src/renderer/util/themeColor.js | import darkTheme from '../assets/themes/dark.theme.css'
import graphiteTheme from '../assets/themes/graphite.theme.css'
import materialDarkTheme from '../assets/themes/material-dark.theme.css'
import oneDarkTheme from '../assets/themes/one-dark.theme.css'
import ulyssesTheme from '../assets/themes/ulysses.theme.css'
import darkPrismTheme from '../assets/themes/prismjs/dark.theme.css'
import oneDarkPrismTheme from '../assets/themes/prismjs/one-dark.theme.css'
export const dark = () => {
return darkTheme + '\n' + darkPrismTheme
}
export const graphite = () => {
return graphiteTheme
}
export const materialDark = () => {
return materialDarkTheme + '\n' + darkPrismTheme
}
export const oneDark = () => {
return oneDarkTheme + '\n' + oneDarkPrismTheme
}
export const ulysses = () => {
return ulyssesTheme
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/index.js | src/renderer/util/index.js | export const delay = time => {
let timerId
let rejectFn
const p = new Promise((resolve, reject) => {
rejectFn = reject
timerId = setTimeout(() => {
p.cancel = () => {}
rejectFn = null
resolve()
}, time)
})
p.cancel = () => {
clearTimeout(timerId)
timerId = null
rejectFn()
rejectFn = null
}
return p
}
const ID_PREFEX = 'mt-'
let id = 0
export const serialize = function (params) {
return Object.keys(params).map(key => `${key}=${encodeURI(params[key])}`).join('&')
}
export const merge = function (...args) {
return Object.assign({}, ...args)
}
export const dataURItoBlob = function (dataURI) {
const data = dataURI.split(';base64,')
const byte = window.atob(data[1])
const mime = data[0].split(':')[1]
const ab = new ArrayBuffer(byte.length)
const ia = new Uint8Array(ab)
const len = byte.length
let i
for (i = 0; i < len; i++) {
ia[i] = byte.charCodeAt(i)
}
return new window.Blob([ab], { type: mime })
}
export const adjustCursor = (cursor, preline, line, nextline) => {
let newCursor = Object.assign({}, { line: cursor.line, ch: cursor.ch })
// It's need to adjust the cursor when cursor is at begin or end in table row.
if (/\|[^|]+\|.+\|\s*$/.test(line)) {
if (/\|\s*:?-+:?\s*\|[:-\s|]+\|\s*$/.test(line)) { // cursor in `| --- | :---: |` :the second line of table
newCursor.line += 1 // reset the cursor to the next line
newCursor.ch = nextline.indexOf('|') + 1
} else { // cursor is not at the second line to table
if (cursor.ch <= line.indexOf('|')) newCursor.ch = line.indexOf('|') + 1
if (cursor.ch >= line.lastIndexOf('|')) newCursor.ch = line.lastIndexOf('|') - 1
}
}
// Need to adjust the cursor when cursor in the first or last line of code/math block.
if (/```[\S]*/.test(line) || /^\$\$$/.test(line)) {
if (typeof nextline === 'string' && /\S/.test(nextline)) {
newCursor.line += 1
newCursor.ch = 0
} else if (typeof preline === 'string' && /\S/.test(preline)) {
newCursor.line -= 1
newCursor.ch = preline.length
}
}
// Need to adjust the cursor when cursor at the begin of the list
if (/[*+-]\s.+/.test(line) && newCursor.ch <= 1) {
newCursor.ch = 2
}
// Need to adjust the cursor when cursor at blank line or in a line contains HTML tag.
// set the newCursor to null, the new cursor will at the last line of document.
if (!/\S/.test(line) || /<\/?([a-zA-Z\d-]+)(?=\s|>).*>/.test(line)) {
newCursor = null
}
return newCursor
}
export const animatedScrollTo = function (element, to, duration, callback) {
const start = element.scrollTop
const change = to - start
const animationStart = +new Date()
// Prevent animation on small steps or duration is 0
if (Math.abs(change) <= 6 || duration === 0) {
element.scrollTop = to
return
}
const easeInOutQuad = function (t, b, c, d) {
t /= d / 2
if (t < 1) return (c / 2) * t * t + b
t--
return (-c / 2) * (t * (t - 2) - 1) + b
}
const animateScroll = function () {
const now = +new Date()
const val = Math.floor(easeInOutQuad(now - animationStart, start, change, duration))
element.scrollTop = val
if (now > animationStart + duration) {
element.scrollTop = to
if (callback) {
callback()
}
} else {
requestAnimationFrame(animateScroll)
}
}
requestAnimationFrame(animateScroll)
}
export const getUniqueId = () => {
return `${ID_PREFEX}${id++}`
}
export const hasKeys = obj => Object.keys(obj).length > 0
/**
* Clone an object as a shallow or deep copy.
*
* @param {*} obj Object to clone
* @param {Boolean} deepCopy Create a shallow (false) or deep copy (true)
* @deprecated Use `cloneObject` (shallow copy) or `deepClone` (deep copy).
*/
export const cloneObj = (obj, deepCopy = true) => {
return deepCopy ? JSON.parse(JSON.stringify(obj)) : Object.assign({}, obj)
}
/**
* Shallow clone the given object.
*
* @param {*} obj Object to clone
* @param {boolean} inheritFromObject Whether the clone should inherit from `Object`
*/
export const cloneObject = (obj, inheritFromObject = true) => {
return Object.assign(inheritFromObject ? {} : Object.create(null), obj)
}
/**
* Deep clone the given object.
*
* @param {*} obj Object to clone
*/
export const deepClone = obj => {
return JSON.parse(JSON.stringify(obj))
}
export const isOsx = process.platform === 'darwin'
export const isWindows = process.platform === 'win32'
export const isLinux = process.platform === 'linux'
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/listToTree.js | src/renderer/util/listToTree.js | class Node {
constructor (item) {
const { parent, lvl, content, slug } = item
this.parent = parent
this.lvl = lvl
this.label = content
this.slug = slug
this.children = []
}
// Add child node.
addChild (node) {
this.children.push(node)
}
}
const findParent = (item, lastNode, rootNode) => {
if (!lastNode) {
return rootNode
}
const { lvl: lastLvl } = lastNode
const { lvl } = item
if (lvl < lastLvl) {
return findParent(item, lastNode.parent, rootNode)
} else if (lvl === lastLvl) {
return lastNode.parent
} else {
return lastNode
}
}
const listToTree = list => {
const rootNode = new Node({ parent: null, lvl: null, content: null, slug: null })
let lastNode = null
for (const item of list) {
const parent = findParent(item, lastNode, rootNode)
const node = new Node({ parent, ...item })
parent.addChild(node)
lastNode = node
}
return rootNode.children
}
export default listToTree
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/theme.js | src/renderer/util/theme.js | import { THEME_STYLE_ID, COMMON_STYLE_ID, DEFAULT_CODE_FONT_FAMILY, oneDarkThemes, railscastsThemes } from '../config'
import { dark, graphite, materialDark, oneDark, ulysses } from './themeColor'
import { isLinux } from './index'
import elementStyle from 'element-ui/lib/theme-chalk/index.css'
const ORIGINAL_THEME = '#409EFF'
const patchTheme = css => {
return `@media not print {\n${css}\n}`
}
const getEmojiPickerPatch = () => {
return isLinux
? '.ag-emoji-picker section .emoji-wrapper .item span { font-family: sans-serif, "Noto Color Emoji"; }'
: ''
}
const getThemeCluster = themeColor => {
const tintColor = (color, tint) => {
let red = parseInt(color.slice(1, 3), 16)
let green = parseInt(color.slice(3, 5), 16)
let blue = parseInt(color.slice(5, 7), 16)
if (tint === 0) { // when primary color is in its rgb space
return [red, green, blue].join(',')
} else {
red += Math.round(tint * (255 - red))
green += Math.round(tint * (255 - green))
blue += Math.round(tint * (255 - blue))
red = red.toString(16)
green = green.toString(16)
blue = blue.toString(16)
return `#${red}${green}${blue}`
}
}
const clusters = [{
color: themeColor,
variable: 'var(--themeColor)'
}]
for (let i = 9; i >= 1; i--) {
clusters.push({
color: tintColor(themeColor, Number((i / 10).toFixed(2))),
variable: `var(--themeColor${10 - i}0)`
})
}
return clusters
}
export const addThemeStyle = theme => {
const isCmRailscasts = railscastsThemes.includes(theme)
const isCmOneDark = oneDarkThemes.includes(theme)
const isDarkTheme = isCmOneDark || isCmRailscasts
let themeStyleEle = document.querySelector(`#${THEME_STYLE_ID}`)
if (!themeStyleEle) {
themeStyleEle = document.createElement('style')
themeStyleEle.id = THEME_STYLE_ID
document.head.appendChild(themeStyleEle)
}
switch (theme) {
case 'light':
themeStyleEle.innerHTML = ''
break
case 'dark':
themeStyleEle.innerHTML = patchTheme(dark())
break
case 'material-dark':
themeStyleEle.innerHTML = patchTheme(materialDark())
break
case 'ulysses':
themeStyleEle.innerHTML = patchTheme(ulysses())
break
case 'graphite':
themeStyleEle.innerHTML = patchTheme(graphite())
break
case 'one-dark':
themeStyleEle.innerHTML = patchTheme(oneDark())
break
default:
console.log('unknown theme')
break
}
// workaround: use dark icons
document.body.classList.remove('dark')
if (isDarkTheme) {
document.body.classList.add('dark')
}
// change CodeMirror theme
const cm = document.querySelector('.CodeMirror')
if (cm) {
cm.classList.remove('cm-s-default')
cm.classList.remove('cm-s-one-dark')
cm.classList.remove('cm-s-railscasts')
if (isCmOneDark) {
cm.classList.add('cm-s-one-dark')
} else if (isCmRailscasts) {
cm.classList.add('cm-s-railscasts')
} else {
cm.classList.add('cm-s-default')
}
}
}
export const setEditorWidth = value => {
const EDITOR_WIDTH_STYLE_ID = 'editor-width'
let result = ''
if (value && /^[0-9]+(?:ch|px|%)$/.test(value)) {
// Overwrite the theme value and add 100px for padding.
result = `:root { --editorAreaWidth: calc(100px + ${value}); }`
}
let styleEle = document.querySelector(`#${EDITOR_WIDTH_STYLE_ID}`)
if (!styleEle) {
styleEle = document.createElement('style')
styleEle.setAttribute('id', EDITOR_WIDTH_STYLE_ID)
document.head.appendChild(styleEle)
}
styleEle.innerHTML = result
}
export const addCommonStyle = options => {
const { codeFontFamily, codeFontSize, hideScrollbar } = options
let sheet = document.querySelector(`#${COMMON_STYLE_ID}`)
if (!sheet) {
sheet = document.createElement('style')
sheet.id = COMMON_STYLE_ID
document.head.appendChild(sheet)
}
let scrollbarStyle = ''
if (hideScrollbar) {
scrollbarStyle = '::-webkit-scrollbar {display: none;}'
}
sheet.innerHTML = `${scrollbarStyle}
span code,
td code,
th code,
code,
code[class*="language-"],
.CodeMirror,
pre.ag-paragraph {
font-family: ${codeFontFamily}, ${DEFAULT_CODE_FONT_FAMILY};
font-size: ${codeFontSize}px;
}
${getEmojiPickerPatch()}
`
}
export const addElementStyle = () => {
const ID = 'mt-el-style'
let sheet = document.querySelector(`#${ID}`)
if (sheet) {
return
}
const themeCluster = getThemeCluster(ORIGINAL_THEME)
let newElementStyle = elementStyle
for (const { color, variable } of themeCluster) {
newElementStyle = newElementStyle.replace(new RegExp(color, 'ig'), variable)
}
sheet = document.createElement('style')
sheet.id = ID
// NOTE: Prepend element UI style, otherwise we cannot overwrite the style with the default light theme.
document.head.insertBefore(sheet, document.head.firstChild)
sheet.innerHTML = newElementStyle
}
// Append common sheet and theme at the end of head - order is important.
export const addStyles = options => {
const { theme } = options
addThemeStyle(theme)
addCommonStyle(options)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/fileSystem.js | src/renderer/util/fileSystem.js | import path from 'path'
import crypto from 'crypto'
import fs from 'fs-extra'
import { statSync, constants } from 'fs'
import cp from 'child_process'
import { tmpdir } from 'os'
import dayjs from 'dayjs'
import { Octokit } from '@octokit/rest'
import { isImageFile } from 'common/filesystem/paths'
import { isWindows } from './index'
export const create = async (pathname, type) => {
return type === 'directory'
? fs.ensureDir(pathname)
: fs.outputFile(pathname, '')
}
export const paste = async ({ src, dest, type }) => {
return type === 'cut'
? fs.move(src, dest)
: fs.copy(src, dest)
}
export const rename = async (src, dest) => {
return fs.move(src, dest)
}
export const getHash = (content, encoding, type) => {
return crypto.createHash(type).update(content, encoding).digest('hex')
}
export const getContentHash = content => {
return getHash(content, 'utf8', 'sha1')
}
/**
* Moves an image to a relative position.
*
* @param {String} cwd The relative base path (project root or full folder path of opened file).
* @param {String} relativeName The relative directory name.
* @param {String} filePath The full path to the opened file in editor.
* @param {String} imagePath The image to move.
* @returns {String} The relative path the the image from given `filePath`.
*/
export const moveToRelativeFolder = async (cwd, relativeName, filePath, imagePath) => {
if (!relativeName) {
// Use fallback name according settings description
relativeName = 'assets'
} else if (path.isAbsolute(relativeName)) {
throw new Error('Invalid relative directory name.')
}
// Path combination:
// - markdown file directory + relative directory name or
// - root directory + relative directory name
const absPath = path.resolve(cwd, relativeName)
const dstPath = path.resolve(absPath, path.basename(imagePath))
await fs.ensureDir(absPath)
await fs.move(imagePath, dstPath, { overwrite: true })
// Find relative path between given file and saved image.
const dstRelPath = path.relative(path.dirname(filePath), dstPath)
if (isWindows) {
// Use forward slashes for better compatibility with websites.
return dstRelPath.replace(/\\/g, '/')
}
return dstRelPath
}
export const moveImageToFolder = async (pathname, image, outputDir) => {
await fs.ensureDir(outputDir)
const isPath = typeof image === 'string'
if (isPath) {
const dirname = path.dirname(pathname)
const imagePath = path.resolve(dirname, image)
const isImage = isImageFile(imagePath)
if (isImage) {
const filename = path.basename(imagePath)
const extname = path.extname(imagePath)
const noHashPath = path.join(outputDir, filename)
if (noHashPath === imagePath) {
return imagePath
}
const hash = getContentHash(imagePath)
// To avoid name conflict.
const hashFilePath = path.join(outputDir, `${hash}${extname}`)
await fs.copy(imagePath, hashFilePath)
return hashFilePath
} else {
return Promise.resolve(image)
}
} else {
const imagePath = path.join(outputDir, `${dayjs().format('YYYY-MM-DD-HH-mm-ss')}-${image.name}`)
const binaryString = await new Promise((resolve, reject) => {
const fileReader = new FileReader()
fileReader.onload = () => {
resolve(fileReader.result)
}
fileReader.readAsBinaryString(image)
})
await fs.writeFile(imagePath, binaryString, 'binary')
return imagePath
}
}
/**
* @jocs todo, rewrite it use class
*/
export const uploadImage = async (pathname, image, preferences) => {
const { currentUploader, imageBed, githubToken: auth, cliScript } = preferences
const { owner, repo, branch } = imageBed.github
const isPath = typeof image === 'string'
const MAX_SIZE = 5 * 1024 * 1024
let re
let rj
const promise = new Promise((resolve, reject) => {
re = resolve
rj = reject
})
if (currentUploader === 'none') {
rj('No image uploader provided.')
}
const uploadByGithub = (content, filename) => {
const octokit = new Octokit({
auth
})
const path = dayjs().format('YYYY/MM') + `/${dayjs().format('DD-HH-mm-ss')}-${filename}`
const message = `Upload by MarkText at ${dayjs().format('YYYY-MM-DD HH:mm:ss')}`
const payload = {
owner,
repo,
path,
branch,
message,
content
}
if (!branch) {
delete payload.branch
}
octokit.repos.createOrUpdateFileContents(payload)
.then(result => {
re(result.data.content.download_url)
})
.catch(_ => {
rj('Upload failed, the image will be copied to the image folder')
})
}
const uploadByCommand = async (uploader, filepath) => {
let isPath = true
if (typeof filepath !== 'string') {
isPath = false
const data = new Uint8Array(filepath)
filepath = path.join(tmpdir(), +new Date())
await fs.writeFile(filepath, data)
}
if (uploader === 'picgo') {
cp.exec(`picgo u "${filepath}"`, async (err, data) => {
if (!isPath) {
await fs.unlink(filepath)
}
if (err) {
return rj(err)
}
const parts = data.split('[PicGo SUCCESS]:')
if (parts.length === 2) {
re(parts[1].trim())
} else {
rj('PicGo upload error')
}
})
} else {
cp.execFile(cliScript, [filepath], async (err, data) => {
if (!isPath) {
await fs.unlink(filepath)
}
if (err) {
return rj(err)
}
re(data.trim())
})
}
}
const notification = () => {
rj('Cannot upload more than 5M image, the image will be copied to the image folder')
}
if (isPath) {
const dirname = path.dirname(pathname)
const imagePath = path.resolve(dirname, image)
const isImage = isImageFile(imagePath)
if (isImage) {
const { size } = await fs.stat(imagePath)
if (size > MAX_SIZE) {
notification()
} else {
switch (currentUploader) {
case 'cliScript':
case 'picgo':
uploadByCommand(currentUploader, imagePath)
break
case 'github': {
const imageFile = await fs.readFile(imagePath)
const base64 = Buffer.from(imageFile).toString('base64')
uploadByGithub(base64, path.basename(imagePath))
break
}
}
}
} else {
re(image)
}
} else {
const { size } = image
if (size > MAX_SIZE) {
notification()
} else {
const reader = new FileReader()
reader.onload = async () => {
switch (currentUploader) {
case 'picgo':
case 'cliScript':
uploadByCommand(currentUploader, reader.result)
break
default:
uploadByGithub(reader.result, image.name)
}
}
const readerFunction = currentUploader !== 'github' ? 'readAsArrayBuffer' : 'readAsDataURL'
reader[readerFunction](image)
}
}
return promise
}
export const isFileExecutableSync = (filepath) => {
try {
const stat = statSync(filepath)
return stat.isFile() && (stat.mode & (constants.S_IXUSR | constants.S_IXGRP | constants.S_IXOTH)) !== 0
} catch (err) {
// err ignored
return false
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/clipboard.js | src/renderer/util/clipboard.js | import { isLinux, isOsx, isWindows } from './index'
import plist from 'plist'
import { clipboard as remoteClipboard } from '@electron/remote'
const hasClipboardFiles = () => {
return remoteClipboard.has('NSFilenamesPboardType')
}
const getClipboardFiles = () => {
if (!hasClipboardFiles()) { return [] }
return plist.parse(remoteClipboard.read('NSFilenamesPboardType'))
}
export const guessClipboardFilePath = () => {
if (isLinux) return ''
if (isOsx) {
const result = getClipboardFiles()
return Array.isArray(result) && result.length ? result[0] : ''
} else if (isWindows) {
const rawFilePath = remoteClipboard.read('FileNameW')
const filePath = rawFilePath.replace(new RegExp(String.fromCharCode(0), 'g'), '')
return filePath && typeof filePath === 'string' ? filePath : ''
} else {
return ''
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/dompurify.js | src/renderer/util/dompurify.js | import runSanitize from 'muya/lib/utils/dompurify'
export const PREVIEW_DOMPURIFY_CONFIG = Object.freeze({
FORBID_ATTR: ['style', 'contenteditable'],
ALLOW_DATA_ATTR: false,
USE_PROFILES: {
html: true,
svg: true,
svgFilters: true,
mathMl: false
},
RETURN_TRUSTED_TYPE: false
})
export const EXPORT_DOMPURIFY_CONFIG = Object.freeze({
FORBID_ATTR: ['contenteditable'],
ALLOW_DATA_ATTR: false,
ADD_ATTR: ['data-align'],
USE_PROFILES: {
html: true,
svg: true,
svgFilters: true,
mathMl: false
},
RETURN_TRUSTED_TYPE: false,
// Allow "file" protocol to export images on Windows (#1997).
ALLOWED_URI_REGEXP: /^(?:(?:(?:f|ht)tps?|mailto|tel|callto|cid|xmpp|file):|[^a-z]|[a-z+.\-]+(?:[^a-z+.\-:]|$))/i // eslint-disable-line no-useless-escape
})
export const sanitize = (html, purifyOptions) => {
return runSanitize(html, purifyOptions)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/util/day.js | src/renderer/util/day.js | import dayjs from 'dayjs/esm'
import relativeTime from 'dayjs/esm/plugin/relativeTime'
// `en` is a built in locale. no need to import it.
// import 'dayjs/esm/locale/en' // load on demand
// dayjs.locale('en') // use en locale globally
dayjs.extend(relativeTime)
export default dayjs
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/node/ripgrepSearcher.js | src/renderer/node/ripgrepSearcher.js | // Modified version of https://github.com/atom/atom/blob/master/src/ripgrep-directory-searcher.js
//
// Copyright (c) 2011-2019 GitHub Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
import { spawn } from 'child_process'
import path from 'path'
function cleanResultLine (resultLine) {
resultLine = getText(resultLine)
return resultLine[resultLine.length - 1] === '\n' ? resultLine.slice(0, -1) : resultLine
}
function getPositionFromColumn (lines, column) {
let currentLength = 0
let currentLine = 0
let previousLength = 0
while (column >= currentLength) {
previousLength = currentLength
currentLength += lines[currentLine].length + 1
currentLine++
}
return [currentLine - 1, column - previousLength]
}
function processUnicodeMatch (match) {
const text = getText(match.lines)
if (text.length === Buffer.byteLength(text)) {
// fast codepath for lines that only contain characters of 1 byte length.
return
}
let remainingBuffer = Buffer.from(text)
let currentLength = 0
let previousPosition = 0
function convertPosition (position) {
const currentBuffer = remainingBuffer.slice(0, position - previousPosition)
currentLength = currentBuffer.toString().length + currentLength
remainingBuffer = remainingBuffer.slice(position - previousPosition)
previousPosition = position
return currentLength
}
// Iterate over all the submatches to find the convert the start and end values
// (which come as bytes from ripgrep) to character positions.
// We can do this because submatches come ordered by position.
for (const submatch of match.submatches) {
submatch.start = convertPosition(submatch.start)
submatch.end = convertPosition(submatch.end)
}
}
// This function processes a ripgrep submatch to create the correct
// range. This is mostly needed for multi-line results, since the range
// will have differnt start and end rows and we need to calculate these
// based on the lines that ripgrep returns.
function processSubmatch (submatch, lineText, offsetRow) {
const lineParts = lineText.split('\n')
const start = getPositionFromColumn(lineParts, submatch.start)
const end = getPositionFromColumn(lineParts, submatch.end)
// Make sure that the lineText string only contains lines that are
// relevant to this submatch. This means getting rid of lines above
// the start row and below the end row.
for (let i = start[0]; i > 0; i--) {
lineParts.shift()
}
while (end[0] < lineParts.length - 1) {
lineParts.pop()
}
start[0] += offsetRow
end[0] += offsetRow
return {
range: [start, end],
lineText: cleanResultLine({ text: lineParts.join('\n') })
}
}
function getText (input) {
return 'text' in input ? input.text : Buffer.from(input.bytes, 'base64').toString()
}
class RipgrepDirectorySearcher {
constructor () {
this.rgPath = global.marktext.paths.ripgrepBinaryPath
}
// Performs a text search for files in the specified `Directory`s, subject to the
// specified parameters.
//
// Results are streamed back to the caller by invoking methods on the specified `options`,
// such as `didMatch`.
//
// * `directories` {Array} of absolute {string} paths to search.
// * `pattern` {string} to search with.
// * `options` {Object} with the following properties:
// * `didMatch` {Function} call with a search result structured as follows:
// * `searchResult` {Object} with the following keys:
// * `filePath` {String} absolute path to the matching file.
// * `matches` {Array} with object elements with the following keys:
// * `lineText` {String} The full text of the matching line (without a line terminator character).
// * `matchText` {String} The text that matched the `regex` used for the search.
// * `range` {Range} Identifies the matching region in the file. (Likely as an array of numeric arrays.)
// * `didSearchPaths` {Function} periodically call with the number of paths searched that contain results thus far.
// * `inclusions` {Array} of glob patterns (as strings) to search within. Note that this
// array may be empty, indicating that all files should be searched.
//
// Each item in the array is a file/directory pattern, e.g., `src` to search in the "src"
// directory or `*.js` to search all JavaScript files. In practice, this often comes from the
// comma-delimited list of patterns in the bottom text input of the ProjectFindView dialog.
// * `noIgnore` {boolean} whether to ignore ignore files like `.gitignore`.
// * `exclusions` {Array} similar to inclusions
// * `followSymlinks` {boolean} whether symlinks should be followed.
// * `isWholeWord` {boolean} whether to search for whole words.
// * `isRegexp` {boolean} whether `pattern` is a RegEx.
// * `isCaseSensitive` {boolean} whether to search case sensitive or not.
// * `maxFileSize` {number} the maximal file size.
// * `includeHidden` {boolean} whether to search in hidden files and directories.
// Returns a *thenable* `DirectorySearch` that includes a `cancel()` method. If `cancel()` is
// invoked before the `DirectorySearch` is determined, it will resolve the `DirectorySearch`.
search (directories, pattern, options) {
const numPathsFound = { num: 0 }
const allPromises = directories.map(
directory => this.searchInDirectory(directory, pattern, options, numPathsFound)
)
const promise = Promise.all(allPromises)
promise.cancel = () => {
for (const promise of allPromises) {
promise.cancel()
}
}
return promise
}
searchInDirectory (directoryPath, pattern, options, numPathsFound) {
let regexpStr = null
let textPattern = null
const args = ['--json']
if (options.isRegexp) {
regexpStr = this.prepareRegexp(pattern)
args.push('--regexp', regexpStr)
} else {
args.push('--fixed-strings')
textPattern = pattern
}
if (regexpStr && this.isMultilineRegexp(regexpStr)) {
args.push('--multiline')
}
if (options.isCaseSensitive) {
args.push('--case-sensitive')
} else {
args.push('--ignore-case')
}
if (options.isWholeWord) {
args.push('--word-regexp')
}
if (options.followSymlinks) {
args.push('--follow')
}
if (options.maxFileSize) {
args.push('--max-filesize', options.maxFileSize + '')
}
if (options.includeHidden) {
args.push('--hidden')
}
if (options.noIgnore) {
args.push('--no-ignore')
}
if (options.leadingContextLineCount) {
args.push('--before-context', options.leadingContextLineCount)
}
if (options.trailingContextLineCount) {
args.push('--after-context', options.trailingContextLineCount)
}
for (const inclusion of this.prepareGlobs(options.inclusions, directoryPath)) {
args.push('--iglob', inclusion)
}
for (const exclusion of this.prepareGlobs(options.exclusions, directoryPath)) {
args.push('--iglob', '!' + exclusion)
}
args.push('--')
if (textPattern) {
args.push(textPattern)
}
args.push(directoryPath)
let child = null
try {
child = spawn(this.rgPath, args, {
cwd: directoryPath,
stdio: ['pipe', 'pipe', 'pipe']
})
} catch (err) {
return Promise.reject(err)
}
const didMatch = options.didMatch || (() => {})
let cancelled = false
const returnedPromise = new Promise((resolve, reject) => {
let buffer = ''
let bufferError = ''
let pendingEvent
let pendingLeadingContext
let pendingTrailingContexts
child.on('close', (code, signal) => {
// code 1 is used when no results are found.
if (code !== null && code > 1) {
reject(new Error(bufferError))
} else {
resolve()
}
})
child.on('error', err => {
reject(err)
})
child.stderr.on('data', chunk => {
bufferError += chunk
})
child.stdout.on('data', chunk => {
if (cancelled) {
return
}
buffer += chunk
const lines = buffer.split('\n')
buffer = lines.pop()
for (const line of lines) {
const message = JSON.parse(line)
if (message.type === 'begin') {
pendingEvent = {
filePath: getText(message.data.path),
matches: []
}
pendingLeadingContext = []
pendingTrailingContexts = new Set()
} else if (message.type === 'match') {
const trailingContextLines = []
pendingTrailingContexts.add(trailingContextLines)
processUnicodeMatch(message.data)
for (const submatch of message.data.submatches) {
const { lineText, range } = processSubmatch(
submatch,
getText(message.data.lines),
message.data.line_number - 1
)
pendingEvent.matches.push({
matchText: getText(submatch.match),
lineText,
range,
leadingContextLines: [...pendingLeadingContext],
trailingContextLines
})
}
} else if (message.type === 'end') {
options.didSearchPaths(++numPathsFound.num)
didMatch(pendingEvent)
pendingEvent = null
}
}
})
})
returnedPromise.cancel = () => {
child.kill()
cancelled = true
}
return returnedPromise
}
// We need to prepare the "globs" that we receive from the user to make their behaviour more
// user-friendly (e.g when adding `src/` the user probably means `src/**/*`).
// This helper function takes care of that.
prepareGlobs (globs, projectRootPath) {
const output = []
for (let pattern of globs) {
// we need to replace path separators by slashes since globs should
// always use always slashes as path separators.
pattern = pattern.replace(new RegExp(`\\${path.sep}`, 'g'), '/')
if (pattern.length === 0) {
continue
}
const projectName = path.basename(projectRootPath)
// The user can just search inside one of the opened projects. When we detect
// this scenario we just consider the glob to include every file.
if (pattern === projectName) {
output.push('**/*')
continue
}
if (pattern.startsWith(projectName + '/')) {
pattern = pattern.slice(projectName.length + 1)
}
if (pattern.endsWith('/')) {
pattern = pattern.slice(0, -1)
}
pattern = pattern.startsWith('**/') ? pattern : `**/${pattern}`
output.push(pattern)
output.push(pattern.endsWith('/**') ? pattern : `${pattern}/**`)
}
return output
}
prepareRegexp (regexpStr) {
// ripgrep handles `--` as the arguments separator, so we need to escape it if the
// user searches for that exact same string.
if (regexpStr === '--') {
return '\\-\\-'
}
// ripgrep is quite picky about unnecessarily escaped sequences, so we need to unescape
// them: https://github.com/BurntSushi/ripgrep/issues/434.
regexpStr = regexpStr.replace(/\\\//g, '/')
return regexpStr
}
isMultilineRegexp (regexpStr) {
if (regexpStr.includes('\\n')) {
return true
}
return false
}
}
export default RipgrepDirectorySearcher
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/node/fileSearcher.js | src/renderer/node/fileSearcher.js | import { spawn } from 'child_process'
import RipgrepDirectorySearcher from './ripgrepSearcher'
// Use ripgrep searcher to search for files on disk only.
class FileSearcher extends RipgrepDirectorySearcher {
searchInDirectory (directoryPath, pattern, options, numPathsFound) {
const args = ['--files']
if (options.followSymlinks) {
args.push('--follow')
}
if (options.includeHidden) {
args.push('--hidden')
}
if (options.noIgnore) {
args.push('--no-ignore')
}
for (const inclusion of this.prepareGlobs(options.inclusions, directoryPath)) {
args.push('--iglob', inclusion)
}
args.push('--')
args.push(directoryPath)
let child = null
try {
child = spawn(this.rgPath, args, {
cwd: directoryPath,
stdio: ['pipe', 'pipe', 'pipe']
})
} catch (err) {
return Promise.reject(err)
}
const didMatch = options.didMatch || (() => {})
let cancelled = false
const returnedPromise = new Promise((resolve, reject) => {
let buffer = ''
let bufferError = ''
child.on('close', (code, signal) => {
// code 1 is used when no results are found.
if (code !== null && code > 1) {
reject(new Error(bufferError))
} else {
resolve()
}
})
child.on('error', err => {
reject(err)
})
child.stderr.on('data', chunk => {
bufferError += chunk
})
child.stdout.on('data', chunk => {
if (cancelled) {
return
}
buffer += chunk
const lines = buffer.split('\n')
buffer = lines.pop()
for (const line of lines) {
options.didSearchPaths(++numPathsFound.num)
didMatch(line)
}
})
})
returnedPromise.cancel = () => {
child.kill()
cancelled = true
}
return returnedPromise
}
}
export default FileSearcher
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/node/paths.js | src/renderer/node/paths.js | import { rgPath } from 'vscode-ripgrep'
import EnvPaths from 'common/envPaths'
// // "vscode-ripgrep" is unpacked out of asar because of the binary.
const rgDiskPath = rgPath.replace(/\bapp\.asar\b/, 'app.asar.unpacked')
class RendererPaths extends EnvPaths {
/**
* Configure and sets all application paths.
*
* @param {string} userDataPath The user data path.
*/
constructor (userDataPath) {
if (!userDataPath) {
throw new Error('No user data path is given.')
}
// Initialize environment paths
super(userDataPath)
// Allow to use a local ripgrep binary (e.g. an optimized version).
if (process.env.MARKTEXT_RIPGREP_PATH) {
// NOTE: Binary must be a compatible version, otherwise the searcher may fail.
this._ripgrepBinaryPath = process.env.MARKTEXT_RIPGREP_PATH
} else {
this._ripgrepBinaryPath = rgDiskPath
}
}
// Returns the path to ripgrep on disk.
get ripgrepBinaryPath () {
return this._ripgrepBinaryPath
}
}
export default RendererPaths
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/help.js | src/renderer/store/help.js | import { getUniqueId, cloneObj } from '../util'
/**
* Default internel markdown document with editor options.
*
* @type {IDocumentState} Internel markdown document
*/
export const defaultFileState = {
// Indicates whether there are unsaved changes.
isSaved: true,
// Full path to the file or empty. If the value is empty the file doesn't exist on disk.
pathname: '',
filename: 'Untitled-1',
markdown: '',
encoding: {
encoding: 'utf8',
isBom: false
},
lineEnding: 'lf', // lf or crlf
trimTrailingNewline: 3,
adjustLineEndingOnSave: false, // convert editor buffer (LF) to CRLF when saving
history: {
stack: [],
index: -1
},
cursor: null,
wordCount: {
paragraph: 0,
word: 0,
character: 0,
all: 0
},
searchMatches: {
index: -1,
matches: [],
value: ''
},
// Per tab notifications
notifications: []
}
export const getOptionsFromState = file => {
const { encoding, lineEnding, adjustLineEndingOnSave, trimTrailingNewline } = file
return { encoding, lineEnding, adjustLineEndingOnSave, trimTrailingNewline }
}
export const getFileStateFromData = data => {
const fileState = JSON.parse(JSON.stringify(defaultFileState))
const {
markdown,
filename,
pathname,
encoding,
lineEnding,
adjustLineEndingOnSave,
trimTrailingNewline
} = data
const id = getUniqueId()
assertLineEnding(adjustLineEndingOnSave, lineEnding)
return Object.assign(fileState, {
id,
markdown,
filename,
pathname,
encoding,
lineEnding,
adjustLineEndingOnSave,
trimTrailingNewline
})
}
export const getBlankFileState = (tabs, defaultEncoding = 'utf8', lineEnding = 'lf', markdown = '') => {
const fileState = cloneObj(defaultFileState, true)
let untitleId = Math.max(...tabs.map(f => {
if (f.pathname === '') {
return +f.filename.split('-')[1]
} else {
return 0
}
}), 0)
const id = getUniqueId()
// We may pass markdown=null as parameter.
if (markdown == null) {
markdown = ''
}
fileState.encoding.encoding = defaultEncoding
return Object.assign(fileState, {
lineEnding,
adjustLineEndingOnSave: lineEnding.toLowerCase() === 'crlf',
id,
filename: `Untitled-${++untitleId}`,
markdown
})
}
export const getSingleFileState = ({ id = getUniqueId(), markdown, filename, pathname, options }) => {
// TODO(refactor:renderer/editor): Replace this function with `createDocumentState`.
const fileState = cloneObj(defaultFileState, true)
const { encoding, lineEnding, adjustLineEndingOnSave, trimTrailingNewline } = options
assertLineEnding(adjustLineEndingOnSave, lineEnding)
return Object.assign(fileState, {
id,
markdown,
filename,
pathname,
encoding,
lineEnding,
adjustLineEndingOnSave,
trimTrailingNewline
})
}
/**
* Creates a internal document from the given document.
*
* @param {IMarkdownDocument} markdownDocument Markdown document
* @param {String} [id] Random identifier
* @returns {IDocumentState} Returns a document state
*/
export const createDocumentState = (markdownDocument, id = getUniqueId()) => {
const docState = cloneObj(defaultFileState, true)
const {
markdown,
filename,
pathname,
encoding,
lineEnding,
adjustLineEndingOnSave,
trimTrailingNewline,
cursor = null
} = markdownDocument
assertLineEnding(adjustLineEndingOnSave, lineEnding)
return Object.assign(docState, {
id,
markdown,
filename,
pathname,
encoding,
lineEnding,
cursor,
adjustLineEndingOnSave,
trimTrailingNewline
})
}
const assertLineEnding = (adjustLineEndingOnSave, lineEnding) => {
lineEnding = lineEnding.toLowerCase()
if ((adjustLineEndingOnSave && lineEnding !== 'crlf') ||
(!adjustLineEndingOnSave && lineEnding === 'crlf')) {
console.error('Assertion failed: Line ending is "CRLF" but document is saved as "LF".')
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/treeCtrl.js | src/renderer/store/treeCtrl.js | import path from 'path'
import { getUniqueId } from '../util'
import { PATH_SEPARATOR } from '../config'
/**
* Return all sub-directories relative to the root directory.
*
* @param {string} rootPath Root directory path
* @param {string} pathname Full directory path
* @returns {Array<string>} Sub-directories relative to root.
*/
const getSubdirectoriesFromRoot = (rootPath, pathname) => {
if (!path.isAbsolute(pathname)) {
throw new Error('Invalid path!')
}
const relativePath = path.relative(rootPath, pathname)
return relativePath ? relativePath.split(PATH_SEPARATOR) : []
}
/**
* Add a new file to the tree list.
*
* @param {*} tree Root file tree
* @param {*} file The file that should be added
*/
export const addFile = (tree, file) => {
const { pathname, name } = file
const dirname = path.dirname(pathname)
const subDirectories = getSubdirectoriesFromRoot(tree.pathname, dirname)
let currentPath = tree.pathname
let currentFolder = tree
let currentSubFolders = tree.folders
for (const directoryName of subDirectories) {
let childFolder = currentSubFolders.find(f => f.name === directoryName)
if (!childFolder) {
childFolder = {
id: getUniqueId(),
pathname: `${currentPath}${PATH_SEPARATOR}${directoryName}`,
name: directoryName,
isCollapsed: true,
isDirectory: true,
isFile: false,
isMarkdown: false,
folders: [],
files: []
}
currentSubFolders.push(childFolder)
}
currentPath = `${currentPath}${PATH_SEPARATOR}${directoryName}`
currentFolder = childFolder
currentSubFolders = childFolder.folders
}
// Add file to related directory
if (!currentFolder.files.find(f => f.name === name)) {
// Remove file content from object.
const fileCopy = {
id: getUniqueId(),
birthTime: file.birthTime,
isDirectory: file.isDirectory,
isFile: file.isFile,
isMarkdown: file.isMarkdown,
name: file.name,
pathname: file.pathname
}
const idx = currentFolder.files.findIndex(f => {
return f.name.localeCompare(name) > 0
})
if (idx !== -1) {
currentFolder.files.splice(idx, 0, fileCopy)
} else {
currentFolder.files.push(fileCopy)
}
}
}
/**
* Add a new directory to the tree list.
*
* @param {*} tree Root file tree
* @param {*} dir The directory that should be added
*/
export const addDirectory = (tree, dir) => {
const subDirectories = getSubdirectoriesFromRoot(tree.pathname, dir.pathname)
let currentPath = tree.pathname
let currentSubFolders = tree.folders
for (const directoryName of subDirectories) {
let childFolder = currentSubFolders.find(f => f.name === directoryName)
if (!childFolder) {
childFolder = {
id: getUniqueId(),
pathname: `${currentPath}${PATH_SEPARATOR}${directoryName}`,
name: directoryName,
isCollapsed: true,
isDirectory: true,
isFile: false,
isMarkdown: false,
folders: [],
files: []
}
currentSubFolders.push(childFolder)
}
currentPath = `${currentPath}${PATH_SEPARATOR}${directoryName}`
currentSubFolders = childFolder.folders
}
}
/**
* Remove the given file from the tree list.
*
* @param {*} tree Root file tree
* @param {*} file The file that should be deleted
*/
export const unlinkFile = (tree, file) => {
const { pathname } = file
const dirname = path.dirname(pathname)
const subDirectories = getSubdirectoriesFromRoot(tree.pathname, dirname)
let currentFolder = tree
let currentSubFolders = tree.folders
for (const directoryName of subDirectories) {
const childFolder = currentSubFolders.find(f => f.name === directoryName)
if (!childFolder) return
currentFolder = childFolder
currentSubFolders = childFolder.folders
}
const index = currentFolder.files.findIndex(f => f.pathname === pathname)
if (index !== -1) {
currentFolder.files.splice(index, 1)
}
}
/**
* Remove the given directory from the tree list.
*
* @param {*} tree Root file tree
* @param {*} dir The directory that should be deleted
*/
export const unlinkDirectory = (tree, dir) => {
const { pathname } = dir
const subDirectories = getSubdirectoriesFromRoot(tree.pathname, pathname)
subDirectories.pop()
let currentFolder = tree.folders
for (const directoryName of subDirectories) {
const childFolder = currentFolder.find(f => f.name === directoryName)
if (!childFolder) return
currentFolder = childFolder.folders
}
const index = currentFolder.findIndex(f => f.pathname === pathname)
if (index !== -1) {
currentFolder.splice(index, 1)
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/commandCenter.js | src/renderer/store/commandCenter.js | import { ipcRenderer } from 'electron'
import log from 'electron-log'
import bus from '../bus'
import staticCommands, { RootCommand } from '../commands'
const state = {
rootCommand: new RootCommand(staticCommands)
}
const getters = {}
const mutations = {
REGISTER_COMMAND (state, command) {
state.rootCommand.subcommands.push(command)
},
SORT_COMMANDS (state) {
state.rootCommand.subcommands.sort((a, b) => a.description.localeCompare(b.description))
}
}
const actions = {
LISTEN_COMMAND_CENTER_BUS ({ commit, state }) {
// Init stuff
bus.$on('cmd::sort-commands', () => {
commit('SORT_COMMANDS')
})
ipcRenderer.on('mt::keybindings-response', (e, keybindingMap) => {
const { subcommands } = state.rootCommand
for (const entry of subcommands) {
const value = keybindingMap[entry.id]
if (value) {
entry.shortcut = normalizeAccelerator(value)
}
}
})
// Register commands that are created at runtime.
bus.$on('cmd::register-command', command => {
commit('REGISTER_COMMAND', command)
})
// Allow other compontents to execute commands with predefined values.
bus.$on('cmd::execute', commandId => {
executeCommand(state, commandId)
})
ipcRenderer.on('mt::execute-command-by-id', (e, commandId) => {
executeCommand(state, commandId)
})
}
}
const executeCommand = (state, commandId) => {
const { subcommands } = state.rootCommand
const command = subcommands.find(c => c.id === commandId)
if (!command) {
const errorMsg = `Cannot execute command "${commandId}" because it's missing.`
log.error(errorMsg)
throw new Error(errorMsg)
}
command.execute()
}
const normalizeAccelerator = acc => {
try {
return acc
.replace(/cmdorctrl|cmd/i, 'Cmd')
.replace(/ctrl/i, 'Ctrl')
.split('+')
} catch (_) {
return [acc]
}
}
export default { state, getters, mutations, actions }
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/editor.js | src/renderer/store/editor.js | import { clipboard, ipcRenderer, shell, webFrame } from 'electron'
import path from 'path'
import equal from 'fast-deep-equal'
import { isSamePathSync } from 'common/filesystem/paths'
import bus from '../bus'
import { hasKeys, getUniqueId } from '../util'
import listToTree from '../util/listToTree'
import { createDocumentState, getOptionsFromState, getSingleFileState, getBlankFileState } from './help'
import notice from '../services/notification'
import {
FileEncodingCommand,
LineEndingCommand,
QuickOpenCommand,
TrailingNewlineCommand
} from '../commands'
const autoSaveTimers = new Map()
const state = {
currentFile: {},
tabs: [],
listToc: [], // Just use for deep equal check. and replace with new toc if needed.
toc: []
}
const mutations = {
// set search key and matches also index
SET_SEARCH (state, value) {
state.currentFile.searchMatches = value
},
SET_TOC (state, toc) {
state.listToc = toc
state.toc = listToTree(toc)
},
SET_CURRENT_FILE (state, currentFile) {
const oldCurrentFile = state.currentFile
if (!oldCurrentFile.id || oldCurrentFile.id !== currentFile.id) {
const { id, markdown, cursor, history, pathname } = currentFile
window.DIRNAME = pathname ? path.dirname(pathname) : ''
// set state first, then emit file changed event
state.currentFile = currentFile
bus.$emit('file-changed', { id, markdown, cursor, renderCursor: true, history })
}
},
ADD_FILE_TO_TABS (state, currentFile) {
state.tabs.push(currentFile)
},
REMOVE_FILE_WITHIN_TABS (state, file) {
const { tabs, currentFile } = state
const index = tabs.indexOf(file)
tabs.splice(index, 1)
if (file.id && autoSaveTimers.has(file.id)) {
const timer = autoSaveTimers.get(file.id)
clearTimeout(timer)
autoSaveTimers.delete(file.id)
}
if (file.id === currentFile.id) {
const fileState = state.tabs[index] || state.tabs[index - 1] || state.tabs[0] || {}
state.currentFile = fileState
if (typeof fileState.markdown === 'string') {
const { id, markdown, cursor, history, pathname } = fileState
window.DIRNAME = pathname ? path.dirname(pathname) : ''
bus.$emit('file-changed', { id, markdown, cursor, renderCursor: true, history })
}
}
if (state.tabs.length === 0) {
// Handle close the last tab, need to reset the TOC state
state.listToc = []
state.toc = []
}
},
// Exchange from with to and move from to the end if to is null or empty.
EXCHANGE_TABS_BY_ID (state, tabIDs) {
const { fromId } = tabIDs
const toId = tabIDs.toId // may be null
const { tabs } = state
const moveItem = (arr, from, to) => {
if (from === to) return true
const len = arr.length
const item = arr.splice(from, 1)
if (item.length === 0) return false
arr.splice(to, 0, item[0])
return arr.length === len
}
const fromIndex = tabs.findIndex(t => t.id === fromId)
if (!toId) {
moveItem(tabs, fromIndex, tabs.length - 1)
} else {
const toIndex = tabs.findIndex(t => t.id === toId)
const realToIndex = fromIndex < toIndex ? toIndex - 1 : toIndex
moveItem(tabs, fromIndex, realToIndex)
}
},
LOAD_CHANGE (state, change) {
const { tabs, currentFile } = state
const { data, pathname } = change
const {
isMixedLineEndings,
lineEnding,
adjustLineEndingOnSave,
trimTrailingNewline,
encoding,
markdown,
filename
} = data
const options = { encoding, lineEnding, adjustLineEndingOnSave, trimTrailingNewline }
// Create a new document and update few entires later.
const newFileState = getSingleFileState({ markdown, filename, pathname, options })
const tab = tabs.find(t => isSamePathSync(t.pathname, pathname))
if (!tab) {
// The tab may be closed in the meanwhile.
console.error('LOAD_CHANGE: Cannot find tab in tab list.')
notice.notify({
title: 'Error loading tab',
message: 'There was an error while loading the file change because the tab cannot be found.',
type: 'error',
time: 20000,
showConfirm: false
})
return
}
// Backup few entries that we need to restore later.
const oldId = tab.id
const oldNotifications = tab.notifications
let oldHistory = null
if (tab.history.index >= 0 && tab.history.stack.length >= 1) {
// Allow to restore the old document.
oldHistory = {
stack: [tab.history.stack[tab.history.index]],
index: 0
}
// Free reference from array
tab.history.index--
tab.history.stack.pop()
}
// Update file content and restore some entries.
Object.assign(tab, newFileState)
tab.id = oldId
tab.notifications = oldNotifications
if (oldHistory) {
tab.history = oldHistory
}
if (isMixedLineEndings) {
tab.notifications.push({
msg: `"${filename}" has mixed line endings which are automatically normalized to ${lineEnding.toUpperCase()}.`,
showConfirm: false,
style: 'info',
exclusiveType: '',
action: () => {}
})
}
// Reload the editor if the tab is currently opened.
if (pathname === currentFile.pathname) {
state.currentFile = tab
const { id, cursor, history } = tab
bus.$emit('file-changed', { id, markdown, cursor, renderCursor: true, history })
}
},
// NOTE: Please call this function only from main process via "mt::set-pathname" and free resources before!
SET_PATHNAME (state, { tab, fileInfo }) {
const { currentFile } = state
const { filename, pathname, id } = fileInfo
// Change reference path for images.
if (id === currentFile.id && pathname) {
window.DIRNAME = path.dirname(pathname)
}
if (tab) {
Object.assign(tab, { filename, pathname, isSaved: true })
}
},
SET_SAVE_STATUS_BY_TAB (state, { tab, status }) {
if (hasKeys(tab)) {
tab.isSaved = status
}
},
SET_SAVE_STATUS (state, status) {
if (hasKeys(state.currentFile)) {
state.currentFile.isSaved = status
}
},
SET_SAVE_STATUS_WHEN_REMOVE (state, { pathname }) {
state.tabs.forEach(f => {
if (f.pathname === pathname) {
f.isSaved = false
}
})
},
SET_MARKDOWN (state, markdown) {
if (hasKeys(state.currentFile)) {
state.currentFile.markdown = markdown
}
},
SET_DOCUMENT_ENCODING (state, encoding) {
if (hasKeys(state.currentFile)) {
state.currentFile.encoding = encoding
}
},
SET_LINE_ENDING (state, lineEnding) {
if (hasKeys(state.currentFile)) {
state.currentFile.lineEnding = lineEnding
}
},
SET_FILE_ENCODING_BY_NAME (state, encodingName) {
if (hasKeys(state.currentFile)) {
const { encoding: encodingObj } = state.currentFile
encodingObj.encoding = encodingName
encodingObj.isBom = false
}
},
SET_FINAL_NEWLINE (state, value) {
if (hasKeys(state.currentFile) && value >= 0 && value <= 3) {
state.currentFile.trimTrailingNewline = value
}
},
SET_ADJUST_LINE_ENDING_ON_SAVE (state, adjustLineEndingOnSave) {
if (hasKeys(state.currentFile)) {
state.currentFile.adjustLineEndingOnSave = adjustLineEndingOnSave
}
},
SET_WORD_COUNT (state, wordCount) {
if (hasKeys(state.currentFile)) {
state.currentFile.wordCount = wordCount
}
},
SET_CURSOR (state, cursor) {
if (hasKeys(state.currentFile)) {
state.currentFile.cursor = cursor
}
},
SET_HISTORY (state, history) {
if (hasKeys(state.currentFile)) {
state.currentFile.history = history
}
},
CLOSE_TABS (state, tabIdList) {
if (!tabIdList || tabIdList.length === 0) return
let tabIndex = 0
tabIdList.forEach(id => {
const index = state.tabs.findIndex(f => f.id === id)
const { pathname } = state.tabs[index]
// Notify main process to remove the file from the window and free resources.
if (pathname) {
ipcRenderer.send('mt::window-tab-closed', pathname)
}
state.tabs.splice(index, 1)
if (state.currentFile.id === id) {
state.currentFile = {}
window.DIRNAME = ''
if (tabIdList.length === 1) {
tabIndex = index
}
}
})
if (!state.currentFile.id && state.tabs.length) {
state.currentFile = state.tabs[tabIndex] || state.tabs[tabIndex - 1] || state.tabs[0] || {}
if (typeof state.currentFile.markdown === 'string') {
const { id, markdown, cursor, history, pathname } = state.currentFile
window.DIRNAME = pathname ? path.dirname(pathname) : ''
bus.$emit('file-changed', { id, markdown, cursor, renderCursor: true, history })
}
}
if (state.tabs.length === 0) {
// Handle close the last tab, need to reset the TOC state
state.listToc = []
state.toc = []
}
},
RENAME_IF_NEEDED (state, { src, dest }) {
const { tabs } = state
tabs.forEach(f => {
if (f.pathname === src) {
f.pathname = dest
f.filename = path.basename(dest)
}
})
},
// Push a tab specific notification on stack that never disappears.
PUSH_TAB_NOTIFICATION (state, data) {
const defaultAction = () => {}
const { tabId, msg } = data
const action = data.action || defaultAction
const showConfirm = data.showConfirm || false
const style = data.style || 'info'
// Whether only one notification should exist.
const exclusiveType = data.exclusiveType || ''
const { tabs } = state
const tab = tabs.find(t => t.id === tabId)
if (!tab) {
console.error('PUSH_TAB_NOTIFICATION: Cannot find tab in tab list.')
return
}
const { notifications } = tab
// Remove the old notification if only one should exist.
if (exclusiveType) {
const index = notifications.findIndex(n => n.exclusiveType === exclusiveType)
if (index >= 0) {
// Reorder current notification
notifications.splice(index, 1)
}
}
// Push new notification on stack.
notifications.push({
msg,
showConfirm,
style,
exclusiveType,
action: action
})
}
}
const actions = {
FORMAT_LINK_CLICK ({ commit }, { data, dirname }) {
ipcRenderer.send('mt::format-link-click', { data, dirname })
},
LISTEN_SCREEN_SHOT ({ commit }) {
ipcRenderer.on('mt::screenshot-captured', e => {
bus.$emit('screenshot-captured')
})
},
// image path auto complement
ASK_FOR_IMAGE_AUTO_PATH ({ commit, state }, src) {
const { pathname } = state.currentFile
if (pathname) {
let rs
const promise = new Promise((resolve, reject) => {
rs = resolve
})
const id = getUniqueId()
ipcRenderer.once(`mt::response-of-image-path-${id}`, (e, files) => {
rs(files)
})
ipcRenderer.send('mt::ask-for-image-auto-path', { pathname, src, id })
return promise
} else {
return []
}
},
SEARCH ({ commit }, value) {
commit('SET_SEARCH', value)
},
SHOW_IMAGE_DELETION_URL ({ commit }, deletionUrl) {
notice.notify({
title: 'Image deletion URL',
message: `Click to copy the deletion URL of the uploaded image to the clipboard (${deletionUrl}).`,
showConfirm: true,
time: 20000
})
.then(() => {
clipboard.writeText(deletionUrl)
})
},
FORCE_CLOSE_TAB ({ commit, dispatch }, file) {
commit('REMOVE_FILE_WITHIN_TABS', file)
const { pathname } = file
// Notify main process to remove the file from the window and free resources.
if (pathname) {
ipcRenderer.send('mt::window-tab-closed', pathname)
}
},
EXCHANGE_TABS_BY_ID ({ commit }, tabIDs) {
commit('EXCHANGE_TABS_BY_ID', tabIDs)
},
// We need to update line endings menu when changing tabs.
UPDATE_LINE_ENDING_MENU ({ state }) {
const { lineEnding } = state.currentFile
if (lineEnding) {
const { windowId } = global.marktext.env
ipcRenderer.send('mt::update-line-ending-menu', windowId, lineEnding)
}
},
CLOSE_UNSAVED_TAB ({ commit, state }, file) {
const { id, pathname, filename, markdown } = file
const options = getOptionsFromState(file)
// Save the file content via main process and send a close tab response.
ipcRenderer.send('mt::save-and-close-tabs', [{ id, pathname, filename, markdown, options }])
},
// need pass some data to main process when `save` menu item clicked
LISTEN_FOR_SAVE ({ state, rootState }) {
ipcRenderer.on('mt::editor-ask-file-save', () => {
const { id, filename, pathname, markdown } = state.currentFile
const options = getOptionsFromState(state.currentFile)
const defaultPath = getRootFolderFromState(rootState)
if (id) {
ipcRenderer.send('mt::response-file-save', {
id,
filename,
pathname,
markdown,
options,
defaultPath
})
}
})
},
// need pass some data to main process when `save as` menu item clicked
LISTEN_FOR_SAVE_AS ({ state, rootState }) {
ipcRenderer.on('mt::editor-ask-file-save-as', () => {
const { id, filename, pathname, markdown } = state.currentFile
const options = getOptionsFromState(state.currentFile)
const defaultPath = getRootFolderFromState(rootState)
if (id) {
ipcRenderer.send('mt::response-file-save-as', {
id,
filename,
pathname,
markdown,
options,
defaultPath
})
}
})
},
LISTEN_FOR_SET_PATHNAME ({ commit, dispatch, state }) {
ipcRenderer.on('mt::set-pathname', (e, fileInfo) => {
const { tabs } = state
const { pathname, id } = fileInfo
const tab = tabs.find(f => f.id === id)
if (!tab) {
console.err('[ERROR] Cannot change file path from unknown tab.')
return
}
// If a tab with the same file path already exists we need to close the tab.
// The existing tab is overwritten by this tab.
const existingTab = tabs.find(t => t.id !== id && isSamePathSync(t.pathname, pathname))
if (existingTab) {
dispatch('CLOSE_TAB', existingTab)
}
commit('SET_PATHNAME', { tab, fileInfo })
})
ipcRenderer.on('mt::tab-saved', (e, tabId) => {
const { tabs } = state
const tab = tabs.find(f => f.id === tabId)
if (tab) {
Object.assign(tab, { isSaved: true })
}
})
ipcRenderer.on('mt::tab-save-failure', (e, tabId, msg) => {
const { tabs } = state
const tab = tabs.find(t => t.id === tabId)
if (!tab) {
notice.notify({
title: 'Save failure',
message: msg,
type: 'error',
time: 20000,
showConfirm: false
})
return
}
commit('SET_SAVE_STATUS_BY_TAB', { tab, status: false })
commit('PUSH_TAB_NOTIFICATION', {
tabId,
msg: `There was an error while saving: ${msg}`,
style: 'crit'
})
})
},
LISTEN_FOR_CLOSE ({ state }) {
ipcRenderer.on('mt::ask-for-close', e => {
const unsavedFiles = state.tabs
.filter(file => !file.isSaved)
.map(file => {
const { id, filename, pathname, markdown } = file
const options = getOptionsFromState(file)
return { id, filename, pathname, markdown, options }
})
if (unsavedFiles.length) {
ipcRenderer.send('mt::close-window-confirm', unsavedFiles)
} else {
ipcRenderer.send('mt::close-window')
}
})
},
LISTEN_FOR_SAVE_CLOSE ({ commit }) {
ipcRenderer.on('mt::force-close-tabs-by-id', (e, tabIdList) => {
if (Array.isArray(tabIdList) && tabIdList.length) {
commit('CLOSE_TABS', tabIdList)
}
})
},
ASK_FOR_SAVE_ALL ({ commit, state }, closeTabs) {
const { tabs } = state
const unsavedFiles = tabs
.filter(file => !(file.isSaved && /[^\n]/.test(file.markdown)))
.map(file => {
const { id, filename, pathname, markdown } = file
const options = getOptionsFromState(file)
return { id, filename, pathname, markdown, options }
})
if (closeTabs) {
if (unsavedFiles.length) {
commit('CLOSE_TABS', tabs.filter(f => f.isSaved).map(f => f.id))
ipcRenderer.send('mt::save-and-close-tabs', unsavedFiles)
} else {
commit('CLOSE_TABS', tabs.map(f => f.id))
}
} else {
ipcRenderer.send('mt::save-tabs', unsavedFiles)
}
},
LISTEN_FOR_MOVE_TO ({ state, rootState }) {
ipcRenderer.on('mt::editor-move-file', () => {
const { id, filename, pathname, markdown } = state.currentFile
const options = getOptionsFromState(state.currentFile)
const defaultPath = getRootFolderFromState(rootState)
if (!id) return
if (!pathname) {
// if current file is a newly created file, just save it!
ipcRenderer.send('mt::response-file-save', {
id,
filename,
pathname,
markdown,
options,
defaultPath
})
} else {
// if not, move to a new(maybe) folder
ipcRenderer.send('mt::response-file-move-to', { id, pathname })
}
})
},
LISTEN_FOR_RENAME ({ commit, state, dispatch }) {
ipcRenderer.on('mt::editor-rename-file', () => {
dispatch('RESPONSE_FOR_RENAME')
})
},
RESPONSE_FOR_RENAME ({ state, rootState }) {
const { id, filename, pathname, markdown } = state.currentFile
const options = getOptionsFromState(state.currentFile)
const defaultPath = getRootFolderFromState(rootState)
if (!id) return
if (!pathname) {
// if current file is a newly created file, just save it!
ipcRenderer.send('mt::response-file-save', {
id,
filename,
pathname,
markdown,
options,
defaultPath
})
} else {
bus.$emit('rename')
}
},
// ask for main process to rename this file to a new name `newFilename`
RENAME ({ commit, state }, newFilename) {
const { id, pathname, filename } = state.currentFile
if (typeof filename === 'string' && filename !== newFilename) {
const newPathname = path.join(path.dirname(pathname), newFilename)
ipcRenderer.send('mt::rename', { id, pathname, newPathname })
}
},
UPDATE_CURRENT_FILE ({ commit, state, dispatch }, currentFile) {
commit('SET_CURRENT_FILE', currentFile)
const { tabs } = state
if (!tabs.some(file => file.id === currentFile.id)) {
commit('ADD_FILE_TO_TABS', currentFile)
}
dispatch('UPDATE_LINE_ENDING_MENU')
},
// This events are only used during window creation.
LISTEN_FOR_BOOTSTRAP_WINDOW ({ commit, state, dispatch, rootState }) {
// Delay load runtime commands and initialize commands.
setTimeout(() => {
bus.$emit('cmd::register-command', new FileEncodingCommand(rootState.editor))
bus.$emit('cmd::register-command', new QuickOpenCommand(rootState))
bus.$emit('cmd::register-command', new LineEndingCommand(rootState.editor))
bus.$emit('cmd::register-command', new TrailingNewlineCommand(rootState.editor))
setTimeout(() => {
ipcRenderer.send('mt::request-keybindings')
bus.$emit('cmd::sort-commands')
}, 100)
}, 400)
ipcRenderer.on('mt::bootstrap-editor', (e, config) => {
const {
addBlankTab,
markdownList,
lineEnding,
sideBarVisibility,
tabBarVisibility,
sourceCodeModeEnabled
} = config
dispatch('SEND_INITIALIZED')
commit('SET_USER_PREFERENCE', { endOfLine: lineEnding })
commit('SET_LAYOUT', {
rightColumn: 'files',
showSideBar: !!sideBarVisibility,
showTabBar: !!tabBarVisibility
})
dispatch('DISPATCH_LAYOUT_MENU_ITEMS')
commit('SET_MODE', {
type: 'sourceCode',
checked: !!sourceCodeModeEnabled
})
if (addBlankTab) {
dispatch('NEW_UNTITLED_TAB', {})
} else if (markdownList.length) {
let isFirst = true
for (const markdown of markdownList) {
isFirst = false
dispatch('NEW_UNTITLED_TAB', { markdown, selected: isFirst })
}
}
})
},
// Open a new tab, optionally with content.
LISTEN_FOR_NEW_TAB ({ dispatch }) {
ipcRenderer.on('mt::open-new-tab', (e, markdownDocument, options = {}, selected = true) => {
if (markdownDocument) {
// Create tab with content.
dispatch('NEW_TAB_WITH_CONTENT', { markdownDocument, options, selected })
} else {
// Fallback: create a blank tab and always select it
dispatch('NEW_UNTITLED_TAB', {})
}
})
ipcRenderer.on('mt::new-untitled-tab', (e, selected = true, markdown = '') => {
// Create a blank tab
dispatch('NEW_UNTITLED_TAB', { markdown, selected })
})
},
LISTEN_FOR_CLOSE_TAB ({ commit, state, dispatch }) {
ipcRenderer.on('mt::editor-close-tab', e => {
const file = state.currentFile
if (!hasKeys(file)) return
dispatch('CLOSE_TAB', file)
})
},
LISTEN_FOR_TAB_CYCLE ({ commit, state, dispatch }) {
ipcRenderer.on('mt::tabs-cycle-left', e => {
dispatch('CYCLE_TABS', false)
})
ipcRenderer.on('mt::tabs-cycle-right', e => {
dispatch('CYCLE_TABS', true)
})
},
LISTEN_FOR_SWITCH_TABS ({ commit, state, dispatch }) {
ipcRenderer.on('mt::switch-tab-by-index', (event, index) => {
dispatch('SWITCH_TAB_BY_INDEX', index)
})
},
CLOSE_TAB ({ dispatch }, file) {
const { isSaved } = file
if (isSaved) {
dispatch('FORCE_CLOSE_TAB', file)
} else {
dispatch('CLOSE_UNSAVED_TAB', file)
}
},
CLOSE_OTHER_TABS ({ state, dispatch }, file) {
const { tabs } = state
tabs.filter(f => f.id !== file.id).forEach(tab => {
dispatch('CLOSE_TAB', tab)
})
},
CLOSE_SAVED_TABS ({ state, dispatch }) {
const { tabs } = state
tabs.filter(f => f.isSaved).forEach(tab => {
dispatch('CLOSE_TAB', tab)
})
},
CLOSE_ALL_TABS ({ state, dispatch }) {
const { tabs } = state
tabs.slice().forEach(tab => {
dispatch('CLOSE_TAB', tab)
})
},
RENAME_FILE ({ commit, dispatch }, file) {
commit('SET_CURRENT_FILE', file)
dispatch('UPDATE_LINE_ENDING_MENU')
bus.$emit('rename')
},
// Direction is a boolean where false is left and true right.
CYCLE_TABS ({ commit, dispatch, state }, direction) {
const { tabs, currentFile } = state
if (tabs.length <= 1) {
return
}
const currentIndex = tabs.findIndex(t => t.id === currentFile.id)
if (currentIndex === -1) {
console.error('CYCLE_TABS: Cannot find current tab index.')
return
}
let nextTabIndex = 0
if (!direction) {
// Switch tab to the left.
nextTabIndex = currentIndex === 0 ? tabs.length - 1 : currentIndex - 1
} else {
// Switch tab to the right.
nextTabIndex = (currentIndex + 1) % tabs.length
}
const nextTab = tabs[nextTabIndex]
if (!nextTab || !nextTab.id) {
console.error(`CYCLE_TABS: Cannot find next tab (index="${nextTabIndex}").`)
return
}
commit('SET_CURRENT_FILE', nextTab)
dispatch('UPDATE_LINE_ENDING_MENU')
},
SWITCH_TAB_BY_INDEX ({ commit, dispatch, state }, nextTabIndex) {
const { tabs, currentFile } = state
if (nextTabIndex < 0 || nextTabIndex >= tabs.length) {
console.warn('Invalid tab index:', nextTabIndex)
return
}
const currentIndex = tabs.findIndex(t => t.id === currentFile.id)
if (currentIndex === -1) {
console.error('Cannot find current tab index.')
return
}
const nextTab = tabs[nextTabIndex]
if (!nextTab || !nextTab.id) {
console.error(`Cannot find tab by index="${nextTabIndex}".`)
return
}
commit('SET_CURRENT_FILE', nextTab)
dispatch('UPDATE_LINE_ENDING_MENU')
},
/**
* Create a new untitled tab optional from a markdown string.
*
* @param {*} context The store context.
* @param {{markdown?: string, selected?: boolean}} obj Optional markdown string
* and whether the tab should become the selected tab (true if not set).
*/
NEW_UNTITLED_TAB ({ commit, state, dispatch, rootState }, { markdown: markdownString, selected }) {
// If not set select the tab.
if (selected == null) {
selected = true
}
dispatch('SHOW_TAB_VIEW', false)
const { defaultEncoding, endOfLine } = rootState.preferences
const { tabs } = state
const fileState = getBlankFileState(tabs, defaultEncoding, endOfLine, markdownString)
if (selected) {
const { id, markdown } = fileState
dispatch('UPDATE_CURRENT_FILE', fileState)
bus.$emit('file-loaded', { id, markdown })
} else {
commit('ADD_FILE_TO_TABS', fileState)
}
},
/**
* Create a new tab from the given markdown document.
*
* @param {*} context The store context.
* @param {{markdownDocument: IMarkdownDocumentRaw, selected?: boolean}} obj The markdown document
* and optional whether the tab should become the selected tab (true if not set).
*/
NEW_TAB_WITH_CONTENT ({ commit, state, dispatch }, { markdownDocument, options = {}, selected }) {
if (!markdownDocument) {
console.warn('Cannot create a file tab without a markdown document!')
dispatch('NEW_UNTITLED_TAB', {})
return
}
// Select the tab if not value is specified.
if (typeof selected === 'undefined') {
selected = true
}
// Check if tab already exist and always select existing tab if so.
const { currentFile, tabs } = state
const { pathname } = markdownDocument
const existingTab = tabs.find(t => isSamePathSync(t.pathname, pathname))
if (existingTab) {
dispatch('UPDATE_CURRENT_FILE', existingTab)
return
}
// Replace/close selected untitled empty tab
let keepTabBarState = false
if (currentFile) {
const { isSaved, pathname } = currentFile
if (isSaved && !pathname) {
keepTabBarState = true
dispatch('FORCE_CLOSE_TAB', currentFile)
}
}
if (!keepTabBarState) {
dispatch('SHOW_TAB_VIEW', false)
}
const { markdown, isMixedLineEndings } = markdownDocument
const docState = createDocumentState(Object.assign(markdownDocument, options))
const { id, cursor } = docState
if (selected) {
dispatch('UPDATE_CURRENT_FILE', docState)
bus.$emit('file-loaded', { id, markdown, cursor })
} else {
commit('ADD_FILE_TO_TABS', docState)
}
if (isMixedLineEndings) {
const { filename, lineEnding } = markdownDocument
commit('PUSH_TAB_NOTIFICATION', {
tabId: id,
msg: `${filename}" has mixed line endings which are automatically normalized to ${lineEnding.toUpperCase()}.`
})
}
},
SHOW_TAB_VIEW ({ commit, state, dispatch }, always) {
const { tabs } = state
if (always || tabs.length === 1) {
commit('SET_LAYOUT', { showTabBar: true })
dispatch('DISPATCH_LAYOUT_MENU_ITEMS')
}
},
// Content change from realtime preview editor and source code editor
// WORKAROUND: id is "muya" if changes come from muya and not source code editor! So we don't have to apply the workaround.
LISTEN_FOR_CONTENT_CHANGE ({ commit, dispatch, state, rootState }, { id, markdown, wordCount, cursor, history, toc }) {
const { autoSave } = rootState.preferences
const {
id: currentId,
filename,
pathname,
markdown: oldMarkdown,
trimTrailingNewline
} = state.currentFile
const { listToc } = state
if (!id) {
throw new Error('Listen for document change but id was not set!')
} else if (!currentId || state.tabs.length === 0) {
// Discard changes - this case should normally not occur.
return
} else if (id !== 'muya' && currentId !== id) {
// WORKAROUND: We commit changes after switching the tab in source code mode.
// Update old tab or discard changes
for (const tab of state.tabs) {
if (tab.id && tab.id === id) {
tab.markdown = adjustTrailingNewlines(markdown, tab.trimTrailingNewline)
// Set cursor
if (cursor) {
tab.cursor = cursor
}
// Set history
if (history) {
tab.history = history
}
break
}
}
return
}
markdown = adjustTrailingNewlines(markdown, trimTrailingNewline)
commit('SET_MARKDOWN', markdown)
// Ignore new line which is added if the editor text is empty (#422)
if (oldMarkdown.length === 0 && markdown.length === 1 && markdown[0] === '\n') {
return
}
// Word count
if (wordCount) {
commit('SET_WORD_COUNT', wordCount)
}
// Set cursor
if (cursor) {
commit('SET_CURSOR', cursor)
}
// Set history
if (history) {
commit('SET_HISTORY', history)
}
// Set toc
if (toc && !equal(toc, listToc)) {
commit('SET_TOC', toc)
}
// Change save status/save to file only when the markdown changed!
if (markdown !== oldMarkdown) {
commit('SET_SAVE_STATUS', false)
// Save file is auto save is enable and file exist on disk.
if (pathname && autoSave) {
const options = getOptionsFromState(state.currentFile)
dispatch('HANDLE_AUTO_SAVE', {
id: currentId,
filename,
pathname,
markdown,
options
})
}
}
},
HANDLE_AUTO_SAVE ({ commit, state, rootState }, { id, filename, pathname, markdown, options }) {
if (!id || !pathname) {
throw new Error('HANDLE_AUTO_SAVE: Invalid tab.')
}
const { tabs } = state
const { autoSaveDelay } = rootState.preferences
if (autoSaveTimers.has(id)) {
const timer = autoSaveTimers.get(id)
clearTimeout(timer)
autoSaveTimers.delete(id)
}
const timer = setTimeout(() => {
autoSaveTimers.delete(id)
// Validate that the tab still exists. A tab is unchanged until successfully saved
// or force closed. The user decides whether to discard or save the tab when
// gracefully closed. The automatically save event may fire meanwhile.
const tab = tabs.find(t => t.id === id)
if (tab && !tab.isSaved) {
const defaultPath = getRootFolderFromState(rootState)
// Tab changed status is set after the file is saved.
ipcRenderer.send('mt::response-file-save', {
id,
filename,
pathname,
markdown,
options,
defaultPath
})
}
}, autoSaveDelay)
autoSaveTimers.set(id, timer)
},
SELECTION_CHANGE ({ commit }, changes) {
const { start, end } = changes
// Set search keyword to store.
if (start.key === end.key && start.block.text) {
const value = start.block.text.substring(start.offset, end.offset)
commit('SET_SEARCH', {
matches: [],
index: -1,
value
})
}
const { windowId } = global.marktext.env
ipcRenderer.send('mt::editor-selection-changed', windowId, createApplicationMenuState(changes))
},
SELECTION_FORMATS (_, formats) {
const { windowId } = global.marktext.env
ipcRenderer.send('mt::update-format-menu', windowId, createSelectionFormatState(formats))
},
EXPORT ({ state }, { type, content, pageOptions }) {
if (!hasKeys(state.currentFile)) return
// Extract title from TOC buffer.
let title = ''
const { listToc } = state
if (listToc && listToc.length > 0) {
let headerRef = listToc[0]
// The main title should be at the beginning of the document.
const len = Math.min(listToc.length, 6)
for (let i = 1; i < len; ++i) {
if (headerRef.lvl === 1) {
break
}
const header = listToc[i]
if (headerRef.lvl > header.lvl) {
headerRef = header
}
}
title = headerRef.content
}
const { filename, pathname } = state.currentFile
ipcRenderer.send('mt::response-export', {
type,
title,
content,
filename,
pathname,
pageOptions
})
},
LINTEN_FOR_EXPORT_SUCCESS ({ commit }) {
ipcRenderer.on('mt::export-success', (e, { type, filePath }) => {
notice.notify({
title: 'Exported successfully',
message: `Exported "${path.basename(filePath)}" successfully!`,
showConfirm: true
})
.then(() => {
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | true |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/listenForMain.js | src/renderer/store/listenForMain.js | import { ipcRenderer } from 'electron'
import bus from '../bus'
const state = {}
const getters = {}
const mutations = {}
const actions = {
LISTEN_FOR_EDIT ({ commit }) {
ipcRenderer.on('mt::editor-edit-action', (e, type) => {
if (type === 'findInFolder') {
commit('SET_LAYOUT', {
rightColumn: 'search',
showSideBar: true
})
}
bus.$emit(type, type)
})
},
LISTEN_FOR_SHOW_DIALOG ({ commit }) {
ipcRenderer.on('mt::about-dialog', e => {
bus.$emit('aboutDialog')
})
ipcRenderer.on('mt::show-export-dialog', (e, type) => {
bus.$emit('showExportDialog', type)
})
},
LISTEN_FOR_PARAGRAPH_INLINE_STYLE () {
ipcRenderer.on('mt::editor-paragraph-action', (e, { type }) => {
bus.$emit('paragraph', type)
})
ipcRenderer.on('mt::editor-format-action', (e, { type }) => {
bus.$emit('format', type)
})
}
}
const listenForMain = { state, getters, mutations, actions }
export default listenForMain
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/index.js | src/renderer/store/index.js | import Vue from 'vue'
import Vuex from 'vuex'
import { ipcRenderer } from 'electron'
import listenForMain from './listenForMain'
import project from './project'
import editor from './editor'
import layout from './layout'
import preferences from './preferences'
import autoUpdates from './autoUpdates'
import notification from './notification'
import tweet from './tweet'
import commandCenter from './commandCenter'
Vue.use(Vuex)
// global states
const state = {
platform: process.platform, // platform of system `darwin` | `win32` | `linux`
appVersion: process.versions.MARKTEXT_VERSION_STRING, // MarkText version string
windowActive: true, // whether current window is active or focused
init: false // whether MarkText is initialized
}
const getters = {}
const mutations = {
SET_WIN_STATUS (state, status) {
state.windowActive = status
},
SET_INITIALIZED (state) {
state.init = true
}
}
const actions = {
LINTEN_WIN_STATUS ({ commit, state }) {
ipcRenderer.on('mt::window-active-status', (e, { status }) => {
commit('SET_WIN_STATUS', status)
})
},
SEND_INITIALIZED ({ commit }) {
commit('SET_INITIALIZED')
}
}
const store = new Vuex.Store({
state,
getters,
mutations,
actions,
modules: {
// have no states
listenForMain,
autoUpdates,
notification,
tweet,
// have states
project,
preferences,
editor,
layout,
commandCenter
}
})
export default store
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/preferences.js | src/renderer/store/preferences.js | import { ipcRenderer } from 'electron'
import bus from '../bus'
// user preference
const state = {
autoSave: false,
autoSaveDelay: 5000,
titleBarStyle: 'custom',
openFilesInNewWindow: false,
openFolderInNewWindow: false,
zoom: 1.0,
hideScrollbar: false,
wordWrapInToc: false,
fileSortBy: 'created',
startUpAction: 'lastState',
defaultDirectoryToOpen: '',
language: 'en',
editorFontFamily: 'Open Sans',
fontSize: 16,
lineHeight: 1.6,
codeFontSize: 14,
codeFontFamily: 'DejaVu Sans Mono',
codeBlockLineNumbers: true,
trimUnnecessaryCodeBlockEmptyLines: true,
editorLineWidth: '',
autoPairBracket: true,
autoPairMarkdownSyntax: true,
autoPairQuote: true,
endOfLine: 'default',
defaultEncoding: 'utf8',
autoGuessEncoding: true,
trimTrailingNewline: 2,
textDirection: 'ltr',
hideQuickInsertHint: false,
imageInsertAction: 'folder',
imagePreferRelativeDirectory: false,
imageRelativeDirectoryName: 'assets',
hideLinkPopup: false,
autoCheck: false,
preferLooseListItem: true,
bulletListMarker: '-',
orderListDelimiter: '.',
preferHeadingStyle: 'atx',
tabSize: 4,
listIndentation: 1,
frontmatterType: '-',
superSubScript: false,
footnote: false,
isHtmlEnabled: true,
isGitlabCompatibilityEnabled: false,
sequenceTheme: 'hand',
theme: 'light',
autoSwitchTheme: 2,
spellcheckerEnabled: false,
spellcheckerNoUnderline: false,
spellcheckerLanguage: 'en-US',
// Default values that are overwritten with the entries below.
sideBarVisibility: false,
tabBarVisibility: false,
sourceCodeModeEnabled: false,
searchExclusions: [],
searchMaxFileSize: '',
searchIncludeHidden: false,
searchNoIgnore: false,
searchFollowSymlinks: true,
watcherUsePolling: false,
// --------------------------------------------------------------------------
// Edit modes of the current window (not part of persistent settings)
typewriter: false, // typewriter mode
focus: false, // focus mode
sourceCode: false, // source code mode
// user configration
imageFolderPath: '',
webImages: [],
cloudImages: [],
currentUploader: 'none',
githubToken: '',
imageBed: {
github: {
owner: '',
repo: '',
branch: ''
}
},
cliScript: ''
}
const getters = {}
const mutations = {
SET_USER_PREFERENCE (state, preference) {
Object.keys(preference).forEach(key => {
if (typeof preference[key] !== 'undefined' && typeof state[key] !== 'undefined') {
state[key] = preference[key]
}
})
},
SET_MODE (state, { type, checked }) {
state[type] = checked
},
TOGGLE_VIEW_MODE (state, entryName) {
state[entryName] = !state[entryName]
}
}
const actions = {
ASK_FOR_USER_PREFERENCE ({ commit }) {
ipcRenderer.send('mt::ask-for-user-preference')
ipcRenderer.send('mt::ask-for-user-data')
ipcRenderer.on('mt::user-preference', (e, preferences) => {
commit('SET_USER_PREFERENCE', preferences)
})
},
SET_SINGLE_PREFERENCE ({ commit }, { type, value }) {
// save to electron-store
ipcRenderer.send('mt::set-user-preference', { [type]: value })
},
SET_USER_DATA ({ commit }, { type, value }) {
ipcRenderer.send('mt::set-user-data', { [type]: value })
},
SET_IMAGE_FOLDER_PATH ({ commit }, value) {
ipcRenderer.send('mt::ask-for-modify-image-folder-path', value)
},
SELECT_DEFAULT_DIRECTORY_TO_OPEN ({ commit }) {
ipcRenderer.send('mt::select-default-directory-to-open')
},
LISTEN_FOR_VIEW ({ commit, dispatch }) {
ipcRenderer.on('mt::show-command-palette', () => {
bus.$emit('show-command-palette')
})
ipcRenderer.on('mt::toggle-view-mode-entry', (event, entryName) => {
commit('TOGGLE_VIEW_MODE', entryName)
dispatch('DISPATCH_EDITOR_VIEW_STATE', { [entryName]: state[entryName] })
})
},
// Toggle a view option and notify main process to toggle menu item.
LISTEN_TOGGLE_VIEW ({ commit, dispatch, state }) {
bus.$on('view:toggle-view-entry', entryName => {
commit('TOGGLE_VIEW_MODE', entryName)
dispatch('DISPATCH_EDITOR_VIEW_STATE', { [entryName]: state[entryName] })
})
},
DISPATCH_EDITOR_VIEW_STATE (_, viewState) {
const { windowId } = global.marktext.env
ipcRenderer.send('mt::view-layout-changed', windowId, viewState)
}
}
const preferences = { state, getters, mutations, actions }
export default preferences
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/autoUpdates.js | src/renderer/store/autoUpdates.js | import { ipcRenderer } from 'electron'
import notice from '../services/notification'
const state = {}
const getters = {}
const mutations = {}
// mt::UPDATE_DOWNLOADED
const actions = {
LISTEN_FOR_UPDATE ({ commit }) {
ipcRenderer.on('mt::UPDATE_ERROR', (e, message) => {
notice.notify({
title: 'Update',
type: 'error',
time: 10000,
message
})
})
ipcRenderer.on('mt::UPDATE_NOT_AVAILABLE', (e, message) => {
notice.notify({
title: 'Update not Available',
type: 'primary',
message
})
})
ipcRenderer.on('mt::UPDATE_DOWNLOADED', (e, message) => {
notice.notify({
title: 'Update Downloaded',
type: 'info',
message
})
})
ipcRenderer.on('mt::UPDATE_AVAILABLE', (e, message) => {
notice.notify({
title: 'Update Available',
type: 'primary',
message,
showConfirm: true
})
.then(() => {
const needUpdate = true
ipcRenderer.send('mt::NEED_UPDATE', { needUpdate })
})
.catch(() => {
const needUpdate = false
ipcRenderer.send('mt::NEED_UPDATE', { needUpdate })
})
})
}
}
export default { state, getters, mutations, actions }
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/layout.js | src/renderer/store/layout.js | import { ipcRenderer } from 'electron'
import bus from '../bus'
const width = localStorage.getItem('side-bar-width')
const sideBarWidth = typeof +width === 'number' ? Math.max(+width, 220) : 280
// messages from main process, and do not change the state
const state = {
rightColumn: 'files',
showSideBar: false,
showTabBar: false,
sideBarWidth
}
const getters = {}
const mutations = {
SET_LAYOUT (state, layout) {
if (layout.showSideBar !== undefined) {
const { windowId } = global.marktext.env
ipcRenderer.send('mt::update-sidebar-menu', windowId, !!layout.showSideBar)
}
Object.assign(state, layout)
},
TOGGLE_LAYOUT_ENTRY (state, entryName) {
state[entryName] = !state[entryName]
},
SET_SIDE_BAR_WIDTH (state, width) {
// TODO: Add side bar to session (GH#732).
localStorage.setItem('side-bar-width', Math.max(+width, 220))
state.sideBarWidth = width
}
}
const actions = {
LISTEN_FOR_LAYOUT ({ state, commit, dispatch }) {
ipcRenderer.on('mt::set-view-layout', (e, layout) => {
if (layout.rightColumn) {
commit('SET_LAYOUT', {
...layout,
rightColumn: layout.rightColumn === state.rightColumn ? '' : layout.rightColumn,
showSideBar: true
})
} else {
commit('SET_LAYOUT', layout)
}
dispatch('DISPATCH_LAYOUT_MENU_ITEMS')
})
ipcRenderer.on('mt::toggle-view-layout-entry', (event, entryName) => {
commit('TOGGLE_LAYOUT_ENTRY', entryName)
dispatch('DISPATCH_LAYOUT_MENU_ITEMS')
})
bus.$on('view:toggle-layout-entry', entryName => {
commit('TOGGLE_LAYOUT_ENTRY', entryName)
const { windowId } = global.marktext.env
ipcRenderer.send('mt::view-layout-changed', windowId, { [entryName]: state[entryName] })
})
},
DISPATCH_LAYOUT_MENU_ITEMS ({ state }) {
const { windowId } = global.marktext.env
const { showTabBar, showSideBar } = state
ipcRenderer.send('mt::view-layout-changed', windowId, { showTabBar, showSideBar })
},
CHANGE_SIDE_BAR_WIDTH ({ commit }, width) {
commit('SET_SIDE_BAR_WIDTH', width)
}
}
export default { state, getters, mutations, actions }
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/notification.js | src/renderer/store/notification.js | import { ipcRenderer, shell } from 'electron'
import notice from '../services/notification'
const state = {}
const getters = {}
const mutations = {}
const actions = {
LISTEN_FOR_NOTIFICATION ({ commit }) {
const DEFAULT_OPTS = {
title: 'Infomation',
type: 'primary',
time: 10000,
message: 'You should never see this message'
}
ipcRenderer.on('mt::show-notification', (e, opts) => {
const options = Object.assign(DEFAULT_OPTS, opts)
notice.notify(options)
})
ipcRenderer.on('mt::pandoc-not-exists', async (e, opts) => {
const options = Object.assign(DEFAULT_OPTS, opts)
options.showConfirm = true
await notice.notify(options)
shell.openExternal('http://pandoc.org')
})
}
}
export default { state, getters, mutations, actions }
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/project.js | src/renderer/store/project.js | import path from 'path'
import { ipcRenderer, shell } from 'electron'
import { addFile, unlinkFile, addDirectory, unlinkDirectory } from './treeCtrl'
import bus from '../bus'
import { create, paste, rename } from '../util/fileSystem'
import { PATH_SEPARATOR } from '../config'
import notice from '../services/notification'
import { getFileStateFromData } from './help'
import { hasMarkdownExtension } from '../../common/filesystem/paths'
const state = {
activeItem: {},
createCache: {},
// Use to cache newly created filename, for open immediately.
newFileNameCache: '',
renameCache: null,
clipboard: null,
projectTree: null
}
const getters = {}
const mutations = {
SET_ROOT_DIRECTORY (state, pathname) {
let name = path.basename(pathname)
if (!name) {
// Root directory such "/" or "C:\"
name = pathname
}
state.projectTree = {
// Root full path
pathname: path.normalize(pathname),
// Root directory name
name,
isDirectory: true,
isFile: false,
isMarkdown: false,
folders: [],
files: []
}
},
SET_NEWFILENAME (state, name) {
state.newFileNameCache = name
},
ADD_FILE (state, change) {
const { projectTree } = state
addFile(projectTree, change)
},
UNLINK_FILE (state, change) {
const { projectTree } = state
unlinkFile(projectTree, change)
},
ADD_DIRECTORY (state, change) {
const { projectTree } = state
addDirectory(projectTree, change)
},
UNLINK_DIRECTORY (state, change) {
const { projectTree } = state
unlinkDirectory(projectTree, change)
},
SET_ACTIVE_ITEM (state, activeItem) {
state.activeItem = activeItem
},
SET_CLIPBOARD (state, data) {
state.clipboard = data
},
CREATE_PATH (state, cache) {
state.createCache = cache
},
SET_RENAME_CACHE (state, cache) {
state.renameCache = cache
}
}
const actions = {
LISTEN_FOR_LOAD_PROJECT ({ commit, dispatch }) {
ipcRenderer.on('mt::open-directory', (e, pathname) => {
commit('SET_ROOT_DIRECTORY', pathname)
commit('SET_LAYOUT', {
rightColumn: 'files',
showSideBar: true,
showTabBar: true
})
dispatch('DISPATCH_LAYOUT_MENU_ITEMS')
})
},
LISTEN_FOR_UPDATE_PROJECT ({ commit, state, dispatch }) {
ipcRenderer.on('mt::update-object-tree', (e, { type, change }) => {
switch (type) {
case 'add': {
const { pathname, data, isMarkdown } = change
commit('ADD_FILE', change)
if (isMarkdown && state.newFileNameCache && pathname === state.newFileNameCache) {
const fileState = getFileStateFromData(data)
dispatch('UPDATE_CURRENT_FILE', fileState)
commit('SET_NEWFILENAME', '')
}
break
}
case 'unlink':
commit('UNLINK_FILE', change)
commit('SET_SAVE_STATUS_WHEN_REMOVE', change)
break
case 'addDir':
commit('ADD_DIRECTORY', change)
break
case 'unlinkDir':
commit('UNLINK_DIRECTORY', change)
break
case 'change':
break
default:
if (process.env.NODE_ENV === 'development') {
console.log(`Unknown directory watch type: "${type}"`)
}
break
}
})
},
CHANGE_ACTIVE_ITEM ({ commit }, activeItem) {
commit('SET_ACTIVE_ITEM', activeItem)
},
CHANGE_CLIPBOARD ({ commit }, data) {
commit('SET_CLIPBOARD', data)
},
ASK_FOR_OPEN_PROJECT ({ commit }) {
ipcRenderer.send('mt::ask-for-open-project-in-sidebar')
},
LISTEN_FOR_SIDEBAR_CONTEXT_MENU ({ commit, state }) {
bus.$on('SIDEBAR::show-in-folder', () => {
const { pathname } = state.activeItem
shell.showItemInFolder(pathname)
})
bus.$on('SIDEBAR::new', type => {
const { pathname, isDirectory } = state.activeItem
const dirname = isDirectory ? pathname : path.dirname(pathname)
commit('CREATE_PATH', { dirname, type })
bus.$emit('SIDEBAR::show-new-input')
})
bus.$on('SIDEBAR::remove', () => {
const { pathname } = state.activeItem
ipcRenderer.invoke('mt::fs-trash-item', pathname).catch(err => {
notice.notify({
title: 'Error while deleting',
type: 'error',
message: err.message
})
})
})
bus.$on('SIDEBAR::copy-cut', type => {
const { pathname: src } = state.activeItem
commit('SET_CLIPBOARD', { type, src })
})
bus.$on('SIDEBAR::paste', () => {
const { clipboard } = state
const { pathname, isDirectory } = state.activeItem
const dirname = isDirectory ? pathname : path.dirname(pathname)
if (clipboard && clipboard.src) {
clipboard.dest = dirname + PATH_SEPARATOR + path.basename(clipboard.src)
if (path.normalize(clipboard.src) === path.normalize(clipboard.dest)) {
notice.notify({
title: 'Paste Forbidden',
type: 'warning',
message: 'Source and destination must not be the same.'
})
return
}
paste(clipboard)
.then(() => {
commit('SET_CLIPBOARD', null)
})
.catch(err => {
notice.notify({
title: 'Error while pasting',
type: 'error',
message: err.message
})
})
}
})
bus.$on('SIDEBAR::rename', () => {
const { pathname } = state.activeItem
commit('SET_RENAME_CACHE', pathname)
bus.$emit('SIDEBAR::show-rename-input')
})
},
CREATE_FILE_DIRECTORY ({ commit, state }, name) {
const { dirname, type } = state.createCache
if (type === 'file' && !hasMarkdownExtension(name)) {
name += '.md'
}
const fullName = `${dirname}/${name}`
create(fullName, type)
.then(() => {
commit('CREATE_PATH', {})
if (type === 'file') {
commit('SET_NEWFILENAME', fullName)
}
})
.catch(err => {
notice.notify({
title: 'Error in Side Bar',
type: 'error',
message: err.message
})
})
},
RENAME_IN_SIDEBAR ({ commit, state }, name) {
const src = state.renameCache
const dirname = path.dirname(src)
const dest = dirname + PATH_SEPARATOR + name
rename(src, dest)
.then(() => {
commit('RENAME_IF_NEEDED', { src, dest })
})
},
OPEN_SETTING_WINDOW () {
ipcRenderer.send('mt::open-setting-window')
}
}
export default { state, getters, mutations, actions }
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/store/tweet.js | src/renderer/store/tweet.js | import { ipcRenderer } from 'electron'
import bus from '../bus'
const state = {}
const getters = {}
const mutations = {}
const actions = {
LISTEN_FOR_TWEET () {
ipcRenderer.on('mt::tweet', (e, type) => {
if (type === 'twitter') {
bus.$emit('tweetDialog')
}
})
}
}
export default { state, getters, mutations, actions }
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/contextMenu/tabs/index.js | src/renderer/contextMenu/tabs/index.js | import { getCurrentWindow, Menu as RemoteMenu, MenuItem as RemoteMenuItem } from '@electron/remote'
import {
CLOSE_THIS,
CLOSE_OTHERS,
CLOSE_SAVED,
CLOSE_ALL,
SEPARATOR,
RENAME,
COPY_PATH,
SHOW_IN_FOLDER
} from './menuItems'
export const showContextMenu = (event, tab) => {
const menu = new RemoteMenu()
const win = getCurrentWindow()
const { pathname } = tab
const CONTEXT_ITEMS = [CLOSE_THIS, CLOSE_OTHERS, CLOSE_SAVED, CLOSE_ALL, SEPARATOR, RENAME, COPY_PATH, SHOW_IN_FOLDER]
const FILE_CONTEXT_ITEMS = [RENAME, COPY_PATH, SHOW_IN_FOLDER]
FILE_CONTEXT_ITEMS.forEach(item => {
item.enabled = !!pathname
})
CONTEXT_ITEMS.forEach(item => {
const menuItem = new RemoteMenuItem(item)
menuItem._tabId = tab.id
menu.append(menuItem)
})
menu.popup([{ window: win, x: event.clientX, y: event.clientY }])
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/contextMenu/tabs/menuItems.js | src/renderer/contextMenu/tabs/menuItems.js | import * as contextMenu from './actions'
// NOTE: This are mutable fields that may change at runtime.
export const SEPARATOR = {
type: 'separator'
}
export const CLOSE_THIS = {
label: 'Close',
id: 'closeThisTab',
click (menuItem, browserWindow) {
contextMenu.closeThis(menuItem._tabId)
}
}
export const CLOSE_OTHERS = {
label: 'Close others',
id: 'closeOtherTabs',
click (menuItem, browserWindow) {
contextMenu.closeOthers(menuItem._tabId)
}
}
export const CLOSE_SAVED = {
label: 'Close saved tabs',
id: 'closeSavedTabs',
click (menuItem, browserWindow) {
contextMenu.closeSaved()
}
}
export const CLOSE_ALL = {
label: 'Close all tabs',
id: 'closeAllTabs',
click (menuItem, browserWindow) {
contextMenu.closeAll()
}
}
export const RENAME = {
label: 'Rename',
id: 'renameFile',
click (menuItem, browserWindow) {
contextMenu.rename(menuItem._tabId)
}
}
export const COPY_PATH = {
label: 'Copy path',
id: 'copyPath',
click (menuItem, browserWindow) {
contextMenu.copyPath(menuItem._tabId)
}
}
export const SHOW_IN_FOLDER = {
label: 'Show in folder',
id: 'showInFolder',
click (menuItem, browserWindow) {
contextMenu.showInFolder(menuItem._tabId)
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/contextMenu/tabs/actions.js | src/renderer/contextMenu/tabs/actions.js | import bus from '../../bus'
export const closeThis = (tabId) => {
bus.$emit('TABS::close-this', tabId)
}
export const closeOthers = (tabId) => {
bus.$emit('TABS::close-others', tabId)
}
export const closeSaved = () => {
bus.$emit('TABS::close-saved')
}
export const closeAll = () => {
bus.$emit('TABS::close-all')
}
export const rename = (tabId) => {
bus.$emit('TABS::rename', tabId)
}
export const copyPath = (tabId) => {
bus.$emit('TABS::copy-path', tabId)
}
export const showInFolder = (tabId) => {
bus.$emit('TABS::show-in-folder', tabId)
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/contextMenu/sideBar/index.js | src/renderer/contextMenu/sideBar/index.js | import { getCurrentWindow, Menu as RemoteMenu, MenuItem as RemoteMenuItem } from '@electron/remote'
import {
SEPARATOR,
NEW_FILE,
NEW_DIRECTORY,
COPY,
CUT,
PASTE,
RENAME,
DELETE,
SHOW_IN_FOLDER
} from './menuItems'
export const showContextMenu = (event, hasPathCache) => {
const menu = new RemoteMenu()
const win = getCurrentWindow()
const CONTEXT_ITEMS = [
NEW_FILE,
NEW_DIRECTORY,
SEPARATOR,
COPY,
CUT,
PASTE,
SEPARATOR,
RENAME,
DELETE,
SEPARATOR,
SHOW_IN_FOLDER
]
PASTE.enabled = hasPathCache
CONTEXT_ITEMS.forEach(item => {
menu.append(new RemoteMenuItem(item))
})
menu.popup([{ window: win, x: event.clientX, y: event.clientY }])
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/contextMenu/sideBar/menuItems.js | src/renderer/contextMenu/sideBar/menuItems.js | import * as contextMenu from './actions'
// NOTE: This are mutable fields that may change at runtime.
export const SEPARATOR = {
type: 'separator'
}
export const NEW_FILE = {
label: 'New File',
id: 'newFileMenuItem',
click (menuItem, browserWindow) {
contextMenu.newFile()
}
}
export const NEW_DIRECTORY = {
label: 'New Directory',
id: 'newDirectoryMenuItem',
click (menuItem, browserWindow) {
contextMenu.newDirectory()
}
}
export const COPY = {
label: 'Copy',
id: 'copyMenuItem',
click (menuItem, browserWindow) {
contextMenu.copy()
}
}
export const CUT = {
label: 'Cut',
id: 'cutMenuItem',
click (menuItem, browserWindow) {
contextMenu.cut()
}
}
export const PASTE = {
label: 'Paste',
id: 'pasteMenuItem',
click (menuItem, browserWindow) {
contextMenu.paste()
}
}
export const RENAME = {
label: 'Rename',
id: 'renameMenuItem',
click (menuItem, browserWindow) {
contextMenu.rename()
}
}
export const DELETE = {
label: 'Move To Trash',
id: 'deleteMenuItem',
click (menuItem, browserWindow) {
contextMenu.remove()
}
}
export const SHOW_IN_FOLDER = {
label: 'Show In Folder',
id: 'showInFolderMenuItem',
click (menuItem, browserWindow) {
contextMenu.showInFolder()
}
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/contextMenu/sideBar/actions.js | src/renderer/contextMenu/sideBar/actions.js | import bus from '../../bus'
export const newFile = (menuItem, browserWindow) => {
bus.$emit('SIDEBAR::new', 'file')
}
export const newDirectory = (menuItem, browserWindow) => {
bus.$emit('SIDEBAR::new', 'directory')
}
export const copy = (menuItem, browserWindow) => {
bus.$emit('SIDEBAR::copy-cut', 'copy')
}
export const cut = (menuItem, browserWindow) => {
bus.$emit('SIDEBAR::copy-cut', 'cut')
}
export const paste = (menuItem, browserWindow) => {
bus.$emit('SIDEBAR::paste')
}
export const rename = (menuItem, browserWindow) => {
bus.$emit('SIDEBAR::rename')
}
export const remove = (menuItem, browserWindow) => {
bus.$emit('SIDEBAR::remove')
}
export const showInFolder = (menuItem, browserWindow) => {
bus.$emit('SIDEBAR::show-in-folder')
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/commands/spellcheckerLanguage.js | src/renderer/commands/spellcheckerLanguage.js | import bus from '../bus'
import notice from '@/services/notification'
import { delay } from '@/util'
import { SpellChecker } from '@/spellchecker'
import { getLanguageName } from '@/spellchecker/languageMap'
// Command to switch the spellchecker language
class SpellcheckerLanguageCommand {
constructor (spellchecker) {
this.id = 'spellchecker.switch-language'
this.description = 'Spelling: Switch language'
this.placeholder = 'Select a language to switch to'
this.shortcut = null
this.spellchecker = spellchecker
this.subcommands = []
this.subcommandSelectedIndex = -1
}
run = async () => {
const langs = await SpellChecker.getAvailableDictionaries()
this.subcommands = langs.map(lang => {
return {
id: `spellchecker.switch-language-id-${lang}`,
description: getLanguageName(lang),
value: lang
}
})
const currentLanguage = this.spellchecker.lang
this.subcommandSelectedIndex = this.subcommands.findIndex(cmd => cmd.value === currentLanguage)
}
execute = async () => {
// Timeout to hide the command palette and then show again to prevent issues.
await delay(100)
bus.$emit('show-command-palette', this)
}
executeSubcommand = async id => {
const command = this.subcommands.find(cmd => cmd.id === id)
if (this.spellchecker.isEnabled) {
bus.$emit('switch-spellchecker-language', command.value)
} else {
notice.notify({
title: 'Spelling',
type: 'warning',
message: 'Cannot change language because spellchecker is disabled.'
})
}
}
unload = () => {
this.subcommands = []
}
}
export default SpellcheckerLanguageCommand
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/commands/index.js | src/renderer/commands/index.js | // List of all static commands that are loaded into command center.
import { ipcRenderer, shell } from 'electron'
import { getCurrentWindow } from '@electron/remote'
import bus from '../bus'
import { delay, isOsx } from '@/util'
import { isUpdatable } from './utils'
import getCommandDescriptionById from './descriptions'
export { default as FileEncodingCommand } from './fileEncoding'
export { default as LineEndingCommand } from './lineEnding'
export { default as QuickOpenCommand } from './quickOpen'
export { default as SpellcheckerLanguageCommand } from './spellcheckerLanguage'
export { default as TrailingNewlineCommand } from './trailingNewline'
export class RootCommand {
constructor (subcommands = []) {
this.id = '#'
this.description = '#'
this.subcommands = subcommands
this.subcommandSelectedIndex = -1
}
async run () {}
async unload () {}
// Execute the command.
async execute () {
throw new Error('Root command.')
}
}
const focusEditorAndExecute = fn => {
setTimeout(() => bus.$emit('editor-focus'), 10)
setTimeout(() => fn(), 150)
}
const commands = [
// --------------------------------------------------------------------------
// File
{
id: 'file.new-tab',
execute: async () => {
ipcRenderer.emit('mt::new-untitled-tab', null)
}
}, {
id: 'file.new-window',
execute: async () => {
ipcRenderer.send('mt::cmd-new-editor-window')
}
}, {
id: 'file.open-file',
execute: async () => {
ipcRenderer.send('mt::cmd-open-file')
}
}, {
id: 'file.open-folder',
execute: async () => {
ipcRenderer.send('mt::cmd-open-folder')
}
}, {
id: 'file.save',
execute: async () => {
ipcRenderer.emit('mt::editor-ask-file-save', null)
}
}, {
id: 'file.save-as',
execute: async () => {
ipcRenderer.emit('mt::editor-ask-file-save-as', null)
}
}, {
id: 'file.print',
execute: async () => {
await delay(50)
bus.$emit('showExportDialog', 'print')
}
}, {
id: 'file.close-tab',
execute: async () => {
ipcRenderer.emit('mt::editor-close-tab', null)
}
}, {
id: 'file.close-window',
execute: async () => {
ipcRenderer.send('mt::cmd-close-window')
}
},
{
id: 'file.toggle-auto-save',
execute: async () => {
ipcRenderer.send('mt::cmd-toggle-autosave')
}
}, {
id: 'file.move-file',
execute: async () => {
ipcRenderer.emit('mt::editor-move-file', null)
}
}, {
id: 'file.rename-file',
execute: async () => {
await delay(50)
ipcRenderer.emit('mt::editor-rename-file', null)
}
}, {
id: 'file.import-file',
execute: async () => {
ipcRenderer.send('mt::cmd-import-file')
}
}, {
id: 'file.export-file',
subcommands: [{
id: 'file.export-file-html',
description: 'HTML',
execute: async () => {
await delay(50)
bus.$emit('showExportDialog', 'styledHtml')
}
}, {
id: 'file.export-file-pdf',
description: 'PDF',
execute: async () => {
await delay(50)
bus.$emit('showExportDialog', 'pdf')
}
}]
},
// --------------------------------------------------------------------------
// Edit
{
id: 'edit.undo',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('undo', 'undo')
)
}
}, {
id: 'edit.redo',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('redo', 'redo')
)
}
}, {
id: 'edit.duplicate',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('duplicate', 'duplicate')
)
}
}, {
id: 'edit.create-paragraph',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('createParagraph', 'createParagraph')
)
}
}, {
id: 'edit.delete-paragraph',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('deleteParagraph', 'deleteParagraph')
)
}
}, {
id: 'edit.find',
execute: async () => {
await delay(150)
bus.$emit('find', 'find')
}
},
// TODO: Find next/previous doesn't work.
// {
// id: 'edit.find-next',
// description: 'Edit: Find Next',
// execute: async () => {
// await delay(150)
// bus.$emit('findNext', 'findNext')
// }
// }, {
// id: 'edit.find-previous',
// description: 'Edit: Find Previous',
// execute: async () => {
// await delay(150)
// bus.$emit('findPrev', 'findPrev')
// }
// },
{
id: 'edit.replace',
execute: async () => {
await delay(150)
bus.$emit('replace', 'replace')
}
}, {
id: 'edit.find-in-folder',
execute: async () => {
await delay(150)
ipcRenderer.emit('mt::editor-edit-action', null, 'findInFolder')
}
},
// --------------------------------------------------------------------------
// Paragraph
{
id: 'paragraph.heading-1',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'heading 1')
)
}
}, {
id: 'paragraph.heading-2',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'heading 2')
)
}
}, {
id: 'paragraph.heading-3',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'heading 3')
)
}
}, {
id: 'paragraph.heading-4',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'heading 4')
)
}
}, {
id: 'paragraph.heading-5',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'heading 5')
)
}
}, {
id: 'paragraph.heading-6',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'heading 6')
)
}
}, {
id: 'paragraph.upgrade-heading',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'upgrade heading')
)
}
}, {
id: 'paragraph.degrade-heading',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'degrade heading')
)
}
}, {
id: 'paragraph.table',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'table')
)
}
}, {
id: 'paragraph.code-fence',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'pre')
)
}
}, {
id: 'paragraph.quote-block',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'blockquote')
)
}
}, {
id: 'paragraph.math-formula',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'mathblock')
)
}
}, {
id: 'paragraph.html-block',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'html')
)
}
}, {
id: 'paragraph.order-list',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'ol-bullet')
)
}
}, {
id: 'paragraph.bullet-list',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'ul-bullet')
)
}
}, {
id: 'paragraph.task-list',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'ul-task')
)
}
}, {
id: 'paragraph.loose-list-item',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'loose-list-item')
)
}
}, {
id: 'paragraph.paragraph',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'paragraph')
)
}
}, {
id: 'paragraph.reset-paragraph',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'reset-to-paragraph')
)
}
}, {
id: 'paragraph.horizontal-line',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'hr')
)
}
}, {
id: 'paragraph.front-matter',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('paragraph', 'front-matter')
)
}
},
// --------------------------------------------------------------------------
// Format
// NOTE: Focus editor to restore selection and try to apply the commmand.
{
id: 'format.strong',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'strong')
)
}
}, {
id: 'format.emphasis',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'em')
)
}
}, {
id: 'format.underline',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'u')
)
}
}, {
id: 'format.highlight',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'mark')
)
}
}, {
id: 'format.superscript',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'sup')
)
}
}, {
id: 'format.subscript',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'sub')
)
}
}, {
id: 'format.inline-code',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'inline_code')
)
}
}, {
id: 'format.inline-math',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'inline_math')
)
}
}, {
id: 'format.strike',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'del')
)
}
}, {
id: 'format.hyperlink',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'link')
)
}
}, {
id: 'format.image',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'image')
)
}
}, {
id: 'format.clear-format',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('format', 'clear')
)
}
},
// --------------------------------------------------------------------------
// Window
{
id: 'window.minimize',
execute: async () => {
getCurrentWindow().minimize()
}
}, {
id: 'window.toggle-always-on-top',
execute: async () => {
ipcRenderer.send('mt::window-toggle-always-on-top')
}
}, {
id: 'window.toggle-full-screen',
execute: async () => {
const win = getCurrentWindow()
win.setFullScreen(!win.isFullScreen())
}
},
{
id: 'file.zoom',
shortcut: [(isOsx ? 'Cmd' : 'Ctrl'), 'Scroll'],
subcommands: [{
id: 'file.zoom-0',
description: '0.625',
value: 0.625
}, {
id: 'file.zoom-1',
description: '0.75',
value: 0.75
}, {
id: 'file.zoom-2',
description: '0.875',
value: 0.875
}, {
id: 'file.zoom-3',
description: '1.0',
value: 1.0
}, {
id: 'file.zoom-4',
description: '1.125',
value: 1.125
}, {
id: 'file.zoom-5',
description: '1.25',
value: 1.25
}, {
id: 'file.zoom-6',
description: '1.375',
value: 1.375
}, {
id: 'file.zoom-7',
description: '1.5',
value: 1.5
}, {
id: 'file.zoom-8',
description: '1.625',
value: 1.625
}, {
id: 'file.zoom-9',
description: '1.75',
value: 1.75
}, {
id: 'file.zoom-10',
description: '1.875',
value: 1.875
}, {
id: 'file.zoom-11',
description: '2.0',
value: 2.0
}],
executeSubcommand: async (_, value) => {
ipcRenderer.emit('mt::window-zoom', null, value)
}
},
// --------------------------------------------------------------------------
// Window
{
id: 'window.change-theme',
subcommands: [{
id: 'window.change-theme-light',
description: 'Cadmium Light',
value: 'light'
}, {
id: 'window.change-theme-dark',
description: 'Dark',
value: 'dark'
}, {
id: 'window.change-theme-graphite',
description: 'Graphite',
value: 'graphite'
}, {
id: 'window.change-theme-material-dark',
description: 'Material Dark',
value: 'material-dark'
}, {
id: 'window.change-theme-one-dark',
description: 'One Dark',
value: 'one-dark'
}, {
id: 'window.change-theme-ulysses',
description: 'Ulysses',
value: 'ulysses'
}],
executeSubcommand: async (_, theme) => {
ipcRenderer.send('mt::set-user-preference', { theme })
}
},
// --------------------------------------------------------------------------
// View
{
id: 'view.source-code-mode',
execute: async () => {
bus.$emit('view:toggle-view-entry', 'sourceCode')
}
}, {
id: 'view.typewriter-mode',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('view:toggle-view-entry', 'typewriter')
)
}
}, {
id: 'view.focus-mode',
execute: async () => {
focusEditorAndExecute(
() => bus.$emit('view:toggle-view-entry', 'focus')
)
}
}, {
id: 'view.toggle-sidebar',
execute: async () => {
bus.$emit('view:toggle-layout-entry', 'showSideBar')
}
}, {
id: 'view.toggle-tabbar',
execute: async () => {
bus.$emit('view:toggle-layout-entry', 'showTabBar')
}
},
{
id: 'view.text-direction',
subcommands: [{
id: 'view.text-direction-ltr',
description: 'Left to Right',
value: 'ltr'
}, {
id: 'view.text-direction-rtl',
description: 'Right to Left',
value: 'rtl'
}],
executeSubcommand: async (_, value) => {
ipcRenderer.send('mt::set-user-preference', { textDirection: value })
}
},
// --------------------------------------------------------------------------
// MarkText
{
id: 'file.preferences',
execute: async () => {
ipcRenderer.send('mt::open-setting-window')
}
}, {
id: 'file.quit',
execute: async () => {
ipcRenderer.send('mt::app-try-quit')
}
}, {
id: 'docs.user-guide',
execute: async () => {
shell.openExternal('https://github.com/marktext/marktext/blob/master/docs/README.md')
}
}, {
id: 'docs.markdown-syntax',
execute: async () => {
shell.openExternal('https://github.com/marktext/marktext/blob/master/docs/MARKDOWN_SYNTAX.md')
}
},
// --------------------------------------------------------------------------
// Misc
{
id: 'tabs.cycle-forward',
execute: async () => {
ipcRenderer.emit('mt::tabs-cycle-right', null)
}
}, {
id: 'tabs.cycle-backward',
execute: async () => {
ipcRenderer.emit('mt::tabs-cycle-left', null)
}
}
]
// --------------------------------------------------------------------------
// etc
if (isUpdatable()) {
commands.push({
id: 'file.check-update',
execute: async () => {
ipcRenderer.send('mt::check-for-update')
}
})
}
if (isOsx) {
commands.push({
id: 'edit.screenshot',
execute: async () => {
ipcRenderer.send('mt::make-screenshot')
}
})
}
// Complete all command descriptions.
for (const item of commands) {
const { id, description } = item
if (id && !description) {
item.description = getCommandDescriptionById(id)
}
}
export default commands
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/commands/trailingNewline.js | src/renderer/commands/trailingNewline.js | import { ipcRenderer } from 'electron'
import { delay } from '@/util'
import bus from '../bus'
const descriptions = [
'Trim all trailing newlines',
'Ensure single newline',
'Disabled'
]
class TrailingNewlineCommand {
constructor (editorState) {
this.id = 'file.trailing-newline'
this.description = 'File: Trailing Newline'
this.placeholder = 'Select an option'
this.subcommands = []
this.subcommandSelectedIndex = -1
// Reference to editor state.
this._editorState = editorState
}
run = async () => {
const { trimTrailingNewline } = this._editorState.currentFile
let index = trimTrailingNewline
if (index !== 0 && index !== 1) {
index = 2
}
this.subcommands = [{
id: 'file.trailing-newline-trim',
description: descriptions[0],
value: 0
}, {
id: 'file.trailing-newline-single',
description: descriptions[1],
value: 1
}, {
id: 'file.trailing-newline-disabled',
description: descriptions[2],
value: 3
}]
this.subcommands[index].description = `${descriptions[index]} - current`
this.subcommandSelectedIndex = index
}
execute = async () => {
// Timeout to hide the command palette and then show again to prevent issues.
await delay(100)
bus.$emit('show-command-palette', this)
}
executeSubcommand = async (_, value) => {
ipcRenderer.emit('mt::set-final-newline', null, value)
}
unload = () => {}
}
export default TrailingNewlineCommand
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/commands/quickOpen.js | src/renderer/commands/quickOpen.js | import path from 'path'
import { ipcRenderer } from 'electron'
import { isChildOfDirectory, hasMarkdownExtension, MARKDOWN_INCLUSIONS } from '../../common/filesystem/paths'
import bus from '../bus'
import { delay } from '@/util'
import FileSearcher from '@/node/fileSearcher'
const SPECIAL_CHARS = /[\[\]\\^$.\|\?\*\+\(\)\/]{1}/g // eslint-disable-line no-useless-escape
// The quick open command
class QuickOpenCommand {
constructor (rootState) {
this.id = 'file.quick-open'
this.description = 'File: Quick Open'
this.placeholder = 'Search file to open'
this.shortcut = null
this.subcommands = []
this.subcommandSelectedIndex = -1
// Reference to folder and editor and project state.
this._editorState = rootState.editor
this._folderState = rootState.project
this._directorySearcher = new FileSearcher()
this._cancelFn = null
}
search = async query => {
// Show opened files when no query given.
if (!query) {
return this.subcommands
}
const { _cancelFn } = this
if (_cancelFn) {
_cancelFn()
this._cancelFn = null
}
const timeout = delay(300)
this._cancelFn = () => {
timeout.cancel()
this._cancelFn = null
}
await timeout
return this._doSearch(query)
}
run = async () => {
const { _editorState, _folderState } = this
if (!_folderState.projectTree && _editorState.tabs.length === 0) {
throw new Error(null)
}
this.subcommands = _editorState.tabs
.map(t => t.pathname)
// Filter untitled tabs
.filter(t => !!t)
.map(pathname => {
const item = { id: pathname }
Object.assign(item, this._getPath(pathname))
return item
})
}
execute = async () => {
// Timeout to hide the command palette and then show again to prevent issues.
await delay(100)
bus.$emit('show-command-palette', this)
}
executeSubcommand = async id => {
const { windowId } = global.marktext.env
ipcRenderer.send('mt::open-file-by-window-id', windowId, id)
}
unload = () => {
this.subcommands = []
}
// --- private ------------------------------------------
_doSearch = query => {
this._cancelFn = null
const { _editorState, _folderState } = this
const isRootDirOpened = !!_folderState.projectTree
const tabsAvailable = _editorState.tabs.length > 0
// Only show opened files if no directory is opened.
if (!isRootDirOpened && !tabsAvailable) {
return []
}
const searchResult = []
const rootPath = isRootDirOpened ? _folderState.projectTree.pathname : null
// Add files that are not in the current root directory but opened.
if (tabsAvailable) {
const re = new RegExp(query.replace(SPECIAL_CHARS, p => {
if (p === '*') return '.*'
return p === '\\' ? '\\\\' : `\\${p}`
}), 'i')
for (const tab of _editorState.tabs) {
const { pathname } = tab
if (pathname && re.test(pathname) &&
(!rootPath || !isChildOfDirectory(rootPath, pathname))
) {
searchResult.push(pathname)
}
}
}
if (!isRootDirOpened) {
return searchResult
.map(pathname => {
return {
id: pathname,
description: pathname,
title: pathname
}
})
}
// Search root directory on disk.
return new Promise((resolve, reject) => {
let canceled = false
const promises = this._directorySearcher.search([rootPath], '', {
didMatch: result => {
if (canceled) return
searchResult.push(result)
},
didSearchPaths: numPathsFound => {
// Cancel when more than 30 files were found. User should specify the search query.
if (!canceled && numPathsFound > 30) {
canceled = true
if (promises.cancel) {
promises.cancel()
}
}
},
// Only search markdown files that contain the query string.
inclusions: this._getInclusions(query)
})
.then(() => {
this._cancelFn = null
resolve(
searchResult
.map(pathname => {
const item = { id: pathname }
Object.assign(item, this._getPath(pathname))
return item
})
)
})
.catch(error => {
this._cancelFn = null
reject(error)
})
this._cancelFn = () => {
this._cancelFn = null
canceled = true
if (promises.cancel) {
promises.cancel()
}
}
})
}
_getInclusions = query => {
// NOTE: This will fail on `foo.m` because we search for `foo.m.md`.
if (hasMarkdownExtension(query)) {
return [`*${query}`]
}
const inclusions = []
for (let i = 0; i < MARKDOWN_INCLUSIONS.length; ++i) {
inclusions[i] = `*${query}` + MARKDOWN_INCLUSIONS[i]
}
return inclusions
}
_getPath = pathname => {
const rootPath = this._folderState.projectTree.pathname
if (!isChildOfDirectory(rootPath, pathname)) {
return { title: pathname, description: pathname }
}
const p = path.relative(rootPath, pathname)
const item = { description: p }
if (p.length > 50) {
item.title = p
}
return item
}
}
export default QuickOpenCommand
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/commands/fileEncoding.js | src/renderer/commands/fileEncoding.js | import { ipcRenderer } from 'electron'
import { ENCODING_NAME_MAP, getEncodingName } from 'common/encoding'
import { delay } from '@/util'
import bus from '../bus'
class FileEncodingCommand {
constructor (editorState) {
this.id = 'file.change-encoding'
this.description = 'File: Change Encoding'
this.placeholder = 'Select an option'
this.subcommands = []
this.subcommandSelectedIndex = -1
// Reference to editor state.
this._editorState = editorState
}
run = async () => {
this.subcommands = []
this.subcommandSelectedIndex = -1
// Load encoding from current tab to highlight it.
const encodingObj = this._getCurrentEncoding()
const { encoding, isBom } = encodingObj
// NOTE: We support UTF-BOM encodings but don't allow to set them.
if (isBom) {
this.subcommandSelectedIndex = 0
this.subcommands.push({
id: `${encoding}-bom`,
description: `${getEncodingName(encodingObj)} - current`
})
}
let i = 0
for (const [key, value] of Object.entries(ENCODING_NAME_MAP)) {
const isTabEncoding = !isBom && key === encoding
const item = {
id: key,
description: isTabEncoding ? `${value} - current` : value
}
if (isTabEncoding) {
// Highlight current encoding and set it as first entry.
this.subcommandSelectedIndex = i
this.subcommands.unshift(item)
} else {
this.subcommands.push(item)
}
++i
}
}
execute = async () => {
// Timeout to hide the command palette and then show again to prevent issues.
await delay(100)
bus.$emit('show-command-palette', this)
}
executeSubcommand = async id => {
// NOTE: We support UTF-BOM encodings but don't allow to set them.
if (!id.endsWith('-bom')) {
ipcRenderer.emit('mt::set-file-encoding', null, id)
}
}
unload = () => {
this.subcommands = []
}
_getCurrentEncoding = () => {
const { _editorState } = this
const { currentFile } = _editorState
if (currentFile) {
return currentFile.encoding
}
return {}
}
}
export default FileEncodingCommand
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/commands/descriptions.js | src/renderer/commands/descriptions.js | const commandDescriptions = Object.freeze({
// ============================================
// # Key binding descriptions
// #
'mt.hide': 'MarkText: Hide MarkText',
'mt.hide-others': 'MarkText: Hide Others',
'file.new-window': 'File: New Window',
'file.new-tab': 'File: New Tab',
'file.open-file': 'File: Open file',
'file.open-folder': 'File: Open Folder',
'file.save': 'File: Save',
'file.save-as': 'File: Save As...',
'file.move-file': 'File: Move...',
'file.rename-file': 'File: Rename...',
'file.quick-open': 'File: Show quick open dialog',
'file.print': 'File: Print current Tab',
'file.preferences': 'MarkText: Preferences',
'file.close-tab': 'File: Close current Tab',
'file.close-window': 'File: Close Window',
'file.quit': 'MarkText: Quit',
'edit.undo': 'Edit: Undo',
'edit.redo': 'Edit: Redo',
'edit.cut': 'Edit: Cut',
'edit.copy': 'Edit: Copy',
'edit.paste': 'Edit: Paste',
'edit.copy-as-markdown': 'Edit: Copy as Markdown',
'edit.copy-as-html': 'Edit: Copy as HTML',
'edit.paste-as-plaintext': 'Edit: Paste as Plain Text',
'edit.select-all': 'Edit: Select All',
'edit.duplicate': 'Edit: Duplicate',
'edit.create-paragraph': 'Edit: Create Paragraph',
'edit.delete-paragraph': 'Edit: Delete Paragraph',
'edit.find': 'Edit: Find',
'edit.find-next': 'Edit: Find Next',
'edit.find-previous': 'Edit: Find Previous',
'edit.replace': 'Edit: Replace',
'edit.find-in-folder': 'Edit: Find in Folder',
'edit.screenshot': 'Edit: Make Screenshot',
'paragraph.heading-1': 'Paragraph: Transform into Heading 1',
'paragraph.heading-2': 'Paragraph: Transform into Heading 2',
'paragraph.heading-3': 'Paragraph: Transform into Heading 3',
'paragraph.heading-4': 'Paragraph: Transform into Heading 4',
'paragraph.heading-5': 'Paragraph: Transform into Heading 5',
'paragraph.heading-6': 'Paragraph: Transform into Heading 6',
'paragraph.upgrade-heading': 'Paragraph: Upgrade Heading',
'paragraph.degrade-heading': 'Paragraph: Degrade Heading',
'paragraph.table': 'Paragraph: Create Table',
'paragraph.code-fence': 'Paragraph: Transform into Code Fence',
'paragraph.quote-block': 'Paragraph: Transform into Quote Block',
'paragraph.math-formula': 'Paragraph: Transform into Math Formula',
'paragraph.html-block': 'Paragraph: Transform into HTML Block',
'paragraph.order-list': 'Paragraph: Transform into Order List',
'paragraph.bullet-list': 'Paragraph: Transform into Bullet List',
'paragraph.task-list': 'Paragraph: Transform into Task List',
'paragraph.loose-list-item': 'Paragraph: Convert to Loose List Item',
'paragraph.paragraph': 'Paragraph: Create new Paragraph',
'paragraph.horizontal-line': 'Paragraph: Insert Horizontal Line',
'paragraph.front-matter': 'Paragraph: Insert Front Matter',
'format.strong': 'Format: Strong',
'format.emphasis': 'Format: Emphasis',
'format.underline': 'Format: Underline',
'format.superscript': 'Format: Superscript',
'format.subscript': 'Format: Subscript',
'format.highlight': 'Format: Highlight',
'format.inline-code': 'Format: Inline Code',
'format.inline-math': 'Format: Inline Math',
'format.strike': 'Format: Strike',
'format.hyperlink': 'Format: Hyperlink',
'format.image': 'Format: Insert Image',
'format.clear-format': 'Format: Clear Format',
'window.minimize': 'Window: Minimize',
'window.toggle-always-on-top': 'Window: Always on Top',
'window.zoom-in': 'Window: Zoom In',
'window.zoom-out': 'Window: Zoom Out',
'window.toggle-full-screen': 'Window: Toggle Full Screen',
'view.command-palette': 'View: Show Command Palette',
'view.source-code-mode': 'View: Toggle Source Code Mode',
'view.typewriter-mode': 'View: Toggle Typewriter Mode',
'view.focus-mode': 'View: Focus Mode',
'view.toggle-sidebar': 'View: Toggle Sidebar',
'view.toggle-toc': 'View: Toggle Table of Content',
'view.toggle-tabbar': 'View: Toggle Tabs',
'view.toggle-dev-tools': 'View: Show Developer Tools (Debug)',
'view.dev-reload': 'View: Reload Window (Debug)',
'tabs.cycle-forward': 'Misc: Cycle Tabs Forward',
'tabs.cycle-backward': 'Misc: Cycle Tabs Backward',
'tabs.switch-to-left': 'Misc: Switch tab to the left',
'tabs.switch-to-right': 'Misc: Switch tab to the right',
'tabs.switch-to-first': 'Misc: Switch tab to the 1st',
'tabs.switch-to-second': 'Misc: Switch tab to the 2st',
'tabs.switch-to-third': 'Misc: Switch tab to the 3st',
'tabs.switch-to-fourth': 'Misc: Switch tab to the 4st',
'tabs.switch-to-fifth': 'Misc: Switch tab to the 5st',
'tabs.switch-to-sixth': 'Misc: Switch tab to the 6st',
'tabs.switch-to-seventh': 'Misc: Switch tab to the 7st',
'tabs.switch-to-eighth': 'Misc: Switch tab to the 8st',
'tabs.switch-to-ninth': 'Misc: Switch tab to the 9st',
'tabs.switch-to-tenth': 'Misc: Switch tab to the 10st',
// ============================================
// # Menu descriptions but not available as command
// #
'view.reload-images': 'View: Force reload images',
// ============================================
// # Additional command descriptions
// #
'file.toggle-auto-save': 'File: Toggle Auto Save',
'file.import-file': 'File: Import...',
'file.export-file': 'File: Export...',
'file.zoom': 'Window: Zoom...',
'file.check-update': 'MarkText: Check for Updates...',
'paragraph.reset-paragraph': 'Paragraph: Transform into Paragraph',
'window.change-theme': 'Theme: Change Theme...',
'view.text-direction': 'View: Set Text Direction',
'docs.user-guide': 'MarkText: End User Guide',
'docs.markdown-syntax': 'MarkText: Markdown Syntax Guide'
})
export default id => {
return commandDescriptions[id]
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/commands/lineEnding.js | src/renderer/commands/lineEnding.js | import { ipcRenderer } from 'electron'
import { delay } from '@/util'
import bus from '../bus'
const crlfDescription = 'Carriage return and line feed (CRLF)'
const lfDescription = 'Line feed (LF)'
class LineEndingCommand {
constructor (editorState) {
this.id = 'file.line-ending'
this.description = 'File: Change Line Ending'
this.placeholder = 'Select an option'
this.subcommands = [{
id: 'file.line-ending-crlf',
description: crlfDescription,
value: 'crlf'
}, {
id: 'file.line-ending-lf',
description: lfDescription,
value: 'lf'
}]
this.subcommandSelectedIndex = -1
// Reference to editor state.
this._editorState = editorState
}
run = async () => {
const { lineEnding } = this._editorState.currentFile
if (lineEnding === 'crlf') {
this.subcommandSelectedIndex = 0
this.subcommands[0].description = `${crlfDescription} - current`
this.subcommands[1].description = lfDescription
} else {
this.subcommandSelectedIndex = 1
this.subcommands[0].description = crlfDescription
this.subcommands[1].description = `${lfDescription} - current`
}
}
execute = async () => {
// Timeout to hide the command palette and then show again to prevent issues.
await delay(100)
bus.$emit('show-command-palette', this)
}
executeSubcommand = async (_, value) => {
ipcRenderer.emit('mt::set-line-ending', null, value)
}
unload = () => {}
}
export default LineEndingCommand
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/commands/utils.js | src/renderer/commands/utils.js | import path from 'path'
import { isFile } from 'common/filesystem'
/// Check whether the package is updatable at runtime.
export const isUpdatable = () => {
// TODO: If not updatable, allow to check whether there is a new version available.
const resFile = isFile(path.join(process.resourcesPath, 'app-update.yml'))
if (!resFile) {
// No update resource file available.
return false
} else if (process.env.APPIMAGE) {
// We are running as AppImage.
return true
} else if (process.platform === 'win32' && isFile(path.join(process.resourcesPath, 'md.ico'))) {
// Windows is a little but tricky. The update resource file is always available and
// there is no way to check the target type at runtime (electron-builder#4119).
// As workaround we check whether "md.ico" exists that is only included in the setup.
return true
}
// Otherwise assume that we cannot perform an auto update (standalone binary, archives,
// packed for package manager).
return false
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/prefComponents/image/config.js | src/renderer/prefComponents/image/config.js | export const imageActions = [{
label: 'Upload image to cloud using selected uploader (must be configured below)',
value: 'upload'
}, {
label: 'Copy image to designated relative assets or global local folder',
value: 'folder'
}, {
label: 'Keep original location',
value: 'path'
}]
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/prefComponents/image/components/uploader/services.js | src/renderer/prefComponents/image/components/uploader/services.js | // TODO: Remove information from other vue source files into this file.
export const isValidService = name => {
return name !== 'none' && services.hasOwnProperty(name)
}
const services = {
// Dummy service used to opt-in real services.
none: {
name: 'None',
isGdprCompliant: true,
privacyUrl: '',
tosUrl: '',
// Set to true to always allow to change to this dummy service
agreedToLegalNotices: true
},
// Real services
picgo: {
name: 'Picgo',
isGdprCompliant: false,
privacyUrl: '',
tosUrl: 'https://github.com/PicGo/PicGo-Core',
// Currently a non-persistent value
agreedToLegalNotices: true
},
github: {
name: 'GitHub',
isGdprCompliant: true,
privacyUrl: 'https://github.com/site/privacy',
tosUrl: 'https://github.com/site/terms',
// Currently a non-persistent value
agreedToLegalNotices: false
},
cliScript: {
name: 'Command line script',
isGdprCompliant: true,
privacyUrl: '',
tosUrl: '',
agreedToLegalNotices: true
}
}
export default services
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/prefComponents/editor/config.js | src/renderer/prefComponents/editor/config.js | import { ENCODING_NAME_MAP } from 'common/encoding'
export const tabSizeOptions = [{
label: '1',
value: 1
}, {
label: '2',
value: 2
}, {
label: '3',
value: 3
}, {
label: '4',
value: 4
}]
export const endOfLineOptions = [{
label: 'Default',
value: 'default'
}, {
label: 'Carriage return and line feed (CRLF)',
value: 'crlf'
}, {
label: 'Line feed (LF)',
value: 'lf'
}]
export const trimTrailingNewlineOptions = [{
label: 'Trim all trailing',
value: 0
}, {
label: 'Ensure exactly one trailing',
value: 1
}, {
label: 'Preserve style of original document',
value: 2
}, {
label: 'Do nothing',
value: 3
}]
export const textDirectionOptions = [{
label: 'Left to Right',
value: 'ltr'
}, {
label: 'Right to Left',
value: 'rtl'
}]
let defaultEncodingOptions = null
export const getDefaultEncodingOptions = () => {
if (defaultEncodingOptions) {
return defaultEncodingOptions
}
defaultEncodingOptions = []
for (const [value, label] of Object.entries(ENCODING_NAME_MAP)) {
defaultEncodingOptions.push({ label, value })
}
return defaultEncodingOptions
}
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/prefComponents/general/config.js | src/renderer/prefComponents/general/config.js | export const titleBarStyleOptions = [{
label: 'Custom',
value: 'custom'
}, {
label: 'Native',
value: 'native'
}]
export const zoomOptions = [{
label: '50.0%',
value: 0.5
}, {
label: '62.5%',
value: 0.625
}, {
label: '75.0%',
value: 0.75
}, {
label: '87.5%',
value: 0.875
}, {
label: '100.0%',
value: 1.0
}, {
label: '112.5%',
value: 1.125
}, {
label: '125.0%',
value: 1.25
}, {
label: '137.5%',
value: 1.375
}, {
label: '150.0%',
value: 1.5
}, {
label: '162.5%',
value: 1.625
}, {
label: '175.0%',
value: 1.75
}, {
label: '187.5%',
value: 1.875
}, {
label: '200.0%',
value: 2.0
}]
export const fileSortByOptions = [{
label: 'Creation time',
value: 'created'
}, {
label: 'Modification time',
value: 'modified'
}, {
label: 'Title',
value: 'title'
}]
export const languageOptions = [{
label: 'English',
value: 'en'
}]
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
marktext/marktext | https://github.com/marktext/marktext/blob/aa71e33e07845419533d767ad0d260a7c267cec7/src/renderer/prefComponents/theme/config.js | src/renderer/prefComponents/theme/config.js | export const themes = [
{
name: 'light'
},
{
name: 'dark'
},
{
name: 'graphite'
},
{
name: 'material-dark'
},
{
name: 'ulysses'
},
{
name: 'one-dark'
}
]
export const autoSwitchThemeOptions = [{
label: 'Adjust theme at startup', // Always
value: 0
}, /* {
label: 'Only at runtime',
value: 1
}, */ {
label: 'Never',
value: 2
}]
| javascript | MIT | aa71e33e07845419533d767ad0d260a7c267cec7 | 2026-01-04T14:57:09.944492Z | false |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.