Merge pull request #2028 from continuedev/pe/core-test-colocation

test: colocate tests in `core`
This commit is contained in:
Patrick Erichsen 2024-08-16 17:46:35 -07:00 • committed by GitHub
commit d99823ebbd
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
52 changed files with 981 additions and 1113 deletions

92
.github/workflows/dev_pr.yaml vendored Normal file
View file

@ -0,0 +1,92 @@
name: Dev PR checks
on:
pull_request:
branches:
- dev
jobs:
tsc-check:
runs-on: ubuntu-latest
steps:
# 1. Check-out repository
- name: Check-out repository
uses: actions/checkout@v4
# 2. Install npm dependencies
- name: Use Node.js from .nvmrc
uses: actions/setup-node@v4
with:
node-version-file: ".nvmrc"
- name: Cache extension node_modules
uses: actions/cache@v3
with:
path: extensions/vscode/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('extensions/vscode/package-lock.json') }}
- name: Cache core node_modules
uses: actions/cache@v3
with:
path: core/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('core/package-lock.json') }}
- name: Cache gui node_modules
uses: actions/cache@v3
with:
path: gui/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('gui/package-lock.json') }}
- name: Cache binary node_modules
uses: actions/cache@v3
with:
path: binary/node_modules
key: ${{ runner.os }}-node-${{ hashFiles('binary/package-lock.json') }}
- name: extensions/vscode install
run: |
cd extensions/vscode
npm ci
env:
# https://github.com/microsoft/vscode-ripgrep/issues/9#issuecomment-643965333
GITHUB_TOKEN: ${{ secrets.CI_GITHUB_TOKEN }}
- name: core install
run: |
cd core
npm ci
- name: gui install
run: |
cd gui
npm ci
- name: binary install
run: |
cd binary
npm ci
- name: extensions/vscode checks
run: |
cd extensions/vscode
npx tsc --noEmit
- name: core checks
run: |
cd core
npm ci
npx tsc --noEmit
npm run lint
env:
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
- name: gui checks
run: |
cd gui
npx tsc --noEmit
- name: binary checks
run: |
cd binary
npx tsc --noEmit

View file

@ -5,7 +5,6 @@ on:
branches:
- main
- preview
- dev
jobs:
tsc-check:

View file

@ -1,138 +1,160 @@
import { jest } from "@jest/globals";
import * as charStream from "./charStream";
import { Typescript } from "./languages";
import { stopAtStopTokens } from "./charStream";
describe("charStream", () => {
let mockFullStop: jest.Mock;
async function getCharGenerator(chars: string[]) {
return (async function* () {
for (const char of chars) {
yield char;
}
})();
describe("stopAtStopTokens", () => {
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
for (const chunk of chunks) {
yield chunk;
}
}
async function getFilteredChars(results: AsyncGenerator<string>) {
it("should yield characters until a stop token is encountered", async () => {
const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]);
const stopTokens = ["Stop"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of results) {
for await (const char of result) {
output.push(char);
}
return output;
}
beforeEach(() => {
mockFullStop = jest.fn();
expect(output.join("")).toBe("Hello world! ");
});
describe("onlyWhitespaceAfterEndOfLine", () => {
const endOfLineChar = Typescript.endOfLine[0];
it("should handle multiple stop tokens", async () => {
const mockStream = createMockStream([
"This",
" is a ",
"test. END",
" of stream",
]);
const stopTokens = ["END", "STOP", "HALT"];
const result = stopAtStopTokens(mockStream, stopTokens);
it("should stop at end of line if non-whitespace follows", async () => {
const charGenerator = await getCharGenerator([
`Hello${endOfLineChar}World`,
]);
const output = [];
for await (const char of result) {
output.push(char);
}
const result = charStream.onlyWhitespaceAfterEndOfLine(
charGenerator,
[endOfLineChar],
mockFullStop,
);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe(`Hello${endOfLineChar}`);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
it("should continue past end of line if only whitespace follows", async () => {
const charGenerator = await getCharGenerator([
`Hello${endOfLineChar} World`,
]);
const result = charStream.onlyWhitespaceAfterEndOfLine(
charGenerator,
[endOfLineChar],
mockFullStop,
);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe(`Hello${endOfLineChar} World`);
expect(mockFullStop).not.toHaveBeenCalled();
});
it("should handle end of line at the end of chunk", async () => {
const charGenerator = await getCharGenerator([
`Hello${endOfLineChar}`,
"World",
]);
const result = charStream.onlyWhitespaceAfterEndOfLine(
charGenerator,
[endOfLineChar],
mockFullStop,
);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe(`Hello${endOfLineChar}`);
expect(mockFullStop).toHaveBeenCalledTimes(1);
});
expect(output.join("")).toBe("This is a test. ");
});
describe("noFirstCharNewline", () => {
it("should remove leading newline", async () => {
const charGenerator = await getCharGenerator(["\nHello"]);
const result = charStream.noFirstCharNewline(charGenerator);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe("");
});
it("should handle stop tokens split across chunks", async () => {
const mockStream = createMockStream([
"Hello",
" wo",
"r",
"ld! ST",
"OP now",
]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
it("should keep content if no leading newline", async () => {
const charGenerator = await getCharGenerator(["Hello\nWorld"]);
const result = charStream.noFirstCharNewline(charGenerator);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe("Hello\nWorld");
});
const output = [];
for await (const char of result) {
output.push(char);
}
it("should remove leading carriage return", async () => {
const charGenerator = await getCharGenerator(["\rHello"]);
const result = charStream.noFirstCharNewline(charGenerator);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe("");
});
expect(output.join("")).toBe("Hello world! ");
});
describe("stopAtStopTokens", () => {
it("should stop at the first occurrence of a stop token", async () => {
const charGenerator = await getCharGenerator(["Hello<|endoftext|>World"]);
const result = charStream.stopAtStopTokens(charGenerator, [
"<|endoftext|>",
]);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe("Hello");
});
it("should yield all characters if no stop token is encountered", async () => {
const mockStream = createMockStream([
"This",
" is ",
"a complete",
" stream",
]);
const stopTokens = ["END"];
const result = stopAtStopTokens(mockStream, stopTokens);
it("should return all content if no stop tokens are provided", async () => {
const charGenerator = await getCharGenerator(["Hello<|endoftext|>World"]);
const result = charStream.stopAtStopTokens(charGenerator, []);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe("Hello<|endoftext|>World");
});
const output = [];
for await (const char of result) {
output.push(char);
}
it("should handle stop tokens that span multiple chunks", async () => {
const charGenerator = await getCharGenerator([
"Hello<|",
"endoftext|>World",
]);
const result = charStream.stopAtStopTokens(charGenerator, [
"<|endoftext|>",
]);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe("Hello");
});
expect(output.join("")).toBe("This is a complete stream");
});
it("should yield remaining characters in buffer if no stop token is found", async () => {
const charGenerator = await getCharGenerator(["Hello", "World"]);
const result = charStream.stopAtStopTokens(charGenerator, [
"<|endoftext|>",
]);
const filteredChars = await getFilteredChars(result);
expect(filteredChars.join("")).toBe("HelloWorld");
});
it("should handle empty chunks", async () => {
const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world! ");
});
it("should handle stop token at the beginning of the stream", async () => {
const mockStream = createMockStream(["STOP", "Hello world"]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("");
});
it("should handle stop token at the end of the stream", async () => {
const mockStream = createMockStream(["Hello world", "STOP"]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world");
});
it("should handle multiple stop tokens of different lengths", async () => {
const mockStream = createMockStream([
"This is a ",
"test with ",
"multiple STOP",
" tokens END",
]);
const stopTokens = ["STOP", "END", "HALT"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a test with multiple ");
});
it("should handle an empty stream", async () => {
const mockStream = createMockStream([]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("");
});
it("should handle an empty stop tokens array", async () => {
const mockStream = createMockStream(["Hello", " world!"]);
const stopTokens: string[] = [];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world!");
});
});

View file

@ -1,5 +1,5 @@
import { BranchAndDir, Chunk } from "../index.js";
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearch.js";
import { FullTextSearchCodebaseIndex } from "../indexing/FullTextSearchCodebaseIndex.js";
export async function fullTextRetrieve(
prefix: string,

View file

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { IDE, SlashCommand } from "../..";
import * as fs from "fs/promises";
import * as path from "path";

View file

@ -1,11 +1,11 @@
import fs from "node:fs";
import path from "node:path";
import { defaultConfig } from "../../config/default";
import { getConfigTsPath } from "../../util/paths";
import { testConfigHandler } from "../fixtures";
import { TEST_DIR } from "../testUtils/testDir";
import { defaultConfig } from "./default";
import { getConfigTsPath } from "../util/paths";
import { testConfigHandler } from "../test/util/fixtures";
import { TEST_DIR } from "../test/util/testDir";
describe("Test the ConfigHandler and E2E config loading", () => {
describe.skip("Test the ConfigHandler and E2E config loading", () => {
test("should show only local profile", () => {
const profiles = testConfigHandler.listProfiles();
expect(profiles.length).toBe(1);

View file

@ -1,5 +1,5 @@
import { BranchAndDir, Chunk } from "../../index.js";
import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearch.js";
import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearchCodebaseIndex.js";
export async function retrieveFts(
query: string,

View file

@ -1,14 +1,13 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { CodeSnippetsCodebaseIndex } from "../../indexing/CodeSnippetsIndex";
import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex";
import { IndexResultType } from "../../indexing/types";
import { testIde } from "../fixtures";
import { jest } from "@jest/globals";
import { testIde } from "../test/util/fixtures";
import {
insertMockChunks,
mockPathAndCacheKey,
updateIndexAndAwaitGenerator,
} from "./utils";
import { jest } from "@jest/globals";
mockPathAndCacheKey,
} from "../test/util/indexing";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
describe("CodeSnippetsCodebaseIndex", () => {
let index: CodeSnippetsCodebaseIndex;

View file

@ -2,20 +2,20 @@ import { jest } from "@jest/globals";
import { execSync } from "node:child_process";
import fs from "node:fs";
import path from "node:path";
import { ContinueServerClient } from "../../continueServer/stubs/client.js";
import { CodebaseIndexer, PauseToken } from "../../indexing/CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "../../indexing/refreshIndex.js";
import { TestCodebaseIndex } from "../../indexing/TestCodebaseIndex.js";
import { CodebaseIndex } from "../../indexing/types.js";
import { walkDir } from "../../indexing/walkDir.js";
import { getIndexSqlitePath } from "../../util/paths.js";
import { testConfigHandler, testIde } from "../fixtures.js";
import { ContinueServerClient } from "../continueServer/stubs/client.js";
import { CodebaseIndexer, PauseToken } from "./CodebaseIndexer.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import { TestCodebaseIndex } from "./TestCodebaseIndex.js";
import { CodebaseIndex } from "./types.js";
import { walkDir } from "./walkDir.js";
import { getIndexSqlitePath } from "../util/paths.js";
import { testConfigHandler, testIde } from "../test/util/fixtures.js";
import {
addToTestDir,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "../testUtils/testDir.js";
} from "../test/util/testDir.js";
jest.useFakeTimers();
@ -57,7 +57,7 @@ class TestCodebaseIndexer extends CodebaseIndexer {
// These are more like integration tests, whereas we should separately test
// the individual CodebaseIndex classes
describe("CodebaseIndexer", () => {
describe.skip("CodebaseIndexer", () => {
const pauseToken = new PauseToken(false);
const continueServerClient = new ContinueServerClient(undefined, undefined);
const codebaseIndexer = new TestCodebaseIndexer(

View file

@ -6,7 +6,7 @@ import { extractMinimalStackTraceInfo } from "../util/extractMinimalStackTraceIn
import { getIndexSqlitePath, getLanceDbPath } from "../util/paths.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { CodeSnippetsCodebaseIndex } from "./CodeSnippetsIndex.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearch.js";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex.js";
import { LanceDbIndex } from "./LanceDbIndex.js";
import { getComputeDeleteAddRemove } from "./refreshIndex.js";
import {

View file

@ -1,13 +1,12 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { FullTextSearchCodebaseIndex } from "../../indexing/FullTextSearch";
import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex";
import { IndexResultType } from "../../indexing/types";
import { jest } from "@jest/globals";
import {
insertMockChunks,
mockPathAndCacheKey,
updateIndexAndAwaitGenerator,
} from "./utils";
import { jest } from "@jest/globals";
mockPathAndCacheKey,
} from "../test/util/indexing";
import { FullTextSearchCodebaseIndex } from "./FullTextSearchCodebaseIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
describe("FullTextSearchCodebaseIndex", () => {
let index: FullTextSearchCodebaseIndex;

View file

@ -1,19 +1,14 @@
import {
BranchAndDir,
Chunk,
IndexTag,
IndexingProgressUpdate,
} from "../index.js";
import { getBasename } from "../util/index.js";
import { RETRIEVAL_PARAMS } from "../util/parameters.js";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex.js";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex.js";
import { BranchAndDir, Chunk, IndexTag, IndexingProgressUpdate } from "../";
import { getBasename } from "../util/index";
import { RETRIEVAL_PARAMS } from "../util/parameters";
import { ChunkCodebaseIndex } from "./chunk/ChunkCodebaseIndex";
import { DatabaseConnection, SqliteDb, tagToString } from "./refreshIndex";
import {
IndexResultType,
MarkCompleteCallback,
RefreshIndexResults,
type CodebaseIndex,
} from "./types.js";
} from "./types";
export class FullTextSearchCodebaseIndex implements CodebaseIndex {
relativeExpectedTime: number = 0.2;

View file

@ -1,17 +1,16 @@
import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex";
import { IndexResultType } from "../../indexing/types";
import { testIde } from "../fixtures";
import { jest } from "@jest/globals";
import {
mockPathAndCacheKey,
mockTag,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "./utils";
import { LanceDbIndex } from "../../indexing/LanceDbIndex";
import { testConfigHandler } from "../fixtures";
import lance from "vectordb";
import { getLanceDbPath } from "../../util/paths";
import { testIde, testConfigHandler } from "../test/util/fixtures";
import {
testContinueServerClient,
mockTag,
updateIndexAndAwaitGenerator,
mockPathAndCacheKey,
} from "../test/util/indexing";
import { getLanceDbPath } from "../util/paths";
import { LanceDbIndex } from "./LanceDbIndex";
import { DatabaseConnection, SqliteDb } from "./refreshIndex";
import { IndexResultType } from "./types";
jest.useFakeTimers();

View file

@ -1,8 +1,8 @@
import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex";
import { DatabaseConnection, SqliteDb } from "../../indexing/refreshIndex";
import { IndexResultType } from "../../indexing/types";
import { testIde } from "../fixtures";
import { addToTestDir } from "../testUtils/testDir";
import { ChunkCodebaseIndex } from "./ChunkCodebaseIndex";
import { DatabaseConnection, SqliteDb } from "../refreshIndex";
import { IndexResultType } from "../types";
import { testIde } from "../../test/util/fixtures";
import { addToTestDir } from "../../test/util/testDir";
import { jest } from "@jest/globals";
import {
mockFileContents,
@ -10,7 +10,7 @@ import {
mockPathAndCacheKey,
testContinueServerClient,
updateIndexAndAwaitGenerator,
} from "./utils";
} from "../../test/util/indexing";
jest.useFakeTimers();

View file

@ -1,5 +1,5 @@
import path from "path";
import { shouldChunk } from "../../../indexing/chunk/chunk";
import { shouldChunk } from "./chunk";
describe("shouldChunk", () => {
test("should chunk a typescript file", () => {

View file

@ -1,5 +1,5 @@
import { ChunkWithoutID } from "../../../index.js";
import { codeChunker } from "../../../indexing/chunk/code.js";
import { ChunkWithoutID } from "../..";
import { codeChunker } from "./code";
async function genToArr<T>(generator: AsyncGenerator<T>): Promise<T[]> {
const result: T[] = [];

View file

@ -1,16 +1,14 @@
/**
* @jest-environment jsdom
*/
import * as fs from "fs";
import * as path from "path";
import { ConfigHandler } from "../../config/ConfigHandler.js";
import { ControlPlaneClient } from "../../control-plane/client.js";
import { SiteIndexingConfig } from "../../index.js";
import DocsService from "../../indexing/docs/DocsService.js";
import preIndexedDocs from "../../indexing/docs/preIndexedDocs.js";
import FreeTrialEmbeddingsProvider from "../../indexing/embeddings/FreeTrialEmbeddingsProvider.js";
import DocsService from "./DocsService.js";
import preIndexedDocs from "./preIndexedDocs.js";
import FreeTrialEmbeddingsProvider from "../embeddings/FreeTrialEmbeddingsProvider.js";
import FileSystemIde from "../../util/filesystem.js";
import { editConfigJson, getConfigJsonPath } from "../../util/paths.js";
import { editConfigJson } from "../../util/paths.js";
describe.skip("DocsService Integration Tests", () => {
let ide: FileSystemIde;
@ -23,13 +21,6 @@ describe.skip("DocsService Integration Tests", () => {
faviconUrl: "https://github.com/favicon.ico",
};
async function clearConfigDir() {
const configFolder = path.dirname(getConfigJsonPath());
if (fs.existsSync(configFolder)) {
fs.rmSync(configFolder, { recursive: true, force: true });
}
}
/**
* We need to reload config explicitly to handle the scenario where the
* config file update listeners are not called before we attempt to
@ -43,8 +34,6 @@ describe.skip("DocsService Integration Tests", () => {
}
beforeEach(async () => {
await clearConfigDir();
ide = new FileSystemIde(process.cwd());
configHandler = new ConfigHandler(
@ -75,10 +64,6 @@ describe.skip("DocsService Integration Tests", () => {
await docsService.isInitialized;
});
afterAll(async () => {
await clearConfigDir();
});
test("Indexing, retrieval, and deletion of a new documentation site", async () => {
const generator = docsService.indexAndAdd(mockSiteConfig);
while (!(await generator.next()).done) {}

View file

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import { SiteIndexingConfig } from "../../index.js";
const preIndexedDocs: Record<

View file

@ -37,9 +37,7 @@ class GeminiEmbeddingsProvider extends BaseEmbeddingsProvider {
requests,
}),
headers: {
// eslint-disable-next-line @typescript-eslint/naming-convention
"x-goog-api-key": this.options.apiKey,
// eslint-disable-next-line @typescript-eslint/naming-convention
"Content-Type": "application/json",
},
}),

View file

@ -19,13 +19,10 @@ export const allEmbeddingsProviders: Record<
EmbeddingsProviderConstructor
> = {
ollama: OllamaEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"transformers.js": TransformersJsEmbeddingsProvider,
openai: OpenAIEmbeddingsProvider,
cohere: CohereEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"free-trial": FreeTrialEmbeddingsProvider,
// eslint-disable-next-line @typescript-eslint/naming-convention
"huggingface-tei": HuggingFaceTEIEmbeddingsProvider,
gemini: GeminiEmbeddingsProvider,
"continue-proxy": ContinueProxyEmbeddingsProvider,

View file

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import crypto from "node:crypto";
import * as fs from "node:fs";
import { open, type Database } from "sqlite";

View file

@ -1,13 +1,12 @@
import path from "path";
import ignore, { Ignore } from "ignore";
import { walkDir, walkDirAsync, WalkerOptions } from "../indexing/walkDir.js";
import FileSystemIde from "../util/filesystem.js";
import { walkDir, WalkerOptions } from "../indexing/walkDir";
import FileSystemIde from "../util/filesystem";
import {
addToTestDir,
TEST_DIR,
setUpTestDir,
tearDownTestDir,
TEST_DIR,
} from "./testUtils/testDir.js";
addToTestDir,
} from "../test/util/testDir";
const ide = new FileSystemIde(TEST_DIR);

View file

@ -1,4 +1,3 @@
/* eslint-disable @typescript-eslint/naming-convention */
import path from "path";
import { fileURLToPath } from "url";

View file

@ -0,0 +1,45 @@
import { LlamaAsyncEncoder, GPTAsyncEncoder } from "./asyncEncoder";
describe("llama encoder", () => {
var tokenizer: LlamaAsyncEncoder;
beforeAll(() => {
tokenizer = new LlamaAsyncEncoder();
});
afterAll(() => {
tokenizer.close();
});
test("hello world", async () => {
const input = "the quick brown fox jumped over the lazy dog";
const output = await tokenizer.encode(input);
expect(output).toEqual([
1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203,
]);
const decoded = await tokenizer.decode(output);
expect(decoded).toBe(input);
});
});
describe("tiktoken encoder", () => {
var tokenizer: GPTAsyncEncoder;
beforeAll(() => {
tokenizer = new GPTAsyncEncoder();
});
afterAll(() => {
tokenizer.close();
});
test("hello world", async () => {
const input = "the quick brown fox jumped over the lazy dog";
const output = await tokenizer.encode(input);
expect(output).toEqual([
1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679,
]);
const decoded = await tokenizer.decode(output);
expect(decoded).toBe(input);
});
});

View file

@ -1,5 +1,4 @@
import llamaTokenizer from "./llamaTokenizer.js";
import { Tiktoken, encodingForModel as _encodingForModel } from "js-tiktoken";
import { encodingForModel as _encodingForModel } from "js-tiktoken";
import workerpool from "workerpool";
import * as path from "path";
@ -13,7 +12,9 @@ export class LlamaAsyncEncoder implements AsyncEncoder {
private workerPool: workerpool.Pool;
constructor() {
this.workerPool = workerpool.pool(workerCodeFilePath("llamaTokenizerWorkerPool.mjs"));
this.workerPool = workerpool.pool(
workerCodeFilePath("llamaTokenizerWorkerPool.mjs"),
);
}
async encode(text: string): Promise<number[]> {
@ -35,7 +36,9 @@ export class GPTAsyncEncoder implements AsyncEncoder {
private workerPool: workerpool.Pool;
constructor() {
this.workerPool = workerpool.pool(workerCodeFilePath("tiktokenWorkerPool.mjs"));
this.workerPool = workerpool.pool(
workerCodeFilePath("tiktokenWorkerPool.mjs"),
);
}
async encode(text: string): Promise<number[]> {
@ -58,4 +61,4 @@ function workerCodeFilePath(workerFileName: string): string {
return path.join(__dirname, "llm", workerFileName);
}
return path.join(__dirname, workerFileName);
}
}

View file

@ -1,5 +1,5 @@
import { ChatMessage, LLMOptions, ModelProvider } from "../index.js";
import { BaseLLM } from "../llm/index.js";
import { ChatMessage, LLMOptions, ModelProvider } from "..";
import { BaseLLM } from ".";
class DummyLLM extends BaseLLM {
static providerName: ModelProvider = "openai";

View file

@ -19,7 +19,10 @@ class WatsonX extends BaseLLM {
super(options);
}
async getBearerToken(): Promise<{ token: string; expiration: number }> {
if (this.watsonxUrl !== null && this.watsonxUrl.includes("cloud.ibm.com")) {
if (
this.watsonxUrl !== null &&
this.watsonxUrl!.includes("cloud.ibm.com")
) {
// watsonx SaaS
const wxToken = await (
await fetch(

View file

@ -3,7 +3,7 @@
"version": "1.0.13",
"description": "The Continue Core contains functionality that can be shared across web, VS Code, or Node.js",
"scripts": {
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand",
"test": "cross-env NODE_OPTIONS=--experimental-vm-modules jest --runInBand --silent",
"build:npm": "tsc -p ./tsconfig.npm.json",
"lint": "eslint . --ext ts",
"lint:fix": "eslint . --ext ts --fix"

View file

@ -1,6 +1,5 @@
/* eslint-disable @typescript-eslint/naming-convention */
import type { AutocompleteInput } from "../autocomplete/completionProvider.js";
import { ProfileDescription } from "../config/ConfigHandler.js";
import type { AutocompleteInput } from "../autocomplete/completionProvider";
import { ProfileDescription } from "../config/ConfigHandler";
import type {
BrowserSerializedContinueConfig,
ChatMessage,
@ -16,7 +15,7 @@ import type {
SerializedContinueConfig,
SessionInfo,
SiteIndexingConfig,
} from "../index.js";
} from "../";
export type ProtocolGeneratorType<T> = AsyncGenerator<{
done?: boolean;

View file

@ -8,7 +8,7 @@ import { ConfigHandler } from "../../../config/ConfigHandler";
import { contextProviderClassFromName } from "../../../context/providers";
import { ControlPlaneClient } from "../../../control-plane/client";
import FileSystemIde from "../../../util/filesystem";
import { TEST_DIR } from "../../testUtils/testDir";
import { TEST_DIR } from "../../util/testDir";
const CONTEXT_PROVIDERS_TO_TEST: ContextProviderWithParams[] = [
{ name: "diff", params: {} },
@ -46,7 +46,7 @@ async function getContextProviderExtras(
};
}
describe("Should successfully run all context providers", () => {
describe.skip("Should successfully run all context providers", () => {
const extrasPromise = getContextProviderExtras("Test");
CONTEXT_PROVIDERS_TO_TEST.forEach((provider) => {

View file

@ -1,24 +0,0 @@
import { IRetrievalPipeline } from "../../../context/retrieval/pipelines/BaseRetrievalPipeline.js";
function testRetrievalPipeline(pipeline: IRetrievalPipeline) {
test("should successfully run");
}
describe.skip("RetrievalPipeline", () => {
test.todo("should successfully run");
});
// describe("Retrieval Pipelines", () => {
// const ide = new FileSystemIde();
// const options: RetrievalPipelineOptions;
// test("NoRerankerRetrievalPipeline", () => {
// const pipeline = new NoRerankerRetrievalPipeline(options);
// testRetrievalPipeline(pipeline);
// });
// test("NoRerankerRetrievalPipeline", () => {
// const pipeline = new NoRerankerRetrievalPipeline(options);
// testRetrievalPipeline(pipeline);
// });
// });

View file

@ -1,8 +1,8 @@
import * as dotenv from "dotenv";
import { CompletionOptions } from "../index.js";
import { BaseLLM } from "../llm/index.js";
import OpenAI from "../llm/llms/OpenAI.js";
import { CompletionOptions } from "../";
import { BaseLLM } from "../llm/";
import OpenAI from "../llm/llms/OpenAI";
// jest.setTimeout(100_000);

View file

@ -1,41 +0,0 @@
import { GPTAsyncEncoder, LlamaAsyncEncoder } from "../../llm/asyncEncoder";
describe("llama encoder", () => {
var tokenizer: LlamaAsyncEncoder;
beforeAll(() => {
tokenizer = new LlamaAsyncEncoder();
});
afterAll(() => {
tokenizer.close();
});
test("hello world", async () => {
const input = "the quick brown fox jumped over the lazy dog";
const output = await tokenizer.encode(input);
expect(output).toEqual([1, 278, 4996, 17354, 1701, 29916, 12500, 287, 975, 278, 17366, 11203]);
const decoded = await tokenizer.decode(output);
expect(decoded).toBe(input);
});
});
describe("tiktoken encoder", () => {
var tokenizer: GPTAsyncEncoder;
beforeAll(() => {
tokenizer = new GPTAsyncEncoder();
});
afterAll(() => {
tokenizer.close();
});
test("hello world", async () => {
const input = "the quick brown fox jumped over the lazy dog";
const output = await tokenizer.encode(input);
expect(output).toEqual([1820, 4062, 14198, 39935, 27096, 927, 279, 16053, 5679]);
const decoded = await tokenizer.decode(output);
expect(decoded).toBe(input);
});
});

View file

@ -1,160 +0,0 @@
import { stopAtStopTokens } from "../../autocomplete/charStream.js";
describe("stopAtStopTokens", () => {
async function* createMockStream(chunks: string[]): AsyncGenerator<string> {
for (const chunk of chunks) {
yield chunk;
}
}
it("should yield characters until a stop token is encountered", async () => {
const mockStream = createMockStream(["Hello", " world", "! Stop", "here"]);
const stopTokens = ["Stop"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world! ");
});
it("should handle multiple stop tokens", async () => {
const mockStream = createMockStream([
"This",
" is a ",
"test. END",
" of stream",
]);
const stopTokens = ["END", "STOP", "HALT"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a test. ");
});
it("should handle stop tokens split across chunks", async () => {
const mockStream = createMockStream([
"Hello",
" wo",
"r",
"ld! ST",
"OP now",
]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world! ");
});
it("should yield all characters if no stop token is encountered", async () => {
const mockStream = createMockStream([
"This",
" is ",
"a complete",
" stream",
]);
const stopTokens = ["END"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a complete stream");
});
it("should handle empty chunks", async () => {
const mockStream = createMockStream(["Hello", "", " world", "", "! STOP"]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world! ");
});
it("should handle stop token at the beginning of the stream", async () => {
const mockStream = createMockStream(["STOP", "Hello world"]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("");
});
it("should handle stop token at the end of the stream", async () => {
const mockStream = createMockStream(["Hello world", "STOP"]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world");
});
it("should handle multiple stop tokens of different lengths", async () => {
const mockStream = createMockStream([
"This is a ",
"test with ",
"multiple STOP",
" tokens END",
]);
const stopTokens = ["STOP", "END", "HALT"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("This is a test with multiple ");
});
it("should handle an empty stream", async () => {
const mockStream = createMockStream([]);
const stopTokens = ["STOP"];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("");
});
it("should handle an empty stop tokens array", async () => {
const mockStream = createMockStream(["Hello", " world!"]);
const stopTokens: string[] = [];
const result = stopAtStopTokens(mockStream, stopTokens);
const output = [];
for await (const char of result) {
output.push(char);
}
expect(output.join("")).toBe("Hello world!");
});
});

View file

@ -1,76 +0,0 @@
// File generated by Continue
import { dedentAndGetCommonWhitespace } from "../../util/index.js";
describe("dedentAndGetCommonWhitespace", () => {
let originalString: string;
beforeEach(() => {
// Setup any global variables or states if needed
originalString = " line1\n line2\n line3";
});
afterEach(() => {
// Tear down any changes to global variables or states if needed
originalString = "";
});
test("should dedent and return common whitespace for a simple case", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", " "]);
});
test("should handle empty string", () => {
const input = "";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with only whitespace", () => {
const input = " ";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with mixed whitespace and content", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
test("should handle string with no common leading whitespace", () => {
const input = "line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([input, ""]);
});
test("should handle string with empty lines", () => {
const input = " line1\n\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\n\nline3", " "]);
});
test("should handle string with only empty lines", () => {
const input = "\n\n";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["\n\n", ""]);
});
test("should handle string with tabs as whitespace", () => {
const input = "\tline1\n\tline2\n\tline3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t"]);
});
test("should handle string with mixed tabs and spaces", () => {
const input = "\t line1\n\t line2\n\t line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t "]);
});
test("should handle string with different leading whitespace lengths", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
});

View file

@ -1,82 +0,0 @@
import { deduplicateArray } from "../../util/index.js";
describe("deduplicateArray", () => {
it("should return an empty array when given an empty array", () => {
const result = deduplicateArray([], (a, b) => a === b);
expect(result).toEqual([]);
});
it("should return the same array when there are no duplicates", () => {
const input = [1, 2, 3, 4, 5];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual(input);
});
it("should remove duplicates based on the equality function", () => {
const input = [1, 2, 2, 3, 4, 4, 5];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual([1, 2, 3, 4, 5]);
});
it("should work with objects using custom equality function", () => {
const input = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 1, name: "Alice" },
{ id: 3, name: "Charlie" },
];
const result = deduplicateArray(input, (a, b) => a.id === b.id);
expect(result).toEqual([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
]);
});
it("should preserve the order of items", () => {
const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]);
});
it("should work with strings", () => {
const input = ["apple", "banana", "apple", "cherry", "banana", "date"];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual(["apple", "banana", "cherry", "date"]);
});
it("should handle arrays with all duplicate elements", () => {
const input = [1, 1, 1, 1, 1];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual([1]);
});
it("should work with custom equality function for complex objects", () => {
const input = [
{ x: 1, y: 2 },
{ x: 2, y: 1 },
{ x: 1, y: 2 },
{ x: 3, y: 4 },
];
const result = deduplicateArray(
input,
(a, b) => a.x === b.x && a.y === b.y,
);
expect(result).toEqual([
{ x: 1, y: 2 },
{ x: 2, y: 1 },
{ x: 3, y: 4 },
]);
});
it("should handle large arrays efficiently", () => {
const input = Array(10000)
.fill(0)
.map((_, i) => i % 100);
const start = performance.now();
const result = deduplicateArray(input, (a, b) => a === b);
const end = performance.now();
expect(result).toHaveLength(100);
expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second
});
});

View file

@ -1,7 +1,7 @@
import { ConfigHandler } from "../config/ConfigHandler";
import { ControlPlaneClient } from "../control-plane/client";
import FileSystemIde from "../util/filesystem";
import { TEST_DIR } from "./testUtils/testDir";
import { ConfigHandler } from "../../config/ConfigHandler";
import { ControlPlaneClient } from "../../control-plane/client";
import FileSystemIde from "../../util/filesystem";
import { TEST_DIR } from "./testDir";
export const testIde = new FileSystemIde(TEST_DIR);

View file

@ -1,51 +0,0 @@
// File generated by Continue
import { getLastNPathParts } from "../../util/index.js";
describe("getLastNPathParts", () => {
const SEP_REGEX = /[\\/]+/;
beforeAll(() => {
// Setup code if needed
});
afterAll(() => {
// Teardown code if needed
});
test("returns the last N parts of a filepath with forward slashes", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt");
});
test("returns the last N parts of a filepath with backward slashes", () => {
const filepath = "C:\\home\\user\\documents\\project\\file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("returns the last part if N is 1", () => {
const filepath = "/home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 1)).toBe("file.txt");
});
test("returns the entire path if N is greater than the number of parts", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 10)).toBe(
"home/user/documents/project/file.txt",
);
});
test("returns an empty string if N is 0", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 0)).toBe("");
});
test("handles paths with mixed forward and backward slashes", () => {
const filepath = "home\\user/documents\\project/file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("handles edge case with empty filepath", () => {
const filepath = "";
expect(getLastNPathParts(filepath, 2)).toBe("");
});
});

View file

@ -1,7 +1,7 @@
import { ChunkCodebaseIndex } from "../../indexing/chunk/ChunkCodebaseIndex";
import { IContinueServerClient } from "../../continueServer/interface";
import { testIde } from "../fixtures";
import { addToTestDir, TEST_DIR } from "../testUtils/testDir";
import { testIde } from "./fixtures";
import { addToTestDir, TEST_DIR } from "./testDir";
import { IndexTag } from "../..";
import {
CodebaseIndex,

View file

@ -1,40 +0,0 @@
// This file is generated by Continue
import { longestCommonSubsequence } from "../../util/lcs.js";
describe("longestCommonSubsequence", () => {
beforeAll(() => {
// Setup if needed
});
afterAll(() => {
// Teardown if needed
});
test("should return the longest common subsequence for non-empty strings", () => {
expect(longestCommonSubsequence("abcde", "ace")).toBe("ace");
expect(longestCommonSubsequence("abc", "abc")).toBe("abc");
expect(longestCommonSubsequence("abc", "def")).toBe("");
});
test("should handle cases where one or both strings are empty", () => {
expect(longestCommonSubsequence("", "abc")).toBe("");
expect(longestCommonSubsequence("abc", "")).toBe("");
expect(longestCommonSubsequence("", "")).toBe("");
});
test("should handle cases with no common subsequence", () => {
expect(longestCommonSubsequence("abc", "def")).toBe("");
expect(longestCommonSubsequence("xyz", "abc")).toBe("");
});
test("should handle cases with special characters", () => {
expect(longestCommonSubsequence("a!@#b$c", "!@#$")).toBe("!@#$");
expect(longestCommonSubsequence("a!@#b$c", "xyz")).toBe("");
});
test("should handle long strings efficiently", () => {
const str1 = "a".repeat(1000) + "b".repeat(1000);
const str2 = "a".repeat(1000) + "c".repeat(1000);
expect(longestCommonSubsequence(str1, str2)).toBe("a".repeat(1000));
});
});

View file

@ -1,105 +0,0 @@
// This file is generated by Continue
import { getRangeInString } from "../../../util/ranges.js";
describe.skip("getRangeInString", () => {
let content: string;
beforeEach(() => {
content = `Line 1
Line 2
Line 3
Line 4
Line 5`;
});
afterEach(() => {
content = "";
});
test("should return substring within the same line", () => {
const range = {
start: { line: 1, character: 0 },
end: { line: 1, character: 4 },
};
expect(getRangeInString(content, range)).toBe("Line");
});
test("should return substring spanning multiple lines", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 3, character: 3 },
};
const expected = `ne 2
Line 3
Line 4`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle range that starts and ends at the same character", () => {
const range = {
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("L");
});
test("should handle range that spans entire content", () => {
const range = {
start: { line: 0, character: 0 },
end: { line: 4, character: 5 },
};
expect(getRangeInString(content, range)).toBe(content);
});
test("should handle range that spans to the end of the last line", () => {
const range = {
start: { line: 3, character: 2 },
end: { line: 4, character: 5 },
};
const expected = `ne 4
Line 5`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle empty content", () => {
content = "";
const range = {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start line > end line)", () => {
const range = {
start: { line: 3, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start character > end character on same line)", () => {
const range = {
start: { line: 1, character: 5 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle range that starts and ends at the same line but different characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 6 },
};
expect(getRangeInString(content, range)).toBe("ne 2");
});
test("should handle range that starts and ends at the same line and same characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("n");
});
});

View file

@ -1,123 +0,0 @@
// This file is generated by Continue
import { intersection } from "../../../util/ranges.js";
interface Position {
line: number;
character: number;
}
interface Range {
start: Position;
end: Position;
}
describe("intersection", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 4, character: 0 },
};
});
test("returns correct intersection for overlapping ranges", () => {
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 5 },
});
});
test("returns null for non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 3, character: 0 },
end: { line: 4, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
// TODO
test.skip("returns correct intersection for single line overlap", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 2, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
});
});
test("returns null for single line non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 2 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
test("returns correct intersection when one range is fully within another", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 4, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
});
});
test("returns correct intersection when ranges touch at the edge", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 2, character: 0 },
end: { line: 3, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
});
});
});

View file

@ -1,70 +0,0 @@
import { maxPosition, minPosition } from "../../../util/ranges.js";
// This file is generated by Continue
interface Position {
line: number;
character: number;
}
describe("Position comparison functions", () => {
let pos1: Position;
let pos2: Position;
let pos3: Position;
let pos4: Position;
beforeAll(() => {
// Setup: Initializing positions
pos1 = { line: 1, character: 5 };
pos2 = { line: 2, character: 3 };
pos3 = { line: 1, character: 7 };
pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality
});
describe("maxPosition", () => {
it("should return the position with the greater line number", () => {
expect(maxPosition(pos1, pos2)).toEqual(pos2);
});
it("should return the position with the greater character number when lines are equal", () => {
expect(maxPosition(pos1, pos3)).toEqual(pos3);
});
it("should return the first position when both positions are equal", () => {
expect(maxPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(maxPosition(posNegative, pos1)).toEqual(pos1);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1);
});
});
describe("minPosition", () => {
it("should return the position with the lesser line number", () => {
expect(minPosition(pos1, pos2)).toEqual(pos1);
});
it("should return the position with the lesser character number when lines are equal", () => {
expect(minPosition(pos1, pos3)).toEqual(pos1);
});
it("should return the first position when both positions are equal", () => {
expect(minPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(minPosition(posNegative, pos1)).toEqual(posNegative);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar);
});
});
});

View file

@ -1,92 +0,0 @@
import { union } from "../../../util/ranges.js";
// This file is generated by Continue
interface Position {
line: number;
character: number;
}
interface Range {
start: Position;
end: Position;
}
describe("union", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 3 },
end: { line: 4, character: 2 },
};
});
test("should return the union of two overlapping ranges", () => {
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when ranges are identical", () => {
const result = union(rangeA, rangeA);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap but are adjacent", () => {
rangeB = {
start: { line: 3, character: 5 },
end: { line: 4, character: 2 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when one range is completely within the other", () => {
rangeB = {
start: { line: 2, character: 1 },
end: { line: 2, character: 4 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap and are not adjacent", () => {
rangeB = {
start: { line: 4, character: 3 },
end: { line: 5, character: 1 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 5, character: 1 },
});
});
// TODO
test.skip("should handle edge case where start and end lines are the same", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 7 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 1, character: 7 },
});
});
});

200
core/util/index.test.ts Normal file
View file

@ -0,0 +1,200 @@
// File generated by Continue
import {
dedentAndGetCommonWhitespace,
deduplicateArray,
getLastNPathParts,
} from "./";
describe("getLastNPathParts", () => {
test("returns the last N parts of a filepath with forward slashes", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 2)).toBe("project/file.txt");
});
test("returns the last N parts of a filepath with backward slashes", () => {
const filepath = "C:\\home\\user\\documents\\project\\file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("returns the last part if N is 1", () => {
const filepath = "/home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 1)).toBe("file.txt");
});
test("returns the entire path if N is greater than the number of parts", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 10)).toBe(
"home/user/documents/project/file.txt",
);
});
test("returns an empty string if N is 0", () => {
const filepath = "home/user/documents/project/file.txt";
expect(getLastNPathParts(filepath, 0)).toBe("");
});
test("handles paths with mixed forward and backward slashes", () => {
const filepath = "home\\user/documents\\project/file.txt";
expect(getLastNPathParts(filepath, 3)).toBe("documents/project/file.txt");
});
test("handles edge case with empty filepath", () => {
const filepath = "";
expect(getLastNPathParts(filepath, 2)).toBe("");
});
});
describe("deduplicateArray", () => {
it("should return an empty array when given an empty array", () => {
const result = deduplicateArray([], (a, b) => a === b);
expect(result).toEqual([]);
});
it("should return the same array when there are no duplicates", () => {
const input = [1, 2, 3, 4, 5];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual(input);
});
it("should remove duplicates based on the equality function", () => {
const input = [1, 2, 2, 3, 4, 4, 5];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual([1, 2, 3, 4, 5]);
});
it("should work with objects using custom equality function", () => {
const input = [
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 1, name: "Alice" },
{ id: 3, name: "Charlie" },
];
const result = deduplicateArray(input, (a, b) => a.id === b.id);
expect(result).toEqual([
{ id: 1, name: "Alice" },
{ id: 2, name: "Bob" },
{ id: 3, name: "Charlie" },
]);
});
it("should preserve the order of items", () => {
const input = [3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual([3, 1, 4, 5, 9, 2, 6]);
});
it("should work with strings", () => {
const input = ["apple", "banana", "apple", "cherry", "banana", "date"];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual(["apple", "banana", "cherry", "date"]);
});
it("should handle arrays with all duplicate elements", () => {
const input = [1, 1, 1, 1, 1];
const result = deduplicateArray(input, (a, b) => a === b);
expect(result).toEqual([1]);
});
it("should work with custom equality function for complex objects", () => {
const input = [
{ x: 1, y: 2 },
{ x: 2, y: 1 },
{ x: 1, y: 2 },
{ x: 3, y: 4 },
];
const result = deduplicateArray(
input,
(a, b) => a.x === b.x && a.y === b.y,
);
expect(result).toEqual([
{ x: 1, y: 2 },
{ x: 2, y: 1 },
{ x: 3, y: 4 },
]);
});
it("should handle large arrays efficiently", () => {
const input = Array(10000)
.fill(0)
.map((_, i) => i % 100);
const start = performance.now();
const result = deduplicateArray(input, (a, b) => a === b);
const end = performance.now();
expect(result).toHaveLength(100);
expect(end - start).toBeLessThan(1000); // Ensure it completes in less than 1 second
});
});
describe("dedentAndGetCommonWhitespace", () => {
let originalString: string;
beforeEach(() => {
// Setup any global variables or states if needed
originalString = " line1\n line2\n line3";
});
afterEach(() => {
// Tear down any changes to global variables or states if needed
originalString = "";
});
test("should dedent and return common whitespace for a simple case", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", " "]);
});
test("should handle empty string", () => {
const input = "";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with only whitespace", () => {
const input = " ";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["", ""]);
});
test("should handle string with mixed whitespace and content", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
test("should handle string with no common leading whitespace", () => {
const input = "line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([input, ""]);
});
test("should handle string with empty lines", () => {
const input = " line1\n\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\n\nline3", " "]);
});
test("should handle string with only empty lines", () => {
const input = "\n\n";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["\n\n", ""]);
});
test("should handle string with tabs as whitespace", () => {
const input = "\tline1\n\tline2\n\tline3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t"]);
});
test("should handle string with mixed tabs and spaces", () => {
const input = "\t line1\n\t line2\n\t line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual(["line1\nline2\nline3", "\t "]);
});
test("should handle string with different leading whitespace lengths", () => {
const input = " line1\n line2\n line3";
const output = dedentAndGetCommonWhitespace(input);
expect(output).toEqual([" line1\nline2\n line3", " "]);
});
});

31
core/util/lcs.test.ts Normal file
View file

@ -0,0 +1,31 @@
import { longestCommonSubsequence as lcs } from "./lcs";
describe("longestCommonSubsequence", () => {
test("should return the longest common subsequence for non-empty strings", () => {
expect(lcs("abcde", "ace")).toBe("ace");
expect(lcs("abc", "abc")).toBe("abc");
expect(lcs("abc", "def")).toBe("");
});
test("should handle cases where one or both strings are empty", () => {
expect(lcs("", "abc")).toBe("");
expect(lcs("abc", "")).toBe("");
expect(lcs("", "")).toBe("");
});
test("should handle cases with no common subsequence", () => {
expect(lcs("abc", "def")).toBe("");
expect(lcs("xyz", "abc")).toBe("");
});
test("should handle cases with special characters", () => {
expect(lcs("a!@#b$c", "!@#$")).toBe("!@#$");
expect(lcs("a!@#b$c", "xyz")).toBe("");
});
test("should handle long strings efficiently", () => {
const str1 = "a".repeat(1000) + "b".repeat(1000);
const str2 = "a".repeat(1000) + "c".repeat(1000);
expect(lcs(str1, str2)).toBe("a".repeat(1000));
});
});

View file

@ -1,5 +1,6 @@
// File generated by Continue
import { mergeJson } from "../../util/merge.js";
import mergeJson from "./merge";
describe("mergeJson", () => {
it("should merge two simple JSON objects", () => {

374
core/util/ranges.test.ts Normal file
View file

@ -0,0 +1,374 @@
// This file is generated by Continue
import {
intersection,
getRangeInString,
maxPosition,
minPosition,
union,
} from "./ranges";
interface Position {
line: number;
character: number;
}
interface Range {
start: Position;
end: Position;
}
describe("union", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 3 },
end: { line: 4, character: 2 },
};
});
test("should return the union of two overlapping ranges", () => {
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when ranges are identical", () => {
const result = union(rangeA, rangeA);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap but are adjacent", () => {
rangeB = {
start: { line: 3, character: 5 },
end: { line: 4, character: 2 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 4, character: 2 },
});
});
test("should return the union when one range is completely within the other", () => {
rangeB = {
start: { line: 2, character: 1 },
end: { line: 2, character: 4 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual(rangeA);
});
test("should return the union when ranges do not overlap and are not adjacent", () => {
rangeB = {
start: { line: 4, character: 3 },
end: { line: 5, character: 1 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 5, character: 1 },
});
});
// TODO
test.skip("should handle edge case where start and end lines are the same", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 7 },
};
const result = union(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 0 },
end: { line: 1, character: 7 },
});
});
});
describe("Position comparison functions", () => {
let pos1: Position;
let pos2: Position;
let pos3: Position;
let pos4: Position;
beforeAll(() => {
// Setup: Initializing positions
pos1 = { line: 1, character: 5 };
pos2 = { line: 2, character: 3 };
pos3 = { line: 1, character: 7 };
pos4 = { line: 2, character: 3 }; // Same as pos2 to test equality
});
describe("maxPosition", () => {
it("should return the position with the greater line number", () => {
expect(maxPosition(pos1, pos2)).toEqual(pos2);
});
it("should return the position with the greater character number when lines are equal", () => {
expect(maxPosition(pos1, pos3)).toEqual(pos3);
});
it("should return the first position when both positions are equal", () => {
expect(maxPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(maxPosition(posNegative, pos1)).toEqual(pos1);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(maxPosition(posNegativeChar, pos1)).toEqual(pos1);
});
});
describe("minPosition", () => {
it("should return the position with the lesser line number", () => {
expect(minPosition(pos1, pos2)).toEqual(pos1);
});
it("should return the position with the lesser character number when lines are equal", () => {
expect(minPosition(pos1, pos3)).toEqual(pos1);
});
it("should return the first position when both positions are equal", () => {
expect(minPosition(pos2, pos4)).toEqual(pos2);
});
it("should handle positions with negative line numbers", () => {
const posNegative = { line: -1, character: 0 };
expect(minPosition(posNegative, pos1)).toEqual(posNegative);
});
it("should handle positions with negative character numbers", () => {
const posNegativeChar = { line: 1, character: -1 };
expect(minPosition(posNegativeChar, pos1)).toEqual(posNegativeChar);
});
});
});
describe.skip("getRangeInString", () => {
let content: string;
beforeEach(() => {
content = `Line 1
Line 2
Line 3
Line 4
Line 5`;
});
afterEach(() => {
content = "";
});
test("should return substring within the same line", () => {
const range = {
start: { line: 1, character: 0 },
end: { line: 1, character: 4 },
};
expect(getRangeInString(content, range)).toBe("Line");
});
test("should return substring spanning multiple lines", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 3, character: 3 },
};
const expected = `ne 2
Line 3
Line 4`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle range that starts and ends at the same character", () => {
const range = {
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("L");
});
test("should handle range that spans entire content", () => {
const range = {
start: { line: 0, character: 0 },
end: { line: 4, character: 5 },
};
expect(getRangeInString(content, range)).toBe(content);
});
test("should handle range that spans to the end of the last line", () => {
const range = {
start: { line: 3, character: 2 },
end: { line: 4, character: 5 },
};
const expected = `ne 4
Line 5`;
expect(getRangeInString(content, range)).toBe(expected);
});
test("should handle empty content", () => {
content = "";
const range = {
start: { line: 0, character: 0 },
end: { line: 0, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start line > end line)", () => {
const range = {
start: { line: 3, character: 0 },
end: { line: 2, character: 0 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle invalid range (start character > end character on same line)", () => {
const range = {
start: { line: 1, character: 5 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("");
});
test("should handle range that starts and ends at the same line but different characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 6 },
};
expect(getRangeInString(content, range)).toBe("ne 2");
});
test("should handle range that starts and ends at the same line and same characters", () => {
const range = {
start: { line: 1, character: 2 },
end: { line: 1, character: 2 },
};
expect(getRangeInString(content, range)).toBe("n");
});
});
describe("intersection", () => {
let rangeA: Range;
let rangeB: Range;
beforeEach(() => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 3, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 4, character: 0 },
};
});
test("returns correct intersection for overlapping ranges", () => {
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 5 },
});
});
test("returns null for non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 3, character: 0 },
end: { line: 4, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
// TODO
test.skip("returns correct intersection for single line overlap", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 5 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 2, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
});
});
test("returns null for single line non-overlapping ranges", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 1, character: 2 },
};
rangeB = {
start: { line: 1, character: 3 },
end: { line: 1, character: 5 },
};
const result = intersection(rangeA, rangeB);
expect(result).toBeNull();
});
test("returns correct intersection when one range is fully within another", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 4, character: 5 },
};
rangeB = {
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 2 },
end: { line: 3, character: 3 },
});
});
test("returns correct intersection when ranges touch at the edge", () => {
rangeA = {
start: { line: 1, character: 0 },
end: { line: 2, character: 0 },
};
rangeB = {
start: { line: 2, character: 0 },
end: { line: 3, character: 0 },
};
const result = intersection(rangeA, rangeB);
expect(result).toEqual({
start: { line: 2, character: 0 },
end: { line: 2, character: 0 },
});
});
});

View file

@ -6,16 +6,12 @@
"outDir": "out/tsc/src",
"sourceMap": true,
"rootDir": "../../",
"strict": true /* enable all strict type-checking options */,
/* Additional Checks */
// "noImplicitReturns": true, /* Report error when not all code paths in function return a value. */
// "noFallthroughCasesInSwitch": true, /* Report errors for fallthrough cases in switch statement. */
// "noUnusedParameters": true, /* Report errors on unused parameters. */
"esModuleInterop": true /* Enables emit interoperability between CommonJS and ES Modules via creation of namespace objects for all imports. Implies 'allowSyntheticDefaultImports'. */,
"resolveJsonModule": true /* Enable importing .json files */,
"strict": true,
"esModuleInterop": true,
"resolveJsonModule": true,
"types": ["mocha"] // This solves conflict between jest and mocha: https://github.com/cypress-io/cypress/issues/7435#issuecomment-631695007
},
"include": ["src/**/*", "../../core/**/*.ts", "../../core/**/*.d.ts"],
// core/test uses @types/jest, which conflicts with @types/mocha
"exclude": ["../../core/dist/**/*", "../../core/test/**/*"]
"exclude": ["../../core/dist/**/*", "../../core/**/*.test.ts"]
}