🎨 run biome check on core

This commit is contained in:
Nate Sesti 2024-04-13 23:55:44 -07:00
parent 0c15100ff4
commit 4bd76b662d
65 changed files with 270 additions and 325 deletions

View file

@ -1,15 +0,0 @@
{
"$schema": "https://biomejs.dev/schemas/1.6.4/schema.json",
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"formatter": {
"indentStyle": "space"
}
}

View file

@ -1,5 +1,5 @@
process.env.IS_BINARY = "true";
import fs from "fs";
import fs from "node:fs";
import { Command } from "commander";
import { getCoreLogsPath } from "core/util/paths";
import { IpcIde } from "./IpcIde";

View file

@ -1,6 +1,6 @@
import { v4 as uuidv4 } from "uuid";
import * as fs from "fs";
import * as fs from "node:fs";
import { getCoreLogsPath } from "core/util/paths";
import type { Message } from "../../core/util/messenger";
import type { Protocol, ReverseProtocol } from "./protocol";
@ -50,7 +50,7 @@ export class IpcMessenger {
try {
const msg: Message = JSON.parse(line);
if (msg.messageType === undefined || msg.messageId === undefined) {
throw new Error("Invalid message sent: " + JSON.stringify(msg));
throw new Error(`Invalid message sent: ${JSON.stringify(msg)}`);
}
// Call handler and respond with return value
@ -99,7 +99,7 @@ export class IpcMessenger {
messageId,
};
// process.send?.(data);
process.stdout?.write(JSON.stringify(data) + "\r\n");
process.stdout?.write(`${JSON.stringify(data)}\r\n`);
return messageId;
}

View file

@ -9,6 +9,10 @@
"recommended": true,
"suspicious": {
"noExplicitAny": "off"
},
"style": {
"noUselessElse": "off",
"noNonNullAssertion": "off"
}
}
},

View file

@ -69,11 +69,11 @@ function formatExternalSnippet(
) {
const comment = language.comment;
const lines = [
comment + " Path: " + getBasename(filepath),
`${comment} Path: ${getBasename(filepath)}`,
...snippet
.trim()
.split("\n")
.map((line) => comment + " " + line),
.map((line) => `${comment} ${line}`),
comment,
];
return lines.join("\n");
@ -191,7 +191,7 @@ export async function getTabCompletion(
)
.join("\n");
if (formattedSnippets.length > 0) {
prefix = formattedSnippets + "\n\n" + prefix;
prefix = `${formattedSnippets}\n\n${prefix}`;
}
prompt = compiledTemplate({

View file

@ -8,7 +8,7 @@ export async function* noTopLevelKeywordsMidline(
): LineStream {
for await (const line of lines) {
for (const keyword of topLevelKeywords) {
const indexOf = line.indexOf(keyword + " ");
const indexOf = line.indexOf(`${keyword} `);
if (indexOf >= 0 && line.slice(indexOf - 1, indexOf).trim() !== "") {
yield line.slice(0, indexOf);
break;
@ -26,7 +26,7 @@ export async function* avoidPathLine(
// Sometimes the model with copy this pattern, which is unwanted
for await (const line of stream) {
// Also filter lines that are empty comments
if (line.startsWith(comment + " Path: ") || line.trim() === comment) {
if (line.startsWith(`${comment} Path: `) || line.trim() === comment) {
continue;
}
yield line;
@ -112,9 +112,8 @@ export async function* filterCodeBlockLines(rawLines: LineStream): LineStream {
if (!seenValidLine) {
if (shouldRemoveLineBeforeStart(line)) {
continue;
} else {
seenValidLine = true;
}
seenValidLine = true;
}
// Filter out ending ```

View file

@ -114,7 +114,7 @@ function mergeOverlappingRangeContents(
): string {
const firstLines = first.contents.split("\n");
const numOverlapping = first.range.end.line - second.range.start.line;
return firstLines.slice(-numOverlapping).join("\n") + "\n" + second.contents;
return `${firstLines.slice(-numOverlapping).join("\n")}\n${second.contents}`;
}
/**
@ -134,7 +134,6 @@ export function fillPromptWithSnippets(
tokensRemaining -= tokenCount;
keptSnippets.push(snippet);
} else {
continue;
}
}
@ -146,18 +145,17 @@ function rangeIntersectionByLines(a: Range, b: Range): Range | null {
const endLine = Math.min(a.end.line, b.end.line);
if (startLine >= endLine) {
return null;
} else {
return {
start: {
line: startLine,
character: 0,
},
end: {
line: endLine,
character: 0,
},
};
}
return {
start: {
line: startLine,
character: 0,
},
end: {
line: endLine,
character: 0,
},
};
}
/**
@ -170,7 +168,8 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
) {
// / | | /
return [];
} else if (
}
if (
orig.start.line <= remove.start.line &&
orig.end.line >= remove.end.line
) {
@ -186,7 +185,8 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
end: orig.end,
},
];
} else if (
}
if (
orig.start.line >= remove.start.line &&
orig.end.line >= remove.end.line
) {
@ -197,7 +197,8 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
end: orig.end,
},
];
} else if (
}
if (
orig.start.line <= remove.start.line &&
orig.end.line <= remove.end.line
) {
@ -208,9 +209,8 @@ function rangeDifferenceByLines(orig: Range, remove: Range): Range[] {
end: remove.start,
},
];
} else {
return [orig];
}
return [orig];
}
export function removeRangeFromSnippets(

View file

@ -51,14 +51,12 @@ const starcoder2FimTemplate: AutocompleteTemplate = {
const otherFiles =
snippets.length === 0
? ""
: "<file_sep>" +
snippets
: `<file_sep>${snippets
.map((snippet) => {
return snippet.contents;
// return `${getBasename(snippet.filepath)}\n${snippet.contents}`;
})
.join("<file_sep>") +
"<file_sep>";
.join("<file_sep>")}<file_sep>`;
const prompt = `${otherFiles}<fim_prefix>${prefix}<fim_suffix>${suffix}<fim_middle>`;
return prompt;

View file

@ -117,7 +117,7 @@ export class GeneratorReuseManager {
}
let alreadyTyped = prefix.slice(this.pendingGeneratorPrefix?.length) || "";
for await (let chunk of this.currentGenerator!.tee()) {
for await (let chunk of this.currentGenerator?.tee()) {
if (!chunk) {
continue;
}

View file

@ -31,7 +31,7 @@ const DraftIssueCommand: SlashCommand = {
{ maxTokens: 20 },
);
title = removeQuotesAndEscapes(title.trim()) + "\n\n";
title = `${removeQuotesAndEscapes(title.trim())}\n\n`;
yield title;
let body = "";

View file

@ -131,7 +131,7 @@ export async function getPromptParts(
rif.contents = rif.contents.substring(1);
}
while (rif.contents.endsWith("\n")) {
fileSuffix = "\n" + fileSuffix;
fileSuffix = `\n${fileSuffix}`;
rif.contents = rif.contents.substring(0, rif.contents.length - 1);
}
}
@ -144,7 +144,7 @@ function compilePrompt(
fileSuffix: string,
input: string,
): string {
if (contents.trim() == "") {
if (contents.trim() === "") {
// Separate prompt for insertion at the cursor, the other tends to cause it to repeat whole file
return `\
<file_prefix>
@ -162,7 +162,7 @@ Please output the code to be inserted at the cursor in order to fulfill the user
}
let prompt = PROMPT;
if (filePrefix.trim() != "") {
if (filePrefix.trim() !== "") {
prompt += `
<file_prefix>
${filePrefix}
@ -173,7 +173,7 @@ ${filePrefix}
${contents}
</code_to_edit>`;
if (fileSuffix.trim() != "") {
if (fileSuffix.trim() !== "") {
prompt += `
<file_suffix>
${fileSuffix}
@ -234,7 +234,7 @@ const EditSlashCommand: SlashCommand = {
const content = history[history.length - 1].content;
if (typeof content !== "string") {
content.forEach((part) => {
if (part.text && part.text.startsWith("/edit")) {
if (part.text?.startsWith("/edit")) {
part.text = part.text.replace("/edit", "").trimStart();
}
});
@ -301,13 +301,9 @@ const EditSlashCommand: SlashCommand = {
linesToDisplay = contentsLines.slice(rewrittenLines);
}
const newFileContents =
fullPrefixLines.join("\n") +
"\n" +
completion +
"\n" +
(linesToDisplay.length > 0 ? linesToDisplay.join("\n") + "\n" : "") +
fullSuffixLines.join("\n");
const newFileContents = `${fullPrefixLines.join("\n")}\n${completion}\n${
linesToDisplay.length > 0 ? `${linesToDisplay.join("\n")}\n` : ""
}${fullSuffixLines.join("\n")}`;
const stepIndex = history.length - 1;
@ -532,11 +528,11 @@ const EditSlashCommand: SlashCommand = {
break;
}
// Lines that should be ignored, like the <> tags
else if (lineToBeIgnored(chunkLines[i], completionLinesCovered === 0)) {
if (lineToBeIgnored(chunkLines[i], completionLinesCovered === 0)) {
continue; // noice
}
// Check if we are currently just copying the prefix
else if (
if (
(linesOfPrefixCopied > 0 || completionLinesCovered === 0) &&
linesOfPrefixCopied < filePrefix.split("\n").length &&
chunkLines[i] === fullPrefixLines[linesOfPrefixCopied]
@ -547,7 +543,7 @@ const EditSlashCommand: SlashCommand = {
}
// Because really short lines might be expected to be repeated, this is only a !heuristic!
// Stop when it starts copying the fileSuffix
else if (
if (
chunkLines[i].trim() === lineBelowHighlightedRange.trim() &&
chunkLines[i].trim().length > 4 &&
!(

View file

@ -18,7 +18,7 @@ function getLastUserHistory(history: ChatMessage[]): string {
if (!lastUserHistory) return "";
if (lastUserHistory.content instanceof Array) {
if (Array.isArray(lastUserHistory.content)) {
return lastUserHistory.content.reduce(
(acc: string, current: { type: string; text?: string }) => {
return current.type === "text" && current.text

View file

@ -1,5 +1,5 @@
import * as fs from "fs";
import path from "path";
import * as fs from "node:fs";
import path from "node:path";
import type {
BrowserSerializedContinueConfig,
Config,
@ -42,7 +42,7 @@ import {
getContinueDotEnv,
migrate,
} from "../util/paths";
const { execSync } = require("child_process");
const { execSync } = require("node:child_process");
function resolveSerializedConfig(filepath: string): SerializedContinueConfig {
let content = fs.readFileSync(filepath, "utf8");
@ -201,7 +201,7 @@ async function intermediateToFinalConfig(
{
...desc,
model: modelName,
title: llm.title + " - " + modelName,
title: `${llm.title} - ${modelName}`,
},
readFile,
copyOf(config.completionOptions),
@ -389,14 +389,13 @@ async function buildConfigTs() {
try {
if (process.env.IS_BINARY === "true") {
execSync(
escapeSpacesInPath(path.dirname(process.execPath)) +
`/esbuild${
getTarget().startsWith("win32") ? ".exe" : ""
} ${escapeSpacesInPath(
getConfigTsPath(),
)} --bundle --outfile=${escapeSpacesInPath(
getConfigJsPath(),
)} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process`,
`${escapeSpacesInPath(path.dirname(process.execPath))}/esbuild${
getTarget().startsWith("win32") ? ".exe" : ""
} ${escapeSpacesInPath(
getConfigTsPath(),
)} --bundle --outfile=${escapeSpacesInPath(
getConfigJsPath(),
)} --platform=node --format=cjs --sourcemap --external:fetch --external:fs --external:path --external:os --external:child_process`,
);
} else {
// Dynamic import esbuild so potentially disastrous errors can be caught
@ -414,7 +413,7 @@ async function buildConfigTs() {
}
} catch (e) {
console.log(
"Build error. Please check your ~/.continue/config.ts file: " + e,
`Build error. Please check your ~/.continue/config.ts file: ${e}`,
);
return undefined;
}

View file

@ -1,4 +1,4 @@
import { readFileSync, writeFileSync } from "fs";
import { readFileSync, writeFileSync } from "node:fs";
import type { ModelDescription } from "..";
import { editConfigJson, getConfigJsonPath } from "../util/paths";

View file

@ -32,7 +32,7 @@ class DatabaseContextProvider extends BaseContextProvider {
const getDatabaseAdapter = await require("dbinfoz");
for (const connection of connections) {
if (connection.name == connectionName) {
if (connection.name === connectionName) {
const adapter = getDatabaseAdapter(
connection.connection_type,
connection.connection,
@ -47,7 +47,7 @@ class DatabaseContextProvider extends BaseContextProvider {
const contextItem = {
name: `${connectionName}-all-tables-schemas`,
description: `Schema for all tables.`,
description: "Schema for all tables.",
content: prompt,
};
@ -101,7 +101,7 @@ class DatabaseContextProvider extends BaseContextProvider {
const contextItem = {
id: `${connection.name}.all`,
title: `${connection.name} all table schemas`,
description: ``,
description: "",
};
contextItems.push(contextItem);
@ -110,7 +110,7 @@ class DatabaseContextProvider extends BaseContextProvider {
const contextItem = {
id: `${connection.name}.${tableName}`,
title: `${connection.name}.${tableName} schema`,
description: ``,
description: "",
};
contextItems.push(contextItem);

View file

@ -28,7 +28,7 @@ function formatFileTree(tree: Directory, indentation = ""): string {
for (const directory of tree.directories) {
result += `${indentation}${directory.name}/\n`;
result += formatFileTree(directory, indentation + " ");
result += formatFileTree(directory, `${indentation} `);
}
return result;
@ -82,9 +82,9 @@ class FileTreeContextProvider extends BaseContextProvider {
return [
{
content:
"Here is a file tree of the current workspace:\n\n" +
trees.join("\n\n"),
content: `Here is a file tree of the current workspace:\n\n${trees.join(
"\n\n",
)}`,
name: "File Tree",
description: "File Tree",
},

View file

@ -46,7 +46,7 @@ class GitHubIssuesContextProvider extends BaseContextProvider {
issue.data.body || "No description",
...comments.data.map((comment) => comment.body),
];
content += "\n\n" + parts.join("\n\n---\n\n");
content += `\n\n${parts.join("\n\n---\n\n")}`;
return [
{

View file

@ -84,7 +84,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
const token = this.options.token;
if (!token) {
throw new Error(`GitLab Private Token is required!`);
throw new Error("GitLab Private Token is required!");
}
return Axios.create({
@ -100,13 +100,13 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
): Promise<RemoteBranchInfo> {
const subprocess = await getSubprocess(extras);
const branchName = await subprocess(`git branch --show-current`);
const branchName = await subprocess("git branch --show-current");
const branchRemote = await subprocess(
`git config branch.${branchName}.remote`,
);
const branchInfo = await subprocess(`git branch -vv`);
const branchInfo = await subprocess("git branch -vv");
const currentBranchInfo = branchInfo
.split("\n")
@ -118,13 +118,13 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
console.dir({ remoteMatches });
const remoteBranch = remoteMatches?.groups?.["remote_branch"] ?? null;
const remoteBranch = remoteMatches?.groups?.remote_branch ?? null;
const remoteUrl = await subprocess(`git remote get-url ${branchRemote}`);
const urlMatches = /:(?<project>.*).git/.exec(remoteUrl);
const project = urlMatches?.groups?.["project"] ?? null;
const project = urlMatches?.groups?.project ?? null;
return {
branch: remoteBranch,
@ -162,7 +162,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
`# GitLab Merge Request\ntitle: "${
mergeRequest.title
}"\ndescription: "${mergeRequest.description ?? "None"}"`,
`## Comments`,
"## Comments",
];
const comments = await api.get<Array<GitLabComment>>(
@ -243,7 +243,7 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
if (filename !== "general") {
parts.push(`### File ${filename}`);
locationComments.sort(
(a, b) => a.position!.new_line - b.position!.new_line,
(a, b) => a.position?.new_line - b.position?.new_line,
);
} else {
parts.push("### General");
@ -260,11 +260,11 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
result.push({
name: mergeRequest.title,
content,
description: `Comments from the Merge Request for this branch.`,
description: "Comments from the Merge Request for this branch.",
});
}
} catch (ex) {
let content = `# GitLab Merge Request\n\nError getting merge request. `;
let content = "# GitLab Merge Request\n\nError getting merge request. ";
if (ex instanceof AxiosError) {
if (ex.response) {
const errorMessage = ex.response?.data
@ -280,9 +280,9 @@ class GitLabMergeRequestContextProvider extends BaseContextProvider {
}
result.push({
name: `GitLab Merge Request`,
name: "GitLab Merge Request",
content,
description: `Error getting the Merge Request for this branch.`,
description: "Error getting the Merge Request for this branch.",
});
}

View file

@ -42,14 +42,14 @@ class GoogleContextProvider extends BaseContextProvider {
const jsonResults = JSON.parse(results);
let content = `Google Search: ${query}\n\n`;
const answerBox = jsonResults["answerBox"];
const answerBox = jsonResults.answerBox;
if (answerBox) {
content += `Answer Box (${answerBox["title"]}): ${answerBox["answer"]}\n\n`;
content += `Answer Box (${answerBox.title}): ${answerBox.answer}\n\n`;
}
for (const result of jsonResults["organic"]) {
content += `${result["title"]}\n${result["link"]}\n${result["snippet"]}\n\n`;
for (const result of jsonResults.organic) {
content += `${result.title}\n${result.link}\n${result.snippet}\n\n`;
}
return [

View file

@ -68,7 +68,8 @@ export class JiraClient {
private authHeader;
constructor(options: JiraClientOptions) {
this.options = {
issueQuery: `assignee = currentUser() AND resolution = Unresolved order by updated DESC`,
issueQuery:
"assignee = currentUser() AND resolution = Unresolved order by updated DESC",
apiVersion: "3",
requestOptions: {},
...options,
@ -76,9 +77,9 @@ export class JiraClient {
this.baseUrl = `https://${this.options.domain}/rest/api/${this.options.apiVersion}`;
this.authHeader = this.options.username
? {
Authorization:
"Basic " +
btoa(this.options.username + ":" + this.options.password),
Authorization: `Basic ${btoa(
`${this.options.username}:${this.options.password}`,
)}`,
}
: {
Authorization: `Bearer ${this.options.password}`,
@ -90,7 +91,7 @@ export class JiraClient {
const response = await fetchwithRequestOptions(
new URL(
this.baseUrl + `/issue/${issueId}?fields=description,comment,summary`,
`${this.baseUrl}/issue/${issueId}?fields=description,comment,summary`,
),
{
method: "GET",
@ -136,11 +137,10 @@ export class JiraClient {
async listIssues(): Promise<Array<QueryResult>> {
const response = await fetchwithRequestOptions(
new URL(
this.baseUrl +
`/search?fields=summary&jql=${
this.options.issueQuery ??
`assignee = currentUser() AND resolution = Unresolved order by updated DESC`
}`,
`${this.baseUrl}/search?fields=summary&jql=${
this.options.issueQuery ??
"assignee = currentUser() AND resolution = Unresolved order by updated DESC"
}`,
),
{
method: "GET",
@ -152,7 +152,7 @@ export class JiraClient {
this.options.requestOptions,
);
if (response.status != 200) {
if (response.status !== 200) {
console.warn(
"Unable to get jira tickets. Response code from API is",
response.status,

View file

@ -23,7 +23,7 @@ class LocalsProvider extends BaseContextProvider {
const localVariables = await extras.ide.getDebugLocals(Number(query));
const threadIndex = Number(query);
const thread = (await extras.ide.getAvailableThreads()).find(
(thread) => thread.id == threadIndex,
(thread) => thread.id === threadIndex,
);
const callStacksSources = await extras.ide.getTopLevelCallStackSources(
threadIndex,
@ -31,7 +31,7 @@ class LocalsProvider extends BaseContextProvider {
);
const callStackContents = callStacksSources.reduce(
(acc, source, index) =>
acc + `\n\ncall stack ${index}\n` + "```\n" + source + "\n```",
`${acc}\n\ncall stack ${index}\n\`\`\`\n${source}\n`\`\``,
"",
);
return [

View file

@ -1,7 +1,7 @@
//os.platform()
//os.arch()
import os from "os";
import os from "node:os";
import { BaseContextProvider } from "..";
import type {
ContextItem,

View file

@ -18,18 +18,6 @@ class PostgresContextProvider extends BaseContextProvider {
static ALL_TABLES = "__all_tables";
static DEFAULT_SAMPLE_ROWS = 3;
constructor(options: {
host: string;
port: number;
user: string;
password: string;
database: string;
schema?: string;
sampleRows?: number;
}) {
super(options);
}
private async getPool() {
const pg = await require("pg");
return new pg.Pool({
@ -43,7 +31,7 @@ class PostgresContextProvider extends BaseContextProvider {
private async getTableNames(pool: any): Promise<string[]> {
const schema = this.options.schema ?? "public";
var tablesInfoQuery = `
let tablesInfoQuery = `
SELECT table_schema, table_name
FROM information_schema.tables`;
if (schema != null) {
@ -78,7 +66,7 @@ FROM information_schema.tables`;
`Table name must be in format schema.table_name, got ${tableName}`,
);
}
var schemaQuery = `
const schemaQuery = `
SELECT column_name, data_type, character_maximum_length
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_schema = '${tableName.split(".")[0]}'
@ -96,7 +84,7 @@ FROM ${tableName}
LIMIT ${sampleRows}`);
// Create prompt from the table schema and sample rows
var prompt = `Postgres schema for database ${this.options.database} table ${tableName}:\n`;
let prompt = `Postgres schema for database ${this.options.database} table ${tableName}:\n`;
prompt += `${JSON.stringify(tableSchema, null, 2)}\n\n`;
prompt += `Sample rows: ${JSON.stringify(sampleRowResults, null, 2)}`;

View file

@ -46,7 +46,7 @@ class ProblemsContextProvider extends BaseContextProvider {
? [
{
description: "Problems in current file",
content: `There are no problems found in the open file.`,
content: "There are no problems found in the open file.",
name: "No problems found",
},
]

View file

@ -68,14 +68,14 @@ export class LLMReranker implements Reranker {
if (answer === "yes") {
return 1.0;
} else if (answer === "no") {
return 0.0;
} else {
console.warn(
`Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".`,
);
}
if (answer === "no") {
return 0.0;
}
console.warn(
`Unexpected response from single token reranker: "${answer}". Expected "yes" or "no".`,
);
return 0.0;
}
async rerank(query: string, chunks: Chunk[]): Promise<number[]> {

View file

@ -49,7 +49,8 @@ export function matchLine(
if (linesMatchPerfectly(newLine, oldLines[i])) {
return [i, true, newLine];
} else if (linesMatch(newLine, oldLines[i], i)) {
}
if (linesMatch(newLine, oldLines[i], i)) {
// This is a way to fix indentation, but only for sufficiently long lines to avoid matching whitespace or short lines
if (
newLine.trimStart() === oldLines[i].trimStart() &&

View file

@ -1,5 +1,5 @@
import fs from "fs";
import path from "path";
import fs from "node:fs";
import path from "node:path";
import type {
ChunkWithoutID,
ContextItem,
@ -112,7 +112,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
// Add snippets to sqlite
for (const snippet of snippets) {
const { lastID } = await db.run(
`INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)`,
"INSERT INTO code_snippets (path, cacheKey, content, title, startLine, endLine) VALUES (?, ?, ?, ?, ?, ?)",
[
compute.path,
compute.cacheKey,
@ -124,7 +124,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
);
await db.run(
`INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`,
"INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
[lastID, tagString],
);
}
@ -139,10 +139,10 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
for (let i = 0; i < results.del.length; i++) {
const del = results.del[i];
const deleted = await db.run(
`DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?`,
"DELETE FROM code_snippets WHERE path = ? AND cacheKey = ?",
[del.path, del.cacheKey],
);
await db.run(`DELETE FROM code_snippets_tags WHERE snippetId = ?`, [
await db.run("DELETE FROM code_snippets_tags WHERE snippetId = ?", [
deleted.lastID,
]);
markComplete([del], IndexResultType.Delete);
@ -150,13 +150,13 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
for (let i = 0; i < results.addTag.length; i++) {
const snippetsWithPath = await db.all(
`SELECT * FROM code_snippets WHERE cacheKey = ?`,
"SELECT * FROM code_snippets WHERE cacheKey = ?",
[results.addTag[i].cacheKey],
);
for (const snippet of snippetsWithPath) {
await db.run(
`INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)`,
"INSERT INTO code_snippets_tags (snippetId, tag) VALUES (?, ?)",
[snippet.id, tagString],
);
}
@ -183,7 +183,7 @@ export class CodeSnippetsCodebaseIndex implements CodebaseIndex {
static async getForId(id: number): Promise<ContextItem> {
const db = await SqliteDb.get();
const row = await db.get(`SELECT * FROM code_snippets WHERE id = ?`, [id]);
const row = await db.get("SELECT * FROM code_snippets WHERE id = ?", [id]);
return {
name: row.title,

View file

@ -43,17 +43,17 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
// Insert chunks
const chunks = await db.all(
`SELECT * FROM chunks WHERE path = ? AND cacheKey = ?`,
"SELECT * FROM chunks WHERE path = ? AND cacheKey = ?",
[item.path, item.cacheKey],
);
for (const chunk of chunks) {
const { lastID } = await db.run(
`INSERT INTO fts (path, content) VALUES (?, ?)`,
"INSERT INTO fts (path, content) VALUES (?, ?)",
[item.path, chunk.content],
);
await db.run(
`INSERT INTO fts_metadata (id, path, cacheKey, chunkId) VALUES (?, ?, ?, ?)`,
"INSERT INTO fts_metadata (id, path, cacheKey, chunkId) VALUES (?, ?, ?, ?)",
[lastID, item.path, item.cacheKey, chunk.id],
);
}
@ -78,10 +78,10 @@ export class FullTextSearchCodebaseIndex implements CodebaseIndex {
// Delete
for (const item of results.del) {
const { lastID } = await db.run(
`DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?`,
"DELETE FROM fts_metadata WHERE path = ? AND cacheKey = ?",
[item.path, item.cacheKey],
);
await db.run(`DELETE FROM fts WHERE rowid = ?`, [lastID]);
await db.run("DELETE FROM fts WHERE rowid = ?", [lastID]);
markComplete([item], IndexResultType.Delete);
}

View file

@ -32,7 +32,7 @@ interface LanceDbRow {
export class LanceDbIndex implements CodebaseIndex {
get artifactId(): string {
return "vectordb::" + this.embeddingsProvider.id;
return `vectordb::${this.embeddingsProvider.id}`;
}
static MAX_CHUNK_SIZE = MAX_CHUNK_SIZE;
@ -276,7 +276,7 @@ export class LanceDbIndex implements CodebaseIndex {
table = await db.createTable(tableName, lanceRows);
needToCreateTable = false;
} else if (lanceRows.length > 0) {
await table!.add(lanceRows);
await table?.add(lanceRows);
}
markComplete([{ path, cacheKey }], IndexResultType.AddTag);
@ -286,7 +286,7 @@ export class LanceDbIndex implements CodebaseIndex {
if (!needToCreateTable) {
for (const { path, cacheKey } of [...results.removeTag, ...results.del]) {
// This is where the aforementioned lowercase conversion problem shows
await table!.delete(`cachekey = '${cacheKey}' AND path = '${path}'`);
await table?.delete(`cachekey = '${cacheKey}' AND path = '${path}'`);
}
}
markComplete(results.removeTag, IndexResultType.RemoveTag);

View file

@ -57,7 +57,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
async function handleChunk(chunk: Chunk) {
const { lastID } = await db.run(
`INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)`,
"INSERT INTO chunks (cacheKey, path, idx, startLine, endLine, content) VALUES (?, ?, ?, ?, ?, ?)",
[
chunk.digest,
chunk.filepath,
@ -68,7 +68,7 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
],
);
await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [
await db.run("INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)", [
lastID,
tagString,
]);
@ -124,12 +124,12 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
// Add tag
for (const item of results.addTag) {
const chunksWithPath = await db.all(
`SELECT * FROM chunks WHERE cacheKey = ?`,
"SELECT * FROM chunks WHERE cacheKey = ?",
[item.cacheKey],
);
for (const chunk of chunksWithPath) {
await db.run(`INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)`, [
await db.run("INSERT INTO chunk_tags (chunkId, tag) VALUES (?, ?)", [
chunk.id,
tagString,
]);
@ -156,12 +156,12 @@ export class ChunkCodebaseIndex implements CodebaseIndex {
// Delete
for (const item of results.del) {
const deleted = await db.run(`DELETE FROM chunks WHERE cacheKey = ?`, [
const deleted = await db.run("DELETE FROM chunks WHERE cacheKey = ?", [
item.cacheKey,
]);
// Delete from chunk_tags
await db.run(`DELETE FROM chunk_tags WHERE chunkId = ?`, [
await db.run("DELETE FROM chunk_tags WHERE chunkId = ?", [
deleted.lastID,
]);

View file

@ -20,7 +20,7 @@ export function* basicChunker(
}
if (lineTokens < maxChunkSize) {
chunkContent += line + "\n";
chunkContent += `${line}\n`;
chunkTokens += lineTokens + 1;
}

View file

@ -6,9 +6,8 @@ import { getParserForFile } from "../../util/treeSitter";
function collapsedReplacement(node: SyntaxNode): string {
if (node.type === "statement_block") {
return "{ ... }";
} else {
return "...";
}
return "...";
}
function firstChild(
@ -19,9 +18,8 @@ function firstChild(
return (
node.children.find((child) => grammarName.includes(child.type)) || null
);
} else {
return node.children.find((child) => child.type === grammarName) || null;
}
return node.children.find((child) => child.type === grammarName) || null;
}
function collapseChildren(
@ -130,12 +128,10 @@ function constructFunctionDefinitionChunk(
// If inside a class, include the class header
const classNode = node.parent.parent;
const classBlock = node.parent;
return (
code.slice(classNode.startIndex, classBlock.startIndex) +
"...\n\n" +
" ".repeat(node.startPosition.column) + // ...
funcText
);
return `${code.slice(
classNode.startIndex,
classBlock.startIndex,
)}...\n\n${" ".repeat(node.startPosition.column)}${funcText}`;
}
return funcText;
}

View file

@ -74,7 +74,8 @@ export async function* markdownChunker(
},
};
return;
} else if (hLevel > 4) {
}
if (hLevel > 4) {
const header = findHeader(content.split("\n"));
for (const chunk of basicChunker(content, maxChunkSize)) {
@ -89,7 +90,7 @@ export async function* markdownChunker(
return;
}
const h = "#".repeat(hLevel + 1) + " ";
const h = `${"#".repeat(hLevel + 1)} `;
const lines = content.split("\n");
const sections = [];
@ -131,7 +132,7 @@ export async function* markdownChunker(
hLevel + 1,
)) {
yield {
content: section.header + "\n" + chunk.content,
content: `${section.header}\n${chunk.content}`,
startLine: section.startLine + chunk.startLine,
endLine: section.startLine + chunk.endLine,
otherMetadata: {

View file

@ -33,7 +33,7 @@ function breakdownArticleComponent(
for (let i = 0; i < lines.length; i++) {
const line = lines[i];
if (content.length + line.length <= MAX_CHUNK_SIZE) {
content += line + "\n";
content += `${line}\n`;
endLine = i;
} else {
chunks.push({
@ -45,12 +45,12 @@ function breakdownArticleComponent(
},
index: index,
filepath: new URL(
subpath + `#${cleanFragment(article.title)}`,
`${subpath}#${cleanFragment(article.title)}`,
url,
).toString(),
digest: subpath,
});
content = line + "\n";
content = `${line}\n`;
startLine = i;
endLine = i;
index += 1;
@ -68,7 +68,7 @@ function breakdownArticleComponent(
},
index: index,
filepath: new URL(
subpath + `#${cleanFragment(article.title)}`,
`${subpath}#${cleanFragment(article.title)}`,
url,
).toString(),
digest: subpath,

View file

@ -1,4 +1,4 @@
import { URL } from "url";
import { URL } from "node:url";
import { Octokit } from "@octokit/rest";
import cheerio from "cheerio";
import fetch from "node-fetch";
@ -45,7 +45,7 @@ async function crawlGithubRepo(baseUrl: URL) {
const paths = tree.data.tree
.filter((file) => file.type === "blob" && file.path?.endsWith(".md"))
.map((file) => baseUrl.pathname + "/tree/main/" + file.path);
.map((file) => `${baseUrl.pathname}/tree/main/${file.path}`);
return paths;
}
@ -63,13 +63,12 @@ async function getLinksFromUrl(url: string, path: string) {
html: "",
links: [],
};
} else {
console.error(error);
return {
html: "",
links: [],
};
}
console.error(error);
return {
html: "",
links: [],
};
}
const html = await response.text();

View file

@ -128,7 +128,7 @@ export async function addDocs(
// Only after add it to SQLite
const db = await getDBDocs();
await db.run(
`INSERT INTO docs (title, baseUrl) VALUES (?, ?)`,
"INSERT INTO docs (title, baseUrl) VALUES (?, ?)",
title,
baseUrl.toString(),
);
@ -138,12 +138,12 @@ export async function listDocs(): Promise<
{ title: string; baseUrl: string }[]
> {
const db = await getDBDocs();
const docs = db.all(`SELECT title, baseUrl FROM docs`);
const docs = db.all("SELECT title, baseUrl FROM docs");
return docs;
}
export async function hasDoc(baseUrl: string) {
const db = await getDBDocs();
const doc = await db.get(`SELECT title FROM docs WHERE baseUrl =?`, baseUrl);
const doc = await db.get("SELECT title FROM docs WHERE baseUrl =?", baseUrl);
return !!doc;
}

View file

@ -12,7 +12,7 @@ class FreeTrialEmbeddingsProvider extends BaseEmbeddingsProvider {
};
get id(): string {
return FreeTrialEmbeddingsProvider.defaultOptions!.model!;
return FreeTrialEmbeddingsProvider.defaultOptions?.model!;
}
async embed(chunks: string[]) {

View file

@ -15,7 +15,7 @@ async function embedOne(chunk: string, options: EmbedOptions) {
);
const resp = await fetchWithBackoff();
if (!resp.ok) {
throw new Error("Failed to embed chunk: " + (await resp.text()));
throw new Error(`Failed to embed chunk: ${await resp.text()}`);
}
return (await resp.json()).embedding;

View file

@ -4,7 +4,7 @@ import {
pipeline,
} from "../../vendor/node_modules/@xenova/transformers";
import path from "path";
import path from "node:path";
import BaseEmbeddingsProvider from "./BaseEmbeddingsProvider";
env.allowLocalModels = true;
@ -20,11 +20,14 @@ class EmbeddingsPipeline {
static instance: any | null = null;
static async getInstance() {
if (this.instance === null) {
this.instance = await pipeline(this.task, this.model);
if (EmbeddingsPipeline.instance === null) {
EmbeddingsPipeline.instance = await pipeline(
EmbeddingsPipeline.task,
EmbeddingsPipeline.model,
);
}
return this.instance;
return EmbeddingsPipeline.instance;
}
}

View file

@ -1,10 +1,10 @@
import path from "path";
import path from "node:path";
import {
env,
pipeline,
} from "../../vendor/node_modules/@xenova/transformers/types/transformers";
import TransformersJsEmbeddingsProvider from "./TransformersJsEmbeddingsProvider";
const { parentPort } = require("worker_threads");
const { parentPort } = require("node:worker_threads");
env.allowLocalModels = true;
env.allowRemoteModels = false;
@ -19,11 +19,14 @@ class EmbeddingsPipeline {
static instance = null;
static async getInstance() {
if (this.instance === null) {
this.instance = await pipeline(this.task, this.model);
if (EmbeddingsPipeline.instance === null) {
EmbeddingsPipeline.instance = await pipeline(
EmbeddingsPipeline.task,
EmbeddingsPipeline.model,
);
}
return this.instance;
return EmbeddingsPipeline.instance;
}
}

View file

@ -132,7 +132,7 @@ export class CodebaseIndexer {
progress:
(completedDirs + completedIndexes / indexesToBuild.length) /
workspaceDirs.length,
desc: "Completed indexing " + codebaseIndex.artifactId,
desc: `Completed indexing ${codebaseIndex.artifactId}`,
};
}
} catch (e) {

View file

@ -1,5 +1,5 @@
import crypto from "crypto";
import * as fs from "fs";
import crypto from "node:crypto";
import * as fs from "node:fs";
import { type Database, open } from "sqlite";
import sqlite3 from "sqlite3";
import type { IndexTag, IndexingProgressUpdate } from "..";
@ -157,7 +157,7 @@ async function getAddRemoveForTag(
switch (resultType) {
case AddRemoveResultType.Add:
await db.run(
`INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)`,
"INSERT INTO tag_catalog (path, cacheKey, lastUpdated, dir, branch, artifactId) VALUES (?, ?, ?, ?, ?, ?)",
path,
cacheKey,
newLastUpdatedTimestamp,
@ -243,7 +243,7 @@ async function getTagsFromGlobalCache(
): Promise<IndexTag[]> {
const db = await SqliteDb.get();
const stmt = await db.prepare(
`SELECT dir, branch, artifactId FROM global_cache WHERE cacheKey = ? AND artifactId = ?`,
"SELECT dir, branch, artifactId FROM global_cache WHERE cacheKey = ? AND artifactId = ?",
);
const rows = await stmt.all(cacheKey, artifactId);
return rows;

View file

@ -282,7 +282,7 @@ function autodetectPromptTemplates(
}
if (editTemplate !== null) {
templates["edit"] = editTemplate;
templates.edit = editTemplate;
}
return templates;

View file

@ -11,7 +11,7 @@ export function constructMessages(history: ChatHistory): ChatMessage[] {
: [{ type: "text", text: historyItem.message.content } as MessagePart];
const ctxItems = historyItem.contextItems.map((ctxItem) => {
return { type: "text", text: ctxItem.content + "\n" } as MessagePart;
return { type: "text", text: `${ctxItem.content}\n` } as MessagePart;
});
content = [...ctxItems, ...content];

View file

@ -32,9 +32,8 @@ function encodingForModel(modelName: string): Encoding {
function countImageTokens(content: MessagePart): number {
if (content.type === "imageUrl") {
return 85;
} else {
throw new Error("Non-image content type");
}
throw new Error("Non-image content type");
}
function countTokens(
@ -49,9 +48,8 @@ function countTokens(
? countImageTokens(part)
: encoding.encode(part.text ?? "", "all", []).length;
}, 0);
} else {
return encoding.encode(content, "all", []).length;
}
return encoding.encode(content, "all", []).length;
}
function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
@ -62,7 +60,7 @@ function flattenMessages(msgs: ChatMessage[]): ChatMessage[] {
flattened.length > 0 &&
flattened[flattened.length - 1].role === msg.role
) {
flattened[flattened.length - 1].content += "\n\n" + (msg.content || "");
flattened[flattened.length - 1].content += `\n\n${msg.content || ""}`;
} else {
flattened.push(msg);
}
@ -76,9 +74,8 @@ export function stripImages(content: MessageContent): string {
.filter((part) => part.type === "text")
.map((part) => part.text)
.join("\n");
} else {
return content;
}
return content;
}
function countChatMessageTokens(
@ -174,10 +171,9 @@ function pruneRawPromptFromBottom(
function summarize(message: MessageContent): string {
if (Array.isArray(message)) {
return stripImages(message).substring(0, 100) + "...";
} else {
return message.substring(0, 100) + "...";
return `${stripImages(message).substring(0, 100)}...`;
}
return `${message.substring(0, 100)}...`;
}
function pruneChatHistory(
@ -276,7 +272,7 @@ function pruneChatHistory(
function compileChatMessages(
modelName: string,
msgs: ChatMessage[] | undefined = undefined,
msgs: ChatMessage[] | undefined,
contextLength: number,
maxTokens: number,
supportsImages: boolean,

View file

@ -20,10 +20,6 @@ class Anthropic extends BaseLLM {
apiBase: "https://api.anthropic.com/v1/",
};
constructor(options: LLMOptions) {
super(options);
}
private _convertArgs(options: CompletionOptions) {
const finalOptions = {
top_k: options.topK,
@ -44,25 +40,23 @@ class Anthropic extends BaseLLM {
.map((message) => {
if (typeof message.content === "string") {
return message;
} else {
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
} else {
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}
}),
};
}
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}),
};
});
return messages;
}

View file

@ -1,6 +1,6 @@
import * as fs from "fs";
import { join as joinPath } from "path";
import { promisify } from "util";
import * as fs from "node:fs";
import { join as joinPath } from "node:path";
import { promisify } from "node:util";
import { BaseLLM } from "..";
import type {
ChatMessage,
@ -64,25 +64,23 @@ class Bedrock extends BaseLLM {
.map((message) => {
if (typeof message.content === "string") {
return message;
} else {
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
} else {
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}
}),
};
}
return {
...message,
content: message.content.map((part) => {
if (part.type === "text") {
return part;
}
return {
type: "image",
source: {
type: "base64",
media_type: "image/jpeg",
data: part.imageUrl?.url.split(",")[1],
},
};
}),
};
});
return messages;
}
@ -139,7 +137,9 @@ class Bedrock extends BaseLLM {
region: this.region,
};
let accessKeyId: string, secretAccessKey: string, sessionToken: string;
let accessKeyId: string;
let secretAccessKey: string;
let sessionToken: string;
try {
const data = await readFile(
@ -156,9 +156,8 @@ class Bedrock extends BaseLLM {
}
return await this.fetch(new URL(`${this.apiBase}${path}`), {
method: "POST",
headers: aws4.sign(opts, { accessKeyId, secretAccessKey, sessionToken })[
"headers"
],
headers: aws4.sign(opts, { accessKeyId, secretAccessKey, sessionToken })
.headers,
body: body,
});
}

View file

@ -92,7 +92,7 @@ class Flowise extends BaseLLM {
};
if (this.apiKey) {
headers["Authorization"] = `Bearer ${this.apiKey}`;
headers.Authorization = `Bearer ${this.apiKey}`;
}
for (const additionalHeader of this.additionalHeaders) {

View file

@ -33,7 +33,7 @@ class Gemini extends BaseLLM {
const msgs = [...messages];
if (msgs[0]?.role === "system") {
const sysMsg = msgs.shift()!.content;
const sysMsg = msgs.shift()?.content;
// @ts-ignore
if (msgs[0]?.role === "user") {
msgs[0].content = `System message - follow these instructions in every response: ${sysMsg}\n\n---\n\n${msgs[0].content}`;
@ -139,7 +139,7 @@ class Gemini extends BaseLLM {
const wordsToYield = Math.min(3, words.length);
yield {
role: "assistant",
content: words.splice(0, wordsToYield).join(" ") + " ",
content: `${words.splice(0, wordsToYield).join(" ")} `,
};
await delay(delaySeconds);
}

View file

@ -173,9 +173,9 @@ class Ollama extends BaseLLM {
try {
const j = JSON.parse(chunk);
if ("response" in j) {
yield j["response"];
yield j.response;
} else if ("error" in j) {
throw new Error(j["error"]);
throw new Error(j.error);
}
} catch (e) {
throw new Error(`Error parsing Ollama response: ${e} ${chunk}`);

View file

@ -120,15 +120,14 @@ class OpenAI extends BaseLLM {
`openai/deployments/${this.engine}/${endpoint}?api-version=${this.apiVersion}`,
this.apiBase,
);
} else {
if (!this.apiBase) {
throw new Error(
"No API base URL provided. Please set the 'apiBase' option in config.json",
);
}
return new URL(endpoint, this.apiBase);
}
if (!this.apiBase) {
throw new Error(
"No API base URL provided. Please set the 'apiBase' option in config.json",
);
}
return new URL(endpoint, this.apiBase);
}
protected async *_streamComplete(
@ -149,7 +148,7 @@ class OpenAI extends BaseLLM {
): AsyncGenerator<string> {
const args: any = this._convertArgs(options, []);
args.prompt = prompt;
delete args.messages;
args.messages = undefined;
const response = await this.fetch(this._getEndpoint("completions"), {
method: "POST",

View file

@ -49,7 +49,7 @@ const getHandlebarsVars = (
const letter = convertToLetter(keyIndex);
keysToFilepath[letter] = (ast.body[i] as any).path.original;
value = value.replace(
new RegExp("{{\\s*" + (ast.body[i] as any).path.original + "\\s*}}"),
new RegExp(`{{\\s*${(ast.body[i] as any).path.original}\\s*}}`),
`{{${letter}}}`,
);
keyIndex++;

View file

@ -6,7 +6,7 @@ export async function* streamResponse(
}
if (!response.body) {
throw new Error(`No response body returned.`);
throw new Error("No response body returned.");
}
const stream = response.body as any;
@ -38,9 +38,11 @@ function parseDataLine(line: string): any {
function parseSseLine(line: string): { done: boolean; data: any } {
if (line.startsWith("data: [DONE]")) {
return { done: true, data: undefined };
} else if (line.startsWith("data:")) {
}
if (line.startsWith("data:")) {
return { done: false, data: parseDataLine(line) };
} else if (line.startsWith(": ping")) {
}
if (line.startsWith(": ping")) {
return { done: true, data: undefined };
}
return { done: false, data: undefined };
@ -51,7 +53,7 @@ export async function* streamSse(response: Response): AsyncGenerator<any> {
for await (const value of streamResponse(response)) {
buffer += value;
let position;
let position: number;
while ((position = buffer.indexOf("\n")) >= 0) {
const line = buffer.slice(0, position);
buffer = buffer.slice(position + 1);

View file

@ -166,7 +166,7 @@ function deepseekTemplateMessages(msgs: ChatMessage[]): string {
prompt += msg.role === "user" ? "### Instruction:\n" : "### Response:\n";
if (system && msg.role === "user" && i === msgs.length - 1) {
prompt += system + "\n";
prompt += `${system}\n`;
}
prompt += `${msg.content}`;

View file

@ -1,4 +1,4 @@
import { writeFileSync } from "fs";
import { writeFileSync } from "node:fs";
import { getDevDataFilePath } from "./paths";
export function logDevData(tableName: string, data: any) {

View file

@ -1,4 +1,4 @@
import fs from "fs";
import fs from "node:fs";
import type { DatabaseConnection } from "../indexing/refreshIndex";
import { getDevDataSqlitePath } from "./paths";
@ -24,7 +24,7 @@ export class DevDataSqliteDb {
) {
const db = await DevDataSqliteDb.get();
await db?.run(
`INSERT INTO tokens_generated (model, provider, tokens_generated) VALUES (?, ?, ?)`,
"INSERT INTO tokens_generated (model, provider, tokens_generated) VALUES (?, ?, ?)",
[model, provider, tokens],
);
}

View file

@ -1,5 +1,5 @@
import * as fs from "fs";
import tls from "tls";
import * as fs from "node:fs";
import tls from "node:tls";
import { http, https } from "follow-redirects";
import { HttpProxyAgent } from "http-proxy-agent";
import { HttpsProxyAgent } from "https-proxy-agent";

View file

@ -1,4 +1,4 @@
import * as fs from "fs";
import * as fs from "node:fs";
import type {
ContinueRcJson,
IDE,

View file

@ -1,4 +1,4 @@
import * as fs from "fs";
import * as fs from "node:fs";
import type { PersistedSessionInfo, SessionInfo } from "..";
import { getSessionFilePath, getSessionsListPath } from "./paths";
@ -116,11 +116,10 @@ class HistoryManager {
throw new Error(
`It looks like there is a JSON formatting error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session.`,
);
} else {
throw new Error(
`It looks like there is a validation error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session. Error: ${error}`,
);
}
throw new Error(
`It looks like there is a validation error in your sessions.json file (${sessionsListFilePath}). Please fix this before creating a new session. Error: ${error}`,
);
}
}
}

View file

@ -72,7 +72,7 @@ export function dedentAndGetCommonWhitespace(s: string): [string, string] {
// Iterate through the leading whitespace characters of the current line
for (let j = 0; j < lcp.length; j++) {
// If it doesn't have the same whitespace as lcp, then update lcp
if (j >= lines[i].length || lcp[j] != lines[i][j]) {
if (j >= lines[i].length || lcp[j] !== lines[i][j]) {
lcp = lcp.slice(0, j);
if (lcp === "") {
return [s, ""];

View file

@ -11,7 +11,7 @@ export function mergeJson(
const copyOfFirst = JSON.parse(JSON.stringify(first));
try {
for (var key in second) {
for (const key in second) {
const secondValue = second[key];
if (!(key in copyOfFirst) || mergeBehavior === "overwrite") {

View file

@ -1,6 +1,6 @@
import * as fs from "fs";
import * as os from "os";
import * as path from "path";
import * as fs from "node:fs";
import * as os from "node:os";
import * as path from "node:path";
import dotenv from "dotenv";
import type { IdeType, SerializedContinueConfig } from "..";
import { defaultConfig, defaultConfigJetBrains } from "../config/default";
@ -143,7 +143,7 @@ export function getDevDataSqlitePath(): string {
}
export function getDevDataFilePath(fileName: string): string {
return path.join(devDataPath(), fileName + ".jsonl");
return path.join(devDataPath(), `${fileName}.jsonl`);
}
export function editConfigJson(
@ -220,9 +220,8 @@ export function getContinueDotEnv(): { [key: string]: string } {
const filepath = path.join(getContinueGlobalPath(), ".env");
if (fs.existsSync(filepath)) {
return dotenv.parse(fs.readFileSync(filepath));
} else {
return {};
}
return {};
}
export function getCoreLogsPath(): string {

View file

@ -1,4 +1,4 @@
import os from "os";
import os from "node:os";
export class Telemetry {
// Set to undefined whenever telemetry is disabled

View file

@ -1,4 +1,4 @@
import * as path from "path";
import * as path from "node:path";
import type { Language } from "web-tree-sitter";
const Parser = require("web-tree-sitter");

View file

@ -1,15 +0,0 @@
{
"$schema": "https://biomejs.dev/schemas/1.6.4/schema.json",
"organizeImports": {
"enabled": true
},
"linter": {
"enabled": true,
"rules": {
"recommended": true
}
},
"formatter": {
"indentStyle": "space"
}
}