Merge pull request #6287 from continuedev/jacob/feature/next-edit-mvp
Jacob/feature/next edit mvp
This commit is contained in:
commit
4bcf69fc7e
70 changed files with 10933 additions and 514 deletions
187
.github/workflows/pr_checks.yaml
vendored
187
.github/workflows/pr_checks.yaml
vendored
|
|
@ -75,6 +75,33 @@ jobs:
|
|||
cd packages/config-yaml
|
||||
npm ci
|
||||
|
||||
install-openai-adapters:
|
||||
needs: install-root
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
||||
- uses: actions/cache@v4
|
||||
with:
|
||||
path: node_modules
|
||||
key: ${{ runner.os }}-root-node-modules-${{ hashFiles('package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Install openai-adapters dependencies
|
||||
if: steps.openai-adapters-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm ci
|
||||
|
||||
config-yaml-checks:
|
||||
needs: install-config-yaml
|
||||
runs-on: ubuntu-latest
|
||||
|
|
@ -133,7 +160,7 @@ jobs:
|
|||
npm ci
|
||||
|
||||
core-checks:
|
||||
needs: [install-core, install-config-yaml]
|
||||
needs: [install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -160,11 +187,21 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd core
|
||||
|
|
@ -174,7 +211,8 @@ jobs:
|
|||
OPENAI_API_KEY: ${{ secrets.OPENAI_API_KEY }}
|
||||
|
||||
install-gui:
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
needs:
|
||||
[install-root, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -205,11 +243,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Install gui dependencies
|
||||
if: steps.gui-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -221,7 +270,6 @@ jobs:
|
|||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
- uses: actions/setup-node@v4
|
||||
with:
|
||||
node-version-file: ".nvmrc"
|
||||
|
|
@ -242,6 +290,12 @@ jobs:
|
|||
path: gui/node_modules
|
||||
key: ${{ runner.os }}-gui-node-modules-${{ hashFiles('gui/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: config-yaml-cache
|
||||
with:
|
||||
|
|
@ -253,6 +307,11 @@ jobs:
|
|||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd gui
|
||||
|
|
@ -260,7 +319,8 @@ jobs:
|
|||
npm run lint
|
||||
|
||||
binary-checks:
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
needs:
|
||||
[install-root, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -291,11 +351,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Install binary dependencies
|
||||
if: steps.binary-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -308,7 +379,8 @@ jobs:
|
|||
npx tsc --noEmit
|
||||
|
||||
install-vscode:
|
||||
needs: [install-root, install-core, install-config-yaml]
|
||||
needs:
|
||||
[install-root, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -339,11 +411,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Install vscode dependencies
|
||||
if: steps.vscode-cache.outputs.cache-hit != 'true'
|
||||
run: |
|
||||
|
|
@ -384,11 +467,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Type check and lint
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
|
|
@ -402,7 +496,7 @@ jobs:
|
|||
npm run vitest
|
||||
|
||||
core-tests:
|
||||
needs: [install-core, install-config-yaml]
|
||||
needs: [install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -422,11 +516,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Run core tests
|
||||
run: |
|
||||
cd core
|
||||
|
|
@ -476,7 +581,7 @@ jobs:
|
|||
- uses: actions/checkout@v4
|
||||
|
||||
- name: Cache node modules
|
||||
uses: actions/cache@v3
|
||||
uses: actions/cache@v4
|
||||
with:
|
||||
path: extensions/vscode/node_modules
|
||||
key: ${{ runner.os }}-vscode-node-modules-${{ hashFiles('extensions/vscode/package-lock.json') }}
|
||||
|
|
@ -515,7 +620,13 @@ jobs:
|
|||
|
||||
vscode-package-extension:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [install-vscode, install-core, install-config-yaml]
|
||||
needs:
|
||||
[
|
||||
install-vscode,
|
||||
install-core,
|
||||
install-config-yaml,
|
||||
install-openai-adapters,
|
||||
]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -541,11 +652,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Package extension
|
||||
run: |
|
||||
cd extensions/vscode
|
||||
|
|
@ -559,7 +681,13 @@ jobs:
|
|||
|
||||
vscode-download-e2e-dependencies:
|
||||
runs-on: ubuntu-latest
|
||||
needs: [install-vscode, install-core, install-config-yaml]
|
||||
needs:
|
||||
[
|
||||
install-vscode,
|
||||
install-core,
|
||||
install-config-yaml,
|
||||
install-openai-adapters,
|
||||
]
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
||||
|
|
@ -612,6 +740,7 @@ jobs:
|
|||
install-vscode,
|
||||
install-core,
|
||||
install-config-yaml,
|
||||
install-openai-adapters,
|
||||
]
|
||||
runs-on: ubuntu-latest
|
||||
# Tests requiring secrets need approval from maintainers
|
||||
|
|
@ -658,11 +787,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Fix VSCode binary permissions
|
||||
run: |
|
||||
chmod +x extensions/vscode/e2e/storage/VSCode-linux-x64/code
|
||||
|
|
@ -726,7 +866,8 @@ jobs:
|
|||
path: extensions/vscode/e2e.log
|
||||
|
||||
gui-tests:
|
||||
needs: [install-gui, install-core, install-config-yaml]
|
||||
needs:
|
||||
[install-gui, install-core, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -752,11 +893,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Install GUI dependencies
|
||||
if: steps.gui-cache.outputs.cache-hit != 'true'
|
||||
run: cd gui && npm ci
|
||||
|
|
@ -769,7 +921,8 @@ jobs:
|
|||
npm test
|
||||
|
||||
jetbrains-tests:
|
||||
needs: [install-root, core-checks, install-config-yaml]
|
||||
needs:
|
||||
[install-root, core-checks, install-config-yaml, install-openai-adapters]
|
||||
runs-on: ubuntu-latest
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
|
|
@ -784,11 +937,22 @@ jobs:
|
|||
path: packages/config-yaml/node_modules
|
||||
key: ${{ runner.os }}-config-yaml-node-modules-${{ hashFiles('packages/config-yaml/package-lock.json') }}
|
||||
|
||||
- uses: actions/cache@v4
|
||||
id: openai-adapters-cache
|
||||
with:
|
||||
path: packages/openai-adapters/node_modules
|
||||
key: ${{ runner.os }}-openai-adapters-node-modules-${{ hashFiles('packages/openai-adapters/package-lock.json') }}
|
||||
|
||||
- name: Build config-yaml
|
||||
run: |
|
||||
cd packages/config-yaml
|
||||
npm run build
|
||||
|
||||
- name: Build openai-adapters
|
||||
run: |
|
||||
cd packages/openai-adapters
|
||||
npm run build
|
||||
|
||||
- name: Setup Java
|
||||
uses: actions/setup-java@v4.5.0
|
||||
with:
|
||||
|
|
@ -903,6 +1067,7 @@ jobs:
|
|||
- jetbrains-tests
|
||||
- config-yaml-checks
|
||||
- install-config-yaml
|
||||
- install-openai-adapters
|
||||
|
||||
steps:
|
||||
- name: Decide whether the needed jobs succeeded or failed
|
||||
|
|
|
|||
|
|
@ -20,6 +20,8 @@ export const sharedConfigSchema = z
|
|||
promptPath: z.string(),
|
||||
useCurrentFileAsContext: z.boolean(),
|
||||
logEditingData: z.boolean(),
|
||||
// add internal features below
|
||||
optInNextEditFeature: z.boolean(),
|
||||
|
||||
// `ui` in `ContinueConfig`
|
||||
showSessionTabs: z.boolean(),
|
||||
|
|
@ -175,6 +177,10 @@ export function modifyAnyConfigWithSharedConfig<
|
|||
if (sharedConfig.logEditingData !== undefined) {
|
||||
configCopy.experimental.logEditingData = sharedConfig.logEditingData;
|
||||
}
|
||||
if (sharedConfig.optInNextEditFeature !== undefined) {
|
||||
configCopy.experimental.optInNextEditFeature =
|
||||
sharedConfig.optInNextEditFeature;
|
||||
}
|
||||
|
||||
return configCopy;
|
||||
}
|
||||
|
|
|
|||
16
core/core.ts
16
core/core.ts
|
|
@ -68,8 +68,13 @@ import { walkDirCache } from "./indexing/walkDir";
|
|||
import { LLMLogger } from "./llm/logger";
|
||||
import { RULES_MARKDOWN_FILENAME } from "./llm/rules/constants";
|
||||
import { llmStreamChat } from "./llm/streamChat";
|
||||
import { BeforeAfterDiff } from "./nextEdit/context/diffFormatting";
|
||||
import {
|
||||
BeforeAfterDiff,
|
||||
createDiff,
|
||||
DiffFormatType,
|
||||
} from "./nextEdit/context/diffFormatting";
|
||||
import { processNextEditData } from "./nextEdit/context/processNextEditData.js";
|
||||
import { NextEditProvider } from "./nextEdit/NextEditProvider";
|
||||
import type { FromCoreProtocol, ToCoreProtocol } from "./protocol";
|
||||
import { OnboardingModes } from "./protocol/core";
|
||||
import type { IMessenger, Message } from "./protocol/messenger";
|
||||
|
|
@ -723,6 +728,15 @@ export class Core {
|
|||
cursorPosBeforeEdit: Position,
|
||||
cursorPosAfterPrevEdit: Position,
|
||||
) => {
|
||||
NextEditProvider.getInstance().addDiffToContext(
|
||||
createDiff(
|
||||
beforeAfterdiff.beforeContent,
|
||||
beforeAfterdiff.afterContent,
|
||||
beforeAfterdiff.filePath,
|
||||
DiffFormatType.Unified,
|
||||
),
|
||||
);
|
||||
|
||||
// Get the current context data from the most recent message
|
||||
const currentData = (global._editAggregator as any)
|
||||
.latestContextData || {
|
||||
|
|
|
|||
5
core/index.d.ts
vendored
5
core/index.d.ts
vendored
|
|
@ -1376,6 +1376,11 @@ export interface ExperimentalConfig {
|
|||
* If enabled, will save data on the user's editing processes
|
||||
*/
|
||||
logEditingData?: boolean;
|
||||
|
||||
/**
|
||||
* If enabled, will enable next edit in place of autocomplete
|
||||
*/
|
||||
optInNextEditFeature?: boolean;
|
||||
}
|
||||
|
||||
export interface AnalyticsConfig {
|
||||
|
|
|
|||
|
|
@ -292,6 +292,7 @@ export abstract class BaseLLM implements ILLM {
|
|||
apiKey: this.apiKey ?? "",
|
||||
apiBase: this.apiBase,
|
||||
requestOptions: this.requestOptions,
|
||||
env: this._llmOptions.env,
|
||||
});
|
||||
}
|
||||
|
||||
|
|
|
|||
|
|
@ -405,7 +405,6 @@ class Ollama extends BaseLLM implements ModelInstaller {
|
|||
parameters: tool.function.parameters,
|
||||
},
|
||||
}));
|
||||
chatOptions.stream = false; // Cannot set stream = true for tools calls
|
||||
}
|
||||
const headers: Record<string, string> = {
|
||||
"Content-Type": "application/json",
|
||||
|
|
|
|||
|
|
@ -18,6 +18,7 @@ import {
|
|||
AutocompleteInput,
|
||||
AutocompleteOutcome,
|
||||
} from "../autocomplete/util/types.js";
|
||||
import { replaceEscapedCharacters } from "../util/text.js";
|
||||
import {
|
||||
Prompt,
|
||||
renderDefaultSystemPrompt,
|
||||
|
|
@ -37,6 +38,8 @@ const ERRORS_TO_IGNORE = [
|
|||
];
|
||||
|
||||
export class NextEditProvider {
|
||||
private static instance: NextEditProvider | null = null;
|
||||
|
||||
private autocompleteCache = AutocompleteLruCache.get();
|
||||
public errorsShown: Set<string> = new Set();
|
||||
private bracketMatchingService = new BracketMatchingService();
|
||||
|
|
@ -45,8 +48,9 @@ export class NextEditProvider {
|
|||
private loggingService = new AutocompleteLoggingService();
|
||||
private contextRetrievalService: ContextRetrievalService;
|
||||
private endpointType: "default" | "fineTuned";
|
||||
private diffContext: string = "";
|
||||
|
||||
constructor(
|
||||
private constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: IDE,
|
||||
private readonly _injectedGetLlm: () => Promise<ILLM | undefined>,
|
||||
|
|
@ -59,6 +63,40 @@ export class NextEditProvider {
|
|||
this.endpointType = endpointType;
|
||||
}
|
||||
|
||||
public static initialize(
|
||||
configHandler: ConfigHandler,
|
||||
ide: IDE,
|
||||
injectedGetLlm: () => Promise<ILLM | undefined>,
|
||||
onError: (e: any) => void,
|
||||
getDefinitionsFromLsp: GetLspDefinitionsFunction,
|
||||
endpointType: "default" | "fineTuned",
|
||||
): NextEditProvider {
|
||||
if (!NextEditProvider.instance) {
|
||||
NextEditProvider.instance = new NextEditProvider(
|
||||
configHandler,
|
||||
ide,
|
||||
injectedGetLlm,
|
||||
onError,
|
||||
getDefinitionsFromLsp,
|
||||
endpointType,
|
||||
);
|
||||
}
|
||||
return NextEditProvider.instance;
|
||||
}
|
||||
|
||||
public static getInstance(): NextEditProvider {
|
||||
if (!NextEditProvider.instance) {
|
||||
throw new Error(
|
||||
"NextEditProvider has not been initialized. Call initialize() first.",
|
||||
);
|
||||
}
|
||||
return NextEditProvider.instance;
|
||||
}
|
||||
|
||||
public addDiffToContext(diff: string): void {
|
||||
this.diffContext = diff;
|
||||
}
|
||||
|
||||
private async _prepareLlm(): Promise<ILLM | undefined> {
|
||||
const llm = await this._injectedGetLlm();
|
||||
|
||||
|
|
@ -203,6 +241,7 @@ export class NextEditProvider {
|
|||
snippetPayload,
|
||||
this.ide,
|
||||
helper,
|
||||
this.diffContext,
|
||||
),
|
||||
);
|
||||
}
|
||||
|
|
@ -254,10 +293,19 @@ export class NextEditProvider {
|
|||
|
||||
// TODO: Do some zod schema validation here if needed.
|
||||
} else {
|
||||
const testController = new AbortController();
|
||||
const msg: ChatMessage = await llm.chat(prompts, testController.signal);
|
||||
// const testController = new AbortController();
|
||||
// const msg: ChatMessage = await llm.chat(prompts, testController.signal);
|
||||
// const testToken = testController.signal;
|
||||
const msg: ChatMessage = await llm.chat(prompts, token);
|
||||
if (typeof msg.content === "string") {
|
||||
const nextCompletion = msg.content;
|
||||
// TODO: There are cases where msg.conetnt.split("<|start|>")[1] is undefined
|
||||
const nextCompletion = replaceEscapedCharacters(
|
||||
msg.content.split("<|editable_region_start|>\n")[1],
|
||||
).replace(/\n$/, "");
|
||||
|
||||
// const diffLines = myersDiff(helper.fileContents, nextCompletion);
|
||||
|
||||
// const diff = getRenderableDiff(diffLines);
|
||||
|
||||
const outcomeNext: AutocompleteOutcome = {
|
||||
time: Date.now() - startTime,
|
||||
|
|
|
|||
77
core/nextEdit/diff/diff.ts
Normal file
77
core/nextEdit/diff/diff.ts
Normal file
|
|
@ -0,0 +1,77 @@
|
|||
import { DiffLine } from "../..";
|
||||
|
||||
export function getRenderableDiff(diffLines: DiffLine[]): {
|
||||
renderableDiff: string;
|
||||
offset: {
|
||||
line: number;
|
||||
character: number;
|
||||
};
|
||||
} {
|
||||
let lastNewLineIndex = -1;
|
||||
let lastNewLine = "";
|
||||
|
||||
// Build the string with only "new" lines.
|
||||
let diff = diffLines.reduce((acc, curr, i) => {
|
||||
if (curr.type === "new") {
|
||||
lastNewLineIndex = i;
|
||||
lastNewLine = curr.line;
|
||||
acc += `${curr.line}\n`;
|
||||
}
|
||||
return acc;
|
||||
}, "");
|
||||
|
||||
// Remove the last newline character if it exists.
|
||||
if (diff.length > 0 && diff.charAt(diff.length - 1) === "\n") {
|
||||
diff = diff.slice(0, -1);
|
||||
}
|
||||
|
||||
// There seems to always be an old line replaced by a series of new lines.
|
||||
// Account for this by subtracting one.
|
||||
lastNewLineIndex -= 1;
|
||||
|
||||
// Calculate the character position for the end of the last "new" line.
|
||||
const endOfCharPos = lastNewLineIndex !== -1 ? lastNewLine.length : 0;
|
||||
|
||||
return {
|
||||
renderableDiff: diff,
|
||||
offset: { line: lastNewLineIndex, character: endOfCharPos },
|
||||
};
|
||||
}
|
||||
|
||||
export function getRenderableDiffWithGutterAnnotations(diffLines: DiffLine[]): {
|
||||
renderableDiff: string;
|
||||
offset: {
|
||||
line: number;
|
||||
character: number;
|
||||
};
|
||||
} {
|
||||
let lastNewLineIndex = -1;
|
||||
let lastNewLine = "";
|
||||
|
||||
// Build the string with only "new" lines.
|
||||
let diff = diffLines.reduce((acc, curr, i) => {
|
||||
if (curr.type === "new") {
|
||||
lastNewLineIndex = i;
|
||||
lastNewLine = curr.line;
|
||||
acc += `+ ${curr.line}\n`;
|
||||
}
|
||||
return acc;
|
||||
}, "");
|
||||
|
||||
// Remove the last newline character if it exists.
|
||||
if (diff.length > 0 && diff.charAt(diff.length - 1) === "\n") {
|
||||
diff = diff.slice(0, -1);
|
||||
}
|
||||
|
||||
// There seems to always be an old line replaced by a series of new lines.
|
||||
// Account for this by subtracting one.
|
||||
lastNewLineIndex -= 1;
|
||||
|
||||
// Calculate the character position for the end of the last "new" line.
|
||||
const endOfCharPos = lastNewLineIndex !== -1 ? lastNewLine.length : 0;
|
||||
|
||||
return {
|
||||
renderableDiff: diff,
|
||||
offset: { line: lastNewLineIndex, character: endOfCharPos },
|
||||
};
|
||||
}
|
||||
|
|
@ -102,14 +102,14 @@ export async function renderFineTunedUserPrompt(
|
|||
// helper.filepath,
|
||||
// );
|
||||
|
||||
const editedCodeWithPins = insertCursorPin(
|
||||
helper.fileContents,
|
||||
const editedCodeWithPins = insertPins(
|
||||
helper.fileContents.split("\n"),
|
||||
helper.pos,
|
||||
);
|
||||
|
||||
return {
|
||||
role: "user",
|
||||
content: `### User Edits:\n\n${snippets.diffSnippets}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n\<|editable_region_start|\>\n${JSON.stringify(editedCodeWithPins)}\n\<|editable_region_end|\>\n\`\`\``,
|
||||
content: `### User Edits:\n\n${snippets.diffSnippets}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n${editedCodeWithPins}\`\`\``,
|
||||
};
|
||||
|
||||
case "jetbrains":
|
||||
|
|
@ -137,14 +137,14 @@ export async function renderDefaultBasicUserPrompt(
|
|||
// helper.filepath,
|
||||
// );
|
||||
|
||||
const editedCodeWithPins = insertCursorPin(
|
||||
helper.fileContents,
|
||||
const editedCodeWithPins = insertPins(
|
||||
helper.fileContents.split("\n"),
|
||||
helper.pos,
|
||||
);
|
||||
|
||||
return {
|
||||
role: "user",
|
||||
content: `### User Edits:\n\n${JSON.stringify(snippets)}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n\<|editable_region_start|\>\n${JSON.stringify(editedCodeWithPins)}\n\<|editable_region_end|\>\n\`\`\``,
|
||||
content: `### User Edits:\n\n${JSON.stringify(snippets)}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n${editedCodeWithPins}\`\`\``,
|
||||
};
|
||||
|
||||
case "jetbrains":
|
||||
|
|
@ -162,26 +162,17 @@ export async function renderFineTunedBasicUserPrompt(
|
|||
ide: IDE,
|
||||
// cursorPos: Position,
|
||||
helper: HelperVars,
|
||||
diffContext: string,
|
||||
): Promise<UserPrompt> {
|
||||
const ideInfo = await ide.getIdeInfo();
|
||||
switch (ideInfo.ideType) {
|
||||
case "vscode":
|
||||
// const diffs = await compareAndReturnDiff(
|
||||
// originalCode,
|
||||
// editedCode,
|
||||
// helper.filepath,
|
||||
// );
|
||||
|
||||
const editedCodeWithPins = insertCursorPin(
|
||||
helper.fileContents,
|
||||
helper.pos,
|
||||
);
|
||||
|
||||
console.log(snippets);
|
||||
const lines = helper.fileContents.split("\n");
|
||||
const editedCodeWithPins = insertPins(lines, helper.pos);
|
||||
|
||||
return {
|
||||
role: "user",
|
||||
content: `### User Edits:\n\n${JSON.stringify(snippets)}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n\<|editable_region_start|\>\n${JSON.stringify(editedCodeWithPins)}\n\<|editable_region_end|\>\n\`\`\``,
|
||||
content: `### User Edits:\n\n${diffContext}\n\n### User Excerpts:\n\n\`\`\`${helper.lang.name}\n${editedCodeWithPins}\`\`\``,
|
||||
};
|
||||
|
||||
case "jetbrains":
|
||||
|
|
@ -192,11 +183,15 @@ export async function renderFineTunedBasicUserPrompt(
|
|||
}
|
||||
}
|
||||
|
||||
function insertCursorPin(fileContents: string, cursorPos: Position) {
|
||||
const lines = fileContents.split("\n");
|
||||
function insertPins(lines: string[], cursorPos: Position) {
|
||||
const a = insertCursorPin(lines, cursorPos);
|
||||
const b = insertEditableRegionPinsWithStaticRange(a, cursorPos, 5, 5);
|
||||
return b.join("\n");
|
||||
}
|
||||
|
||||
function insertCursorPin(lines: string[], cursorPos: Position) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return fileContents;
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure character position is within bounds or at the end of the line.
|
||||
|
|
@ -208,5 +203,50 @@ function insertCursorPin(fileContents: string, cursorPos: Position) {
|
|||
"<|user_cursor_is_here|>" +
|
||||
lines[cursorPos.line].slice(charPos);
|
||||
|
||||
return lines.join("\n");
|
||||
return lines;
|
||||
}
|
||||
|
||||
function insertEditableRegionPinsWithStaticRange(
|
||||
lines: string[],
|
||||
cursorPos: Position,
|
||||
marginTop: number,
|
||||
marginBottom: number,
|
||||
) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure editable regions are within bounds.
|
||||
const editableRegionStart = Math.max(cursorPos.line - marginTop, 0);
|
||||
const editableRegionEnd = Math.min(
|
||||
cursorPos.line + marginBottom,
|
||||
lines.length - 1,
|
||||
);
|
||||
|
||||
const instrumentedLines = [
|
||||
...lines.slice(0, editableRegionStart),
|
||||
"<|editable_region_start|>",
|
||||
...lines.slice(editableRegionStart, editableRegionEnd + 1),
|
||||
"<|editable_region_end|>",
|
||||
...lines.slice(editableRegionEnd + 1),
|
||||
];
|
||||
|
||||
return instrumentedLines;
|
||||
}
|
||||
|
||||
function insertEditableRegionPinsWithAst(lines: string[], cursorPos: Position) {
|
||||
if (cursorPos.line < 0 || cursorPos.line >= lines.length) {
|
||||
return lines;
|
||||
}
|
||||
|
||||
// Ensure character position is within bounds or at the end of the line.
|
||||
const lineLength = lines[cursorPos.line].length;
|
||||
const charPos = Math.min(Math.max(0, cursorPos.character), lineLength);
|
||||
|
||||
lines[cursorPos.line] =
|
||||
lines[cursorPos.line].slice(0, charPos) +
|
||||
"<|user_cursor_is_here|>" +
|
||||
lines[cursorPos.line].slice(charPos);
|
||||
|
||||
return lines;
|
||||
}
|
||||
|
|
|
|||
810
core/package-lock.json
generated
810
core/package-lock.json
generated
File diff suppressed because it is too large
Load diff
|
|
@ -41,6 +41,7 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"shiki": "^3.6.0",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
|
|
@ -51,9 +52,9 @@
|
|||
"@aws-sdk/credential-providers": "^3.778.0",
|
||||
"@continuedev/config-types": "^1.0.13",
|
||||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/fetch": "^1.0.14",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.32",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -99,6 +100,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"satori": "^0.15.2",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
|
|||
|
|
@ -55,6 +55,13 @@ export type ToIdeFromWebviewProtocol = ToIdeFromWebviewOrCoreProtocol & {
|
|||
];
|
||||
"edit/addCurrentSelection": [undefined, void];
|
||||
"edit/clearDecorations": [undefined, void];
|
||||
optInNextEditFeature: [
|
||||
{
|
||||
email: string;
|
||||
optIn: boolean;
|
||||
},
|
||||
void,
|
||||
];
|
||||
};
|
||||
|
||||
export type ToWebviewFromIdeProtocol = ToWebviewFromIdeOrCoreProtocol & {
|
||||
|
|
|
|||
395
core/syntaxHighlighting/SyntaxHighlighter.ts
Normal file
395
core/syntaxHighlighting/SyntaxHighlighter.ts
Normal file
|
|
@ -0,0 +1,395 @@
|
|||
import * as fs from "fs/promises";
|
||||
import { JSDOM } from "jsdom";
|
||||
import satori from "satori";
|
||||
// import puppeteer, { Browser, ScreenshotOptions } from "puppeteer";
|
||||
import { BundledTheme, codeToHtml, getSingletonHighlighter } from "shiki";
|
||||
import { escapeForSVG, kebabOfStr } from "../util/text";
|
||||
|
||||
interface SyntaxHighlighterOptions {
|
||||
themesDir?: string;
|
||||
theme?: string;
|
||||
}
|
||||
|
||||
interface HTMLOptions {
|
||||
theme?: string;
|
||||
customCSS?: string;
|
||||
containerClass?: string;
|
||||
}
|
||||
|
||||
interface ConversionOptions extends HTMLOptions {
|
||||
transparent?: boolean;
|
||||
imageType: "svg";
|
||||
}
|
||||
|
||||
interface Dimensions {
|
||||
width: number;
|
||||
height: number;
|
||||
}
|
||||
|
||||
interface DataAndDimensions {
|
||||
data: Buffer;
|
||||
dimensions: Dimensions;
|
||||
}
|
||||
|
||||
interface DataUriAndDimensions {
|
||||
uri: DataUri;
|
||||
dimensions: Dimensions;
|
||||
}
|
||||
|
||||
type DataUri = PngUri | SvgUri;
|
||||
|
||||
type PngUri = string;
|
||||
type SvgUri = string;
|
||||
|
||||
export class SyntaxHighlighter {
|
||||
private static instance: SyntaxHighlighter;
|
||||
private currentTheme: string = "dark-plus";
|
||||
private editorBackground: string = "#000000";
|
||||
private editorForeground: string = "#FFFFFF";
|
||||
|
||||
private constructor(options: SyntaxHighlighterOptions = {}) {}
|
||||
|
||||
static getInstance(options?: SyntaxHighlighterOptions): SyntaxHighlighter {
|
||||
if (!SyntaxHighlighter.instance) {
|
||||
SyntaxHighlighter.instance = new SyntaxHighlighter(options);
|
||||
}
|
||||
return SyntaxHighlighter.instance;
|
||||
}
|
||||
|
||||
public async setTheme(themeName: string): Promise<void> {
|
||||
if (
|
||||
this.themeExists(kebabOfStr(themeName)) ||
|
||||
themeName === "Default Dark Modern"
|
||||
) {
|
||||
this.currentTheme =
|
||||
themeName === "Default Dark Modern"
|
||||
? "dark-plus"
|
||||
: kebabOfStr(themeName);
|
||||
|
||||
const highlighter = await getSingletonHighlighter({
|
||||
themes: [this.currentTheme],
|
||||
});
|
||||
|
||||
const th = highlighter.getTheme(this.currentTheme);
|
||||
this.editorBackground = th.bg;
|
||||
this.editorForeground = th.fg;
|
||||
} else {
|
||||
this.currentTheme = "dark-plus";
|
||||
}
|
||||
}
|
||||
|
||||
async init(): Promise<void> {}
|
||||
|
||||
async close(): Promise<void> {}
|
||||
|
||||
themeExists(themeNameKebab: string): themeNameKebab is BundledTheme {
|
||||
const themeArray: BundledTheme[] = [
|
||||
"andromeeda",
|
||||
"aurora-x",
|
||||
"ayu-dark",
|
||||
"catppuccin-frappe",
|
||||
"catppuccin-latte",
|
||||
"catppuccin-macchiato",
|
||||
"catppuccin-mocha",
|
||||
"dark-plus",
|
||||
"dracula",
|
||||
"dracula-soft",
|
||||
"everforest-dark",
|
||||
"everforest-light",
|
||||
"github-dark",
|
||||
"github-dark-default",
|
||||
"github-dark-dimmed",
|
||||
"github-dark-high-contrast",
|
||||
"github-light",
|
||||
"github-light-default",
|
||||
"github-light-high-contrast",
|
||||
"gruvbox-dark-hard",
|
||||
"gruvbox-dark-medium",
|
||||
"gruvbox-dark-soft",
|
||||
"gruvbox-light-hard",
|
||||
"gruvbox-light-medium",
|
||||
"gruvbox-light-soft",
|
||||
"houston",
|
||||
"kanagawa-dragon",
|
||||
"kanagawa-lotus",
|
||||
"kanagawa-wave",
|
||||
"laserwave",
|
||||
"light-plus",
|
||||
"material-theme",
|
||||
"material-theme-darker",
|
||||
"material-theme-lighter",
|
||||
"material-theme-ocean",
|
||||
"material-theme-palenight",
|
||||
"min-dark",
|
||||
"min-light",
|
||||
"monokai",
|
||||
"night-owl",
|
||||
"nord",
|
||||
"one-dark-pro",
|
||||
"one-light",
|
||||
"plastic",
|
||||
"poimandres",
|
||||
"red",
|
||||
"rose-pine",
|
||||
"rose-pine-dawn",
|
||||
"rose-pine-moon",
|
||||
"slack-dark",
|
||||
"slack-ochin",
|
||||
"snazzy-light",
|
||||
"solarized-dark",
|
||||
"solarized-light",
|
||||
"synthwave-84",
|
||||
"tokyo-night",
|
||||
"vesper",
|
||||
"vitesse-black",
|
||||
"vitesse-dark",
|
||||
"vitesse-light",
|
||||
];
|
||||
|
||||
return themeArray.includes(themeNameKebab as BundledTheme);
|
||||
}
|
||||
|
||||
async highlightCode(
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
): Promise<string> {
|
||||
return await codeToHtml(code, {
|
||||
lang: language,
|
||||
theme: this.currentTheme,
|
||||
});
|
||||
}
|
||||
|
||||
// async convertToPNG(
|
||||
// code: string,
|
||||
// language: string = "javascript",
|
||||
// fontSize: number,
|
||||
// dimensions: Dimensions,
|
||||
// lineHeight: number,
|
||||
// options: ConversionOptions,
|
||||
// ): Promise<DataAndDimensions> {
|
||||
// if (!this.browser) {
|
||||
// throw new Error("Browser not initialized. Call init() first.");
|
||||
// }
|
||||
|
||||
// const highlightedCodeHtml = await this.highlightCode(code, language);
|
||||
|
||||
// const page = await this.browser.newPage();
|
||||
// await page.setContent(highlightedCodeHtml);
|
||||
|
||||
// const dims = await page.evaluate(() => {
|
||||
// const body = document.body;
|
||||
// return {
|
||||
// width: body.scrollWidth,
|
||||
// height: body.scrollHeight,
|
||||
// };
|
||||
// });
|
||||
|
||||
// await page.setViewport({
|
||||
// width: 3840,
|
||||
// height: 2160,
|
||||
// deviceScaleFactor: 1,
|
||||
// });
|
||||
|
||||
// const screenshot = await page.screenshot({
|
||||
// type: "png",
|
||||
// omitBackground: true,
|
||||
// ...options.screenshotOptions,
|
||||
// });
|
||||
|
||||
// await page.close();
|
||||
|
||||
// return { data: screenshot, dimensions: dims };
|
||||
// }
|
||||
|
||||
async convertToBlankSVG(
|
||||
dimensions: Dimensions,
|
||||
options: ConversionOptions,
|
||||
): Promise<Buffer> {
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}">
|
||||
<g><rect width="${dimensions.width}" height="${dimensions.height}" fill="#ff0000" /><text fill="#ffffff" x="0" y="20" font-family="monospace" font-size="14" xml:space="preserve">TEST TEXT THIS IS</text></g>
|
||||
</svg>`;
|
||||
|
||||
return Buffer.from(svg, "utf8");
|
||||
}
|
||||
|
||||
async convertToSVG(
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
dimensions: Dimensions,
|
||||
lineHeight: number,
|
||||
options: ConversionOptions,
|
||||
): Promise<Buffer> {
|
||||
const highlightedCodeHtml = await this.highlightCode(code, language);
|
||||
|
||||
const guts = this.convertShikiHtmlToSvgGut(
|
||||
highlightedCodeHtml,
|
||||
fontSize,
|
||||
fontFamily,
|
||||
lineHeight,
|
||||
);
|
||||
const backgroundColor = this.getBackgroundColor(highlightedCodeHtml);
|
||||
|
||||
const svg = `<svg xmlns="http://www.w3.org/2000/svg" width="${dimensions.width}" height="${dimensions.height}">
|
||||
<g>
|
||||
<rect width="${dimensions.width}" height="${dimensions.height}" fill="${backgroundColor}" stroke="${this.editorForeground}" stroke-width="1" />
|
||||
${guts}
|
||||
</g>
|
||||
</svg>`;
|
||||
|
||||
return Buffer.from(svg, "utf8");
|
||||
}
|
||||
|
||||
async convertToSVGWithSatori(
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
fontSize: number,
|
||||
dimensions: Dimensions,
|
||||
lineHeight: number,
|
||||
options: ConversionOptions,
|
||||
): Promise<Buffer> {
|
||||
const highlightedCodeHtml = await this.highlightCode(code, language);
|
||||
|
||||
console.log(code);
|
||||
console.log(highlightedCodeHtml);
|
||||
|
||||
// Convert to SVG using Satori
|
||||
const fontData = await this.loadFont();
|
||||
const svg = await satori(highlightedCodeHtml, {
|
||||
width: dimensions.width, // You'll need to determine appropriate width
|
||||
height: dimensions.height, // Dynamic height based on content
|
||||
fonts: [
|
||||
{
|
||||
name: "YourMonospaceFontName",
|
||||
data: fontData,
|
||||
style: "normal",
|
||||
},
|
||||
],
|
||||
});
|
||||
|
||||
console.log(svg);
|
||||
return Buffer.from(svg, "utf8");
|
||||
}
|
||||
|
||||
// Function to load your font
|
||||
async loadFont(): Promise<Buffer> {
|
||||
// Option 1: If running in Node.js, you can load from the filesystem
|
||||
console.log(process.cwd());
|
||||
return Buffer.from(
|
||||
await fs.readFile(
|
||||
// TODO: fix this to actually resolve to path
|
||||
"/home/jacob/continue/continue/fonts/Cascadia_Mono/static/CascadiaMono-Regular.ttf",
|
||||
"binary",
|
||||
),
|
||||
"binary",
|
||||
);
|
||||
}
|
||||
|
||||
convertShikiHtmlToSvgGut(
|
||||
shikiHtml: string,
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
lineHeight: number,
|
||||
): string {
|
||||
const dom = new JSDOM(shikiHtml);
|
||||
const document = dom.window.document;
|
||||
|
||||
const lines = Array.from(document.querySelectorAll(".line"));
|
||||
const svgLines = lines.map((line, index) => {
|
||||
const spans = Array.from(line.childNodes)
|
||||
.map((node) => {
|
||||
if (node.nodeType === 3) {
|
||||
return `<tspan xml:space="preserve">${escapeForSVG(node.textContent ?? "")}</tspan>`;
|
||||
}
|
||||
|
||||
const el = node as HTMLElement;
|
||||
const style = el.getAttribute("style") || "";
|
||||
const colorMatch = style.match(/color:\s*(#[0-9a-fA-F]{6})/);
|
||||
const fill = colorMatch ? ` fill="${colorMatch[1]}"` : "";
|
||||
const content = el.textContent || "";
|
||||
return `<tspan xml:space="preserve"${fill}>${escapeForSVG(content)}</tspan>`;
|
||||
})
|
||||
.join("");
|
||||
|
||||
const y = (index + 1) * lineHeight;
|
||||
return `<text x="0" y="${y}" font-family="${fontFamily}" font-size="${fontSize.toString()}" xml:space="preserve">${spans}</text>`;
|
||||
});
|
||||
|
||||
return `
|
||||
${svgLines.join("\n")}
|
||||
`.trim();
|
||||
}
|
||||
|
||||
getBackgroundColor(shikiHtml: string): string {
|
||||
const dom = new JSDOM(shikiHtml);
|
||||
const document = dom.window.document;
|
||||
|
||||
const preElement = document.querySelector("pre");
|
||||
let backgroundColor = "#333333"; // Default white background
|
||||
if (preElement) {
|
||||
const style = preElement.getAttribute("style") || "";
|
||||
const bgColorMatch = style.match(/background-color:\s*(#[0-9a-fA-F]{6})/);
|
||||
if (bgColorMatch) {
|
||||
backgroundColor = bgColorMatch[1];
|
||||
}
|
||||
}
|
||||
|
||||
return backgroundColor;
|
||||
}
|
||||
|
||||
async getDataUri(
|
||||
code: string,
|
||||
language: string = "javascript",
|
||||
fontSize: number,
|
||||
fontFamily: string,
|
||||
dimensions: Dimensions,
|
||||
lineHeight: number,
|
||||
options: ConversionOptions,
|
||||
): Promise<DataUri> {
|
||||
switch (options.imageType) {
|
||||
// case "png":
|
||||
// const pngBuffer = await this.convertToPNG(
|
||||
// code,
|
||||
// language,
|
||||
// fontSize,
|
||||
// dimensions,
|
||||
// lineHeight,
|
||||
// options,
|
||||
// );
|
||||
// return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
|
||||
case "svg":
|
||||
const svgBuffer = await this.convertToSVG(
|
||||
code,
|
||||
language,
|
||||
fontSize,
|
||||
fontFamily,
|
||||
dimensions,
|
||||
lineHeight,
|
||||
options,
|
||||
);
|
||||
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
|
||||
}
|
||||
}
|
||||
|
||||
async getBlankDataUri(
|
||||
dimensions: Dimensions,
|
||||
options: ConversionOptions,
|
||||
): Promise<DataUri> {
|
||||
switch (options.imageType) {
|
||||
// case "png":
|
||||
// const pngBuffer = await this.convertToPNG(
|
||||
// code,
|
||||
// language,
|
||||
// fontSize,
|
||||
// dimensions,
|
||||
// lineHeight,
|
||||
// options,
|
||||
// );
|
||||
// return `data:image/png;base64,${pngBuffer.data.toString("base64")}`;
|
||||
case "svg":
|
||||
const svgBuffer = await this.convertToBlankSVG(dimensions, options);
|
||||
return `data:image/svg+xml;base64,${svgBuffer.toString("base64")}`;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
@ -16,7 +16,7 @@ export const createRuleBlock: Tool = {
|
|||
'Creates a "rule" that can be referenced in future conversations. This should be used whenever you want to establish code standards / preferences that should be applied consistently, or when you want to avoid making a mistake again. To modify existing rules, use the edit tool instead.',
|
||||
parameters: {
|
||||
type: "object",
|
||||
required: ["name", "rule", "alwaysApply", "description"],
|
||||
required: ["name", "rule", "description"],
|
||||
properties: {
|
||||
name: {
|
||||
type: "string",
|
||||
|
|
|
|||
|
|
@ -4,3 +4,40 @@ export const capitalizeFirstLetter = (val: string) => {
|
|||
}
|
||||
return val[0].toUpperCase() + val.slice(1);
|
||||
};
|
||||
|
||||
export function replaceEscapedCharacters(str: string): string {
|
||||
return str.replaceAll(/\\(n|t|r|\\|"|')/g, (match, p1) => {
|
||||
switch (p1) {
|
||||
case "n":
|
||||
return "\n";
|
||||
case "t":
|
||||
return "\t";
|
||||
case "r":
|
||||
return "\r";
|
||||
case "\\":
|
||||
return "\\";
|
||||
case '"':
|
||||
return '"';
|
||||
case "'":
|
||||
return "'";
|
||||
default:
|
||||
return match; // NOTE: Handle unexpected escapes better than this.
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
export function escapeForSVG(text: string): string {
|
||||
return text
|
||||
.replace(/&/g, "&") // must be first
|
||||
.replace(/</g, "<")
|
||||
.replace(/>/g, ">")
|
||||
.replace(/"/g, """)
|
||||
.replace(/'/g, "'");
|
||||
}
|
||||
|
||||
export function kebabOfStr(str: string): string {
|
||||
return str
|
||||
.replace(/([a-z])([A-Z])/g, "$1-$2") // handle camelCase and PascalCase
|
||||
.replace(/[\s_]+/g, "-") // replace spaces and underscores with hyphens
|
||||
.toLowerCase();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -211,6 +211,15 @@ const config = {
|
|||
enableInDevelopment: false,
|
||||
},
|
||||
],
|
||||
[
|
||||
"docusaurus-plugin-llms-txt",
|
||||
{
|
||||
// Optional configuration
|
||||
outputPath: "static/llms.txt",
|
||||
includePatterns: ["docs/**"],
|
||||
excludePatterns: ["**/node_modules/**"],
|
||||
},
|
||||
],
|
||||
[
|
||||
"@docusaurus/plugin-client-redirects",
|
||||
{
|
||||
|
|
|
|||
18
docs/package-lock.json
generated
18
docs/package-lock.json
generated
|
|
@ -14,6 +14,7 @@
|
|||
"@docusaurus/preset-classic": "^3.7.0",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"clsx": "^2.1.0",
|
||||
"docusaurus-plugin-llms-txt": "^0.1.3",
|
||||
"posthog-docusaurus": "^2.0.4",
|
||||
"prism-react-renderer": "^2.3.1",
|
||||
"react": "^18.2.0",
|
||||
|
|
@ -7604,6 +7605,23 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/docusaurus-plugin-llms-txt": {
|
||||
"version": "0.1.3",
|
||||
"resolved": "https://registry.npmjs.org/docusaurus-plugin-llms-txt/-/docusaurus-plugin-llms-txt-0.1.3.tgz",
|
||||
"integrity": "sha512-X/Dqf1/soHFjvELWXtfa9C023498HsWWwNPdVZEu0OoznI2Gzf+VCB/4obwpBSV9OeDeI8D94/dK/ETq534k9A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"fs-extra": "^11.2.0",
|
||||
"gray-matter": "^4.0.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16.14"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@docusaurus/core": ">=2.0.0",
|
||||
"react": ">=16.8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/dom-converter": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/dom-converter/-/dom-converter-0.2.0.tgz",
|
||||
|
|
|
|||
|
|
@ -22,6 +22,7 @@
|
|||
"@docusaurus/preset-classic": "^3.7.0",
|
||||
"@mdx-js/react": "^3.0.0",
|
||||
"clsx": "^2.1.0",
|
||||
"docusaurus-plugin-llms-txt": "^0.1.3",
|
||||
"posthog-docusaurus": "^2.0.4",
|
||||
"prism-react-renderer": "^2.3.1",
|
||||
"react": "^18.2.0",
|
||||
|
|
|
|||
8
extensions/vscode/package-lock.json
generated
8
extensions/vscode/package-lock.json
generated
|
|
@ -1,12 +1,12 @@
|
|||
{
|
||||
"name": "continue",
|
||||
"version": "1.1.49",
|
||||
"version": "1.1.50",
|
||||
"lockfileVersion": 3,
|
||||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"name": "continue",
|
||||
"version": "1.1.49",
|
||||
"version": "1.1.50",
|
||||
"license": "Apache-2.0",
|
||||
"dependencies": {
|
||||
"@continuedev/config-types": "^1.0.14",
|
||||
|
|
@ -110,7 +110,7 @@
|
|||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.32",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -156,6 +156,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"satori": "^0.15.2",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -199,6 +200,7 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"shiki": "^3.6.0",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
|
|
|
|||
|
|
@ -334,6 +334,14 @@
|
|||
"category": "Continue",
|
||||
"title": "Enter Enterprise License Key",
|
||||
"group": "Continue"
|
||||
},
|
||||
{
|
||||
"command": "nextEditWindow.hideTooltips",
|
||||
"title": "Hide Tooltip Window"
|
||||
},
|
||||
{
|
||||
"command": "nextEditWindow.acceptNextEdit",
|
||||
"title": "Accept Next Edit Suggestion"
|
||||
}
|
||||
],
|
||||
"keybindings": [
|
||||
|
|
@ -426,6 +434,16 @@
|
|||
"command": "continue.applyCodeFromChat",
|
||||
"mac": "alt+a",
|
||||
"key": "alt+a"
|
||||
},
|
||||
{
|
||||
"command": "nextEditWindow.hideTooltips",
|
||||
"key": "escape",
|
||||
"when": "editorTextFocus && nextEditWindowActive"
|
||||
},
|
||||
{
|
||||
"command": "nextEditWindow.acceptNextEdit",
|
||||
"key": "tab",
|
||||
"when": "editorTextFocus && nextEditWindowActive"
|
||||
}
|
||||
],
|
||||
"submenus": [
|
||||
|
|
|
|||
662
extensions/vscode/src/activation/NextEditWindowManager.ts
Normal file
662
extensions/vscode/src/activation/NextEditWindowManager.ts
Normal file
|
|
@ -0,0 +1,662 @@
|
|||
/* eslint-disable @typescript-eslint/naming-convention */
|
||||
import { EXTENSION_NAME } from "core/control-plane/env";
|
||||
// @ts-ignore
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import { myersDiff } from "core/diff/myers";
|
||||
import { getRenderableDiff } from "core/nextEdit/diff/diff";
|
||||
import { SyntaxHighlighter } from "core/syntaxHighlighting/SyntaxHighlighter";
|
||||
import { getThemeString } from "../util/getTheme";
|
||||
|
||||
export interface TextApplier {
|
||||
applyText(
|
||||
editor: vscode.TextEditor,
|
||||
text: string,
|
||||
position: vscode.Position,
|
||||
): Promise<boolean>;
|
||||
}
|
||||
|
||||
const SVG_CONFIG = {
|
||||
stroke: "#999998",
|
||||
strokeWidth: 1,
|
||||
textColor: "#999998",
|
||||
filter: "drop-shadow(0 2px 2px rgba(0,0,0,0.2))",
|
||||
radius: 3,
|
||||
leftMargin: 40,
|
||||
defaultText: "",
|
||||
lineSpacing: 1.2, // Line spacing multiplier
|
||||
cursorOffset: 4, // Spaces to offset from cursor
|
||||
|
||||
get fontSize() {
|
||||
return Math.ceil(
|
||||
vscode.workspace.getConfiguration("editor").get<number>("fontSize") ?? 14,
|
||||
);
|
||||
},
|
||||
get fontFamily() {
|
||||
return (
|
||||
vscode.workspace.getConfiguration("editor").get<string>("fontFamily") ||
|
||||
"helvetica"
|
||||
);
|
||||
},
|
||||
get paddingX() {
|
||||
return Math.ceil(this.getEstimatedTextWidth(" "));
|
||||
},
|
||||
get paddingY() {
|
||||
return Math.ceil(this.fontSize * 0.3);
|
||||
},
|
||||
get lineHeight() {
|
||||
return Math.ceil(this.fontSize * this.lineSpacing);
|
||||
},
|
||||
getEstimatedTextWidth(text: string): number {
|
||||
return text.length * this.fontSize * 0.6;
|
||||
},
|
||||
getTipWidth(text: string): number {
|
||||
// Find the longest line
|
||||
const lines = text.split("\n");
|
||||
const longestLine = lines.reduce(
|
||||
(longest, line) => (line.length > longest.length ? line : longest),
|
||||
"",
|
||||
);
|
||||
|
||||
return this.getEstimatedTextWidth(longestLine) + this.paddingX * 2;
|
||||
},
|
||||
getTipHeight(text: string): number {
|
||||
// Count the number of lines
|
||||
const lineCount = text.split("\n").length;
|
||||
return this.lineHeight * lineCount + this.paddingY * 2;
|
||||
},
|
||||
} as const;
|
||||
|
||||
// Command ID - can be used in package.json
|
||||
export const HIDE_TOOLTIP_COMMAND = "nextEditWindow.hideTooltips";
|
||||
export const ACCEPT_NEXT_EDIT_COMMAND = "nextEditWindow.acceptNextEdit";
|
||||
|
||||
export class NextEditWindowManager {
|
||||
private static instance: NextEditWindowManager | undefined;
|
||||
|
||||
private readonly excludedURIPrefixes = ["output:", "vscode://inline-chat"];
|
||||
private readonly hideCommand = "continue.hideNextEditWindow";
|
||||
private theme: string;
|
||||
private fontSize: number;
|
||||
private fontFamily: string;
|
||||
private syntaxHighlighter: SyntaxHighlighter;
|
||||
|
||||
// Current active decoration
|
||||
private currentDecoration: vscode.TextEditorDecorationType | null = null;
|
||||
// Track which editor has the active decoration
|
||||
private activeEditor: vscode.TextEditor | null = null;
|
||||
// Store the current tooltip text for accepting
|
||||
private currentTooltipText: string | null = null;
|
||||
|
||||
// Disposables
|
||||
private disposables: vscode.Disposable[] = [];
|
||||
|
||||
private textApplier: TextApplier | null = null;
|
||||
|
||||
private finalCursorPos: vscode.Position | null = null;
|
||||
|
||||
public static getInstance(): NextEditWindowManager {
|
||||
if (!NextEditWindowManager.instance) {
|
||||
NextEditWindowManager.instance = new NextEditWindowManager();
|
||||
}
|
||||
return NextEditWindowManager.instance;
|
||||
}
|
||||
|
||||
public static isInstantiated(): boolean {
|
||||
return !!NextEditWindowManager.instance;
|
||||
}
|
||||
|
||||
public static clearInstance(): void {
|
||||
if (NextEditWindowManager.instance) {
|
||||
NextEditWindowManager.instance.dispose();
|
||||
NextEditWindowManager.instance = undefined;
|
||||
}
|
||||
}
|
||||
|
||||
private constructor() {
|
||||
this.theme = getThemeString();
|
||||
|
||||
console.log(
|
||||
"Next Edit Theme initialized:",
|
||||
this.theme
|
||||
? `Theme exists: ${JSON.stringify(this.theme)}`
|
||||
: "Theme is undefined",
|
||||
);
|
||||
this.setupListeners();
|
||||
this.syntaxHighlighter = SyntaxHighlighter.getInstance();
|
||||
this.syntaxHighlighter.setTheme(this.theme);
|
||||
|
||||
const editorConfig = vscode.workspace.getConfiguration("editor");
|
||||
this.fontSize = editorConfig.get<number>("fontSize") ?? 14;
|
||||
this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace";
|
||||
}
|
||||
|
||||
public async setupNextEditWindowManager(
|
||||
context: vscode.ExtensionContext,
|
||||
textApplier?: TextApplier,
|
||||
) {
|
||||
await vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"nextEditWindowActive",
|
||||
false,
|
||||
);
|
||||
|
||||
const existingCommands = await vscode.commands.getCommands();
|
||||
|
||||
if (!existingCommands.includes(HIDE_TOOLTIP_COMMAND)) {
|
||||
// Register the command to hide tooltips
|
||||
const hideTooltipsCommand = vscode.commands.registerCommand(
|
||||
HIDE_TOOLTIP_COMMAND,
|
||||
async () => {
|
||||
await this.hideAllTooltips();
|
||||
},
|
||||
);
|
||||
context.subscriptions.push(hideTooltipsCommand);
|
||||
}
|
||||
|
||||
if (!existingCommands.includes(ACCEPT_NEXT_EDIT_COMMAND)) {
|
||||
// Register the command to accept next edit
|
||||
const acceptNextEditCommand = vscode.commands.registerCommand(
|
||||
ACCEPT_NEXT_EDIT_COMMAND,
|
||||
() => {
|
||||
this.acceptNextEdit();
|
||||
},
|
||||
);
|
||||
context.subscriptions.push(acceptNextEditCommand);
|
||||
}
|
||||
|
||||
// Add this class to context disposables
|
||||
context.subscriptions.push(this);
|
||||
|
||||
if (textApplier) {
|
||||
this.textApplier = textApplier;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Show a tooltip with the given text at the current cursor position
|
||||
* @param editor The active text editor
|
||||
* @param text Text to display in the tooltip
|
||||
*/
|
||||
public async showTooltip(editor: vscode.TextEditor, text: string) {
|
||||
if (!text || !this.shouldRenderTip(editor.document.uri)) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear any existing decorations first (very important to prevent overlapping)
|
||||
await this.hideAllTooltips();
|
||||
// this.dispose();
|
||||
|
||||
// Store the current tooltip text for accepting later
|
||||
this.currentTooltipText = text;
|
||||
|
||||
// Get cursor position
|
||||
const position = editor.selection.active;
|
||||
const startPos = Math.max(position.line - 5, 0);
|
||||
const endPos = Math.min(position.line + 5, editor.document.lineCount - 1);
|
||||
const originalSlice = editor.document
|
||||
.getText()
|
||||
.split("\n")
|
||||
.slice(startPos, endPos + 1)
|
||||
.join("\n");
|
||||
|
||||
// TODO: we may use a unified diff here if the file is too huge
|
||||
// TODO: compare text with the editable region slice.
|
||||
const diffLines = myersDiff(originalSlice, text);
|
||||
const diff = getRenderableDiff(diffLines);
|
||||
|
||||
this.finalCursorPos = new vscode.Position(
|
||||
startPos + diff.offset.line,
|
||||
diff.offset.character,
|
||||
);
|
||||
|
||||
// Stops the manager from rendering blank windows when there is nothing to render.
|
||||
if (diff.renderableDiff === "") {
|
||||
return;
|
||||
}
|
||||
|
||||
// Create and apply decoration with the text
|
||||
await this.renderTooltip(editor, position, diff.renderableDiff);
|
||||
await vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"nextEditWindowActive",
|
||||
true,
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Hide all tooltips in all editors
|
||||
*/
|
||||
public async hideAllTooltips() {
|
||||
console.log("hideAllTooltips");
|
||||
if (this.currentDecoration) {
|
||||
// Remove decoration from all editors to be extra safe
|
||||
vscode.window.visibleTextEditors.forEach((editor) => {
|
||||
editor.setDecorations(this.currentDecoration!, []);
|
||||
});
|
||||
|
||||
// If we know which editor had the decoration, clear it specifically
|
||||
if (this.activeEditor) {
|
||||
this.activeEditor.setDecorations(this.currentDecoration, []);
|
||||
this.activeEditor = null;
|
||||
}
|
||||
|
||||
// Dispose the decoration
|
||||
this.currentDecoration.dispose();
|
||||
this.currentDecoration = null;
|
||||
|
||||
this.disposables.forEach((d) => d.dispose());
|
||||
this.disposables = [];
|
||||
|
||||
// Clear the current tooltip text
|
||||
this.currentTooltipText = null;
|
||||
}
|
||||
|
||||
await vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"nextEditWindowActive",
|
||||
false,
|
||||
);
|
||||
|
||||
// this.dispose();
|
||||
}
|
||||
|
||||
/**
|
||||
* Accept the current next edit suggestion by inserting it at cursor position
|
||||
*/
|
||||
private async acceptNextEdit() {
|
||||
if (!this.activeEditor || !this.currentTooltipText) {
|
||||
return;
|
||||
}
|
||||
|
||||
const editor = this.activeEditor;
|
||||
const text = this.currentTooltipText;
|
||||
const position = editor.selection.active;
|
||||
|
||||
let success = false;
|
||||
if (this.textApplier) {
|
||||
success = await this.textApplier.applyText(editor, text, position);
|
||||
} else {
|
||||
// applyText already has this,
|
||||
// but we could technically have an instance of
|
||||
// NextEditWindowManager without the textApplier
|
||||
|
||||
const editableRegionStartLine = Math.max(0, position.line - 5);
|
||||
const editableRegionEndLine = Math.min(
|
||||
editor.document.lineCount - 1,
|
||||
position.line + 5,
|
||||
);
|
||||
const startPos = new vscode.Position(editableRegionStartLine, 0);
|
||||
const endPosChar = editor.document.lineAt(editableRegionEndLine).text
|
||||
.length;
|
||||
|
||||
const endPos = new vscode.Position(editableRegionEndLine, endPosChar);
|
||||
const editRange = new vscode.Range(startPos, endPos);
|
||||
|
||||
success = await editor.edit((editBuilder) => {
|
||||
editBuilder.replace(editRange, text);
|
||||
});
|
||||
}
|
||||
|
||||
if (success) {
|
||||
// Move cursor to the final position if available.
|
||||
if (this.finalCursorPos) {
|
||||
editor.selection = new vscode.Selection(
|
||||
this.finalCursorPos,
|
||||
this.finalCursorPos,
|
||||
);
|
||||
}
|
||||
await this.hideAllTooltips();
|
||||
}
|
||||
}
|
||||
|
||||
public dispose() {
|
||||
// Dispose current decoration
|
||||
if (this.currentDecoration) {
|
||||
this.currentDecoration.dispose();
|
||||
this.currentDecoration = null;
|
||||
}
|
||||
|
||||
// Dispose all other disposables
|
||||
this.disposables.forEach((d) => d.dispose());
|
||||
this.disposables = [];
|
||||
}
|
||||
|
||||
private setupListeners() {
|
||||
// Theme change listener
|
||||
vscode.workspace.onDidChangeConfiguration((e) => {
|
||||
if (
|
||||
e.affectsConfiguration("workbench.colorTheme") ||
|
||||
e.affectsConfiguration("editor.fontSize") ||
|
||||
e.affectsConfiguration("editor.fontFamily") ||
|
||||
e.affectsConfiguration("window.autoDetectColorScheme") ||
|
||||
e.affectsConfiguration("window.autoDetectHighContrast") ||
|
||||
e.affectsConfiguration("workbench.preferredDarkColorTheme") ||
|
||||
e.affectsConfiguration("workbench.preferredLightColorTheme") ||
|
||||
e.affectsConfiguration("workbench.preferredHighContrastColorTheme") ||
|
||||
e.affectsConfiguration("workbench.preferredHighContrastLightColorTheme")
|
||||
) {
|
||||
this.theme = getThemeString();
|
||||
this.syntaxHighlighter.setTheme(this.theme);
|
||||
console.log(
|
||||
"Theme updated:",
|
||||
this.theme ? "Theme exists" : "Theme is undefined",
|
||||
);
|
||||
const editorConfig = vscode.workspace.getConfiguration("editor");
|
||||
this.fontSize = editorConfig.get<number>("fontSize") ?? 14;
|
||||
this.fontFamily = editorConfig.get<string>("fontFamily") ?? "monospace";
|
||||
}
|
||||
});
|
||||
// this.disposables.push(themeListener);
|
||||
|
||||
// Listen for active color theme changes
|
||||
vscode.window.onDidChangeActiveColorTheme(() => {
|
||||
this.theme = getThemeString();
|
||||
this.syntaxHighlighter.setTheme(this.theme);
|
||||
console.log(
|
||||
"Active theme changed:",
|
||||
this.theme ? "Theme exists" : "Theme is undefined",
|
||||
);
|
||||
});
|
||||
// this.disposables.push(activeThemeListener);
|
||||
|
||||
// Listen for editor changes to clean up decorations when editor closes
|
||||
vscode.window.onDidChangeVisibleTextEditors(async () => {
|
||||
// If our active editor is no longer visible, clear decorations
|
||||
if (
|
||||
this.activeEditor &&
|
||||
!vscode.window.visibleTextEditors.includes(this.activeEditor)
|
||||
) {
|
||||
await this.hideAllTooltips();
|
||||
}
|
||||
});
|
||||
// this.disposables.push(editorCloseListener);
|
||||
|
||||
// Listen for selection changes to hide tooltip when cursor moves
|
||||
vscode.window.onDidChangeTextEditorSelection(async (e) => {
|
||||
// If the selection changed in our active editor, hide the tooltip
|
||||
if (this.activeEditor && e.textEditor === this.activeEditor) {
|
||||
await this.hideAllTooltips();
|
||||
}
|
||||
});
|
||||
// this.disposables.push(selectionListener);
|
||||
}
|
||||
|
||||
private shouldRenderTip(uri: vscode.Uri): boolean {
|
||||
const isAllowedUri =
|
||||
!this.excludedURIPrefixes.some((prefix) =>
|
||||
uri.toString().startsWith(prefix),
|
||||
) && uri.scheme !== "comment";
|
||||
|
||||
const isEnabled =
|
||||
!!vscode.workspace
|
||||
.getConfiguration(EXTENSION_NAME)
|
||||
.get<boolean>("showInlineTip") === true;
|
||||
|
||||
return isAllowedUri && isEnabled;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create an SVG with the given text, supporting multiple lines
|
||||
*/
|
||||
private async createSvgTooltip(
|
||||
text: string,
|
||||
): Promise<
|
||||
| { uri: vscode.Uri; dimensions: { width: number; height: number } }
|
||||
| undefined
|
||||
> {
|
||||
console.log("createSvgTooltip");
|
||||
// const baseTextConfig = {
|
||||
// "font-family": SVG_CONFIG.fontFamily,
|
||||
// "font-size": SVG_CONFIG.fontSize,
|
||||
// fill: this.theme.colors["editor.foreground"],
|
||||
// };
|
||||
|
||||
try {
|
||||
const tipWidth = SVG_CONFIG.getTipWidth(text);
|
||||
const tipHeight = SVG_CONFIG.getTipHeight(text);
|
||||
const dimensions = {
|
||||
width: tipWidth,
|
||||
height: tipHeight,
|
||||
};
|
||||
|
||||
// const lines = text.split("\n");
|
||||
// const globalIndent =
|
||||
// lines.length > 0 ? (lines[0].match(/^[ \t]*/) || [""])[0].length : 0;
|
||||
|
||||
// const syntaxHighlighter = SyntaxHighlighter.getInstance({
|
||||
// theme: "one-dark-pro",
|
||||
// });
|
||||
|
||||
// await syntaxHighlighter.init();
|
||||
|
||||
const uri = await this.syntaxHighlighter.getDataUri(
|
||||
text,
|
||||
"typescript",
|
||||
this.fontSize,
|
||||
this.fontFamily,
|
||||
dimensions,
|
||||
SVG_CONFIG.lineHeight,
|
||||
{
|
||||
imageType: "svg",
|
||||
},
|
||||
);
|
||||
|
||||
// console.log(dimensions);
|
||||
|
||||
return {
|
||||
uri: vscode.Uri.parse(uri),
|
||||
dimensions,
|
||||
};
|
||||
} catch (error) {
|
||||
console.error("Error creating SVG tooltip:", error);
|
||||
return undefined;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a decoration type with SVG content
|
||||
*/
|
||||
private async createSvgDecoration(
|
||||
text: string,
|
||||
): Promise<vscode.TextEditorDecorationType | undefined> {
|
||||
console.log("createSvgDecoration");
|
||||
console.log(text);
|
||||
const uriAndDimensions = await this.createSvgTooltip(text);
|
||||
if (!uriAndDimensions) {
|
||||
return undefined;
|
||||
}
|
||||
|
||||
const { uri, dimensions } = uriAndDimensions;
|
||||
|
||||
// Use theme or fallback
|
||||
// const backgroundColour = this.theme.colors["editor.background"];
|
||||
// const tipWidth = SVG_CONFIG.getTipWidth(text);
|
||||
// const tipHeight = SVG_CONFIG.getTipHeight(text);
|
||||
const tipWidth = dimensions.width;
|
||||
const tipHeight = dimensions.height;
|
||||
|
||||
return vscode.window.createTextEditorDecorationType({
|
||||
after: {
|
||||
contentIconPath: uri,
|
||||
// border: `;box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px ${backgroundColour};
|
||||
// border-radius: ${SVG_CONFIG.radius}px;
|
||||
// filter: ${SVG_CONFIG.filter}`,
|
||||
// width: `${tipWidth}px`,
|
||||
// height: `${tipHeight}px`,
|
||||
// border: `transparent; position: absolute; z-index: 1000;
|
||||
// box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke},
|
||||
// inset 0 0 0 ${tipHeight}px ${backgroundColour};
|
||||
// border-radius: ${SVG_CONFIG.radius}px;
|
||||
// filter: ${SVG_CONFIG.filter};
|
||||
// margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`,
|
||||
border: `transparent; position: absolute; z-index: 1000;
|
||||
box-shadow: inset 0 0 0 ${SVG_CONFIG.strokeWidth}px ${SVG_CONFIG.stroke}, inset 0 0 0 ${tipHeight}px;
|
||||
filter: ${SVG_CONFIG.filter};
|
||||
border-radius: ${SVG_CONFIG.radius}px;
|
||||
margin-left: ${SVG_CONFIG.cursorOffset * 8}px;`,
|
||||
// border: `solid 1px white; position: absolute; z-index: 1000;
|
||||
// margin-left: ${SVG_CONFIG.cursorOffset * 8}px;
|
||||
// margin-top: 0em;`,
|
||||
// border: `solid 1px white; position: absolute; z-index: 1000;
|
||||
// margin: 0em; padding: 0em;
|
||||
// margin-left: ${SVG_CONFIG.cursorOffset * 8}px;
|
||||
// margin-top: 0em;`,
|
||||
width: `${tipWidth}px`,
|
||||
height: `${tipHeight}px`,
|
||||
// textDecoration: `none; transform: translateY(-100%);`,
|
||||
},
|
||||
// Set a negative margin to make the decoration float if it starts to displace text.
|
||||
// Also use absolute positioning.
|
||||
rangeBehavior: vscode.DecorationRangeBehavior.ClosedClosed,
|
||||
});
|
||||
}
|
||||
|
||||
private buildHideTooltipHoverMsg() {
|
||||
const hoverMarkdown = new vscode.MarkdownString(
|
||||
`[Dismiss](command:${HIDE_TOOLTIP_COMMAND}) | [Accept (Ctrl+Space, Tab)](command:${ACCEPT_NEXT_EDIT_COMMAND})`,
|
||||
);
|
||||
|
||||
hoverMarkdown.isTrusted = true;
|
||||
hoverMarkdown.supportHtml = true;
|
||||
return hoverMarkdown;
|
||||
}
|
||||
|
||||
private isValidRange(
|
||||
editor: vscode.TextEditor,
|
||||
range: vscode.Range,
|
||||
): boolean {
|
||||
const doc = editor.document;
|
||||
|
||||
// Check if line numbers are valid
|
||||
if (range.start.line < 0 || range.start.line >= doc.lineCount) {
|
||||
console.log(
|
||||
"Invalid start line:",
|
||||
range.start.line,
|
||||
"doc lines:",
|
||||
doc.lineCount,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (range.end.line < 0 || range.end.line >= doc.lineCount) {
|
||||
console.log(
|
||||
"Invalid end line:",
|
||||
range.end.line,
|
||||
"doc lines:",
|
||||
doc.lineCount,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if character positions are valid
|
||||
const startLine = doc.lineAt(range.start.line);
|
||||
const endLine = doc.lineAt(range.end.line);
|
||||
|
||||
if (
|
||||
range.start.character < 0 ||
|
||||
range.start.character > startLine.text.length
|
||||
) {
|
||||
console.log(
|
||||
"Invalid start character:",
|
||||
range.start.character,
|
||||
"line length:",
|
||||
startLine.text.length,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
if (range.end.character < 0 || range.end.character > endLine.text.length) {
|
||||
console.log(
|
||||
"Invalid end character:",
|
||||
range.end.character,
|
||||
"line length:",
|
||||
endLine.text.length,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculate a position to the right of the cursor with the specified offset
|
||||
*/
|
||||
private getOffsetPosition(
|
||||
editor: vscode.TextEditor,
|
||||
position: vscode.Position,
|
||||
): vscode.Position {
|
||||
// Create a position that's offset spaces to the right of the cursor
|
||||
// const offsetChar = position.character + SVG_CONFIG.cursorOffset;
|
||||
// return new vscode.Position(position.line, offsetChar);
|
||||
|
||||
const line = editor.document.lineAt(position.line);
|
||||
const offsetChar = Math.min(
|
||||
position.character + SVG_CONFIG.cursorOffset,
|
||||
line.text.length,
|
||||
);
|
||||
return new vscode.Position(position.line, offsetChar);
|
||||
}
|
||||
|
||||
/**
|
||||
* Render a tooltip with the given text at the specified position
|
||||
*/
|
||||
private async renderTooltip(
|
||||
editor: vscode.TextEditor,
|
||||
position: vscode.Position,
|
||||
text: string,
|
||||
) {
|
||||
console.log("renderTooltip");
|
||||
// Capture document version to detect changes
|
||||
const docVersion = editor.document.version;
|
||||
|
||||
// Create a new decoration with the text
|
||||
const decoration = await this.createSvgDecoration(text);
|
||||
if (!decoration) {
|
||||
console.error("Failed to create decoration for text:", text);
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if document changed during async operation
|
||||
if (editor.document.version !== docVersion) {
|
||||
console.log("Document changed during decoration creation, aborting");
|
||||
// decoration.dispose();
|
||||
// return;
|
||||
}
|
||||
|
||||
// Store the decoration and editor
|
||||
await this.hideAllTooltips();
|
||||
this.currentDecoration = decoration;
|
||||
this.activeEditor = editor;
|
||||
|
||||
// console.log(decoration);
|
||||
|
||||
// Get the position with offset
|
||||
const offsetPosition = this.getOffsetPosition(editor, position);
|
||||
const range = new vscode.Range(offsetPosition, offsetPosition);
|
||||
|
||||
// Validate the range before applying
|
||||
if (!this.isValidRange(editor, range)) {
|
||||
console.error("Invalid range detected, skipping decoration");
|
||||
return;
|
||||
}
|
||||
|
||||
// Apply the decoration at the offset position
|
||||
editor.setDecorations(this.currentDecoration, [
|
||||
{
|
||||
range: new vscode.Range(offsetPosition, offsetPosition),
|
||||
hoverMessage: [this.buildHideTooltipHoverMsg()],
|
||||
},
|
||||
]);
|
||||
}
|
||||
}
|
||||
|
||||
export default async function setupNextEditWindowManager(
|
||||
context: vscode.ExtensionContext,
|
||||
textApplier?: TextApplier,
|
||||
) {
|
||||
await NextEditWindowManager.getInstance().setupNextEditWindowManager(
|
||||
context,
|
||||
textApplier,
|
||||
);
|
||||
}
|
||||
|
|
@ -15,6 +15,8 @@ import { handleLLMError } from "../util/errorHandling";
|
|||
import { VsCodeIde } from "../VsCodeIde";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
|
||||
import { NextEditProvider } from "core/nextEdit/NextEditProvider";
|
||||
import { NextEditWindowManager } from "../activation/NextEditWindowManager";
|
||||
import { getDefinitionsFromLsp } from "./lsp";
|
||||
import { RecentlyEditedTracker } from "./recentlyEdited";
|
||||
import { RecentlyVisitedRangesService } from "./RecentlyVisitedRangesService";
|
||||
|
|
@ -54,10 +56,20 @@ export class ContinueCompletionProvider
|
|||
}
|
||||
|
||||
private completionProvider: CompletionProvider;
|
||||
// private nextEditProvider: NextEditProvider;
|
||||
private nextEditProvider: NextEditProvider;
|
||||
public recentlyVisitedRanges: RecentlyVisitedRangesService;
|
||||
public recentlyEditedTracker: RecentlyEditedTracker;
|
||||
|
||||
private isNextEditActive: boolean = false;
|
||||
|
||||
public activateNextEdit() {
|
||||
this.isNextEditActive = true;
|
||||
}
|
||||
|
||||
public deactivateNextEdit() {
|
||||
this.isNextEditActive = false;
|
||||
}
|
||||
|
||||
constructor(
|
||||
private readonly configHandler: ConfigHandler,
|
||||
private readonly ide: VsCodeIde,
|
||||
|
|
@ -81,16 +93,15 @@ export class ContinueCompletionProvider
|
|||
);
|
||||
// NOTE: Only turn it on locally when testing (for review purposes).
|
||||
// TODO: revert back
|
||||
// if (IS_NEXT_EDIT_ACTIVE) {
|
||||
// this.nextEditProvider = new NextEditProvider(
|
||||
// this.configHandler,
|
||||
// this.ide,
|
||||
// getAutocompleteModel,
|
||||
// this.onError.bind(this),
|
||||
// getDefinitionsFromLsp,
|
||||
// "fineTuned",
|
||||
// );
|
||||
// }
|
||||
this.nextEditProvider = NextEditProvider.initialize(
|
||||
this.configHandler,
|
||||
this.ide,
|
||||
getAutocompleteModel,
|
||||
this.onError.bind(this),
|
||||
getDefinitionsFromLsp,
|
||||
"fineTuned",
|
||||
);
|
||||
|
||||
this.recentlyVisitedRanges = new RecentlyVisitedRangesService(ide);
|
||||
}
|
||||
|
||||
|
|
@ -214,33 +225,22 @@ export class ContinueCompletionProvider
|
|||
};
|
||||
|
||||
setupStatusBar(undefined, true);
|
||||
// TODO: revert back
|
||||
const outcome =
|
||||
await this.completionProvider.provideInlineCompletionItems(
|
||||
input,
|
||||
signal,
|
||||
wasManuallyTriggered,
|
||||
);
|
||||
|
||||
const outcome = this.isNextEditActive
|
||||
? await this.nextEditProvider.provideInlineCompletionItems(
|
||||
input,
|
||||
signal,
|
||||
)
|
||||
: await this.completionProvider.provideInlineCompletionItems(
|
||||
input,
|
||||
signal,
|
||||
wasManuallyTriggered,
|
||||
);
|
||||
|
||||
if (!outcome || !outcome.completion) {
|
||||
return null;
|
||||
}
|
||||
|
||||
// NOTE: This is a very rudimentary check to see if we can call the next edit service.
|
||||
// In the future we will have to figure out how to call this more gracefully.
|
||||
// TODO: revert back
|
||||
// if (this.nextEditProvider) {
|
||||
// const nextEditOutcome =
|
||||
// await this.nextEditProvider?.provideInlineCompletionItems(
|
||||
// input,
|
||||
// signal,
|
||||
// );
|
||||
|
||||
// if (nextEditOutcome && nextEditOutcome.completion) {
|
||||
// outcome.completion = nextEditOutcome.completion;
|
||||
// }
|
||||
// }
|
||||
|
||||
// VS Code displays dependent on selectedCompletionInfo (their docstring below)
|
||||
// We should first always make sure we have a valid completion, but if it goes wrong we
|
||||
// want telemetry to be correct
|
||||
|
|
@ -325,7 +325,20 @@ export class ContinueCompletionProvider
|
|||
);
|
||||
|
||||
(completionItem as any).completeBracketPairs = true;
|
||||
return [completionItem];
|
||||
|
||||
if (this.isNextEditActive) {
|
||||
const editor = vscode.window.activeTextEditor;
|
||||
if (editor && NextEditWindowManager.isInstantiated()) {
|
||||
await NextEditWindowManager.getInstance().showTooltip(
|
||||
editor,
|
||||
completionText,
|
||||
);
|
||||
}
|
||||
|
||||
return undefined;
|
||||
} else {
|
||||
return [completionItem];
|
||||
}
|
||||
} finally {
|
||||
stopStatusBarLoading();
|
||||
}
|
||||
|
|
|
|||
|
|
@ -128,6 +128,8 @@ export class VsCodeExtension {
|
|||
configHandlerPromise,
|
||||
this.workOsAuthProvider,
|
||||
this.editDecorationManager,
|
||||
context,
|
||||
this,
|
||||
);
|
||||
|
||||
this.core = new Core(inProcessMessenger, this.ide);
|
||||
|
|
@ -477,4 +479,12 @@ export class VsCodeExtension {
|
|||
registerCustomContextProvider(contextProvider: IContextProvider) {
|
||||
this.configHandler.registerCustomContextProvider(contextProvider);
|
||||
}
|
||||
|
||||
public activateNextEdit() {
|
||||
this.completionProvider.activateNextEdit();
|
||||
}
|
||||
|
||||
public deactivateNextEdit() {
|
||||
this.completionProvider.deactivateNextEdit();
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -17,6 +17,9 @@ import {
|
|||
import { stripImages } from "core/util/messageContent";
|
||||
import * as vscode from "vscode";
|
||||
|
||||
import setupNextEditWindowManager, {
|
||||
NextEditWindowManager,
|
||||
} from "../activation/NextEditWindowManager";
|
||||
import { ApplyManager } from "../apply";
|
||||
import { VerticalDiffManager } from "../diff/vertical/manager";
|
||||
import { addCurrentSelectionToEdit } from "../quickEdit/AddCurrentSelection";
|
||||
|
|
@ -30,6 +33,7 @@ import { showTutorial } from "../util/tutorial";
|
|||
import { getExtensionUri } from "../util/vscode";
|
||||
import { VsCodeIde } from "../VsCodeIde";
|
||||
import { VsCodeWebviewProtocol } from "../webviewProtocol";
|
||||
import { VsCodeExtension } from "./VsCodeExtension";
|
||||
|
||||
type ToIdeOrWebviewFromCoreProtocol = ToIdeFromCoreProtocol &
|
||||
ToWebviewFromCoreProtocol;
|
||||
|
|
@ -82,6 +86,8 @@ export class VsCodeMessenger {
|
|||
private readonly configHandlerPromise: Promise<ConfigHandler>,
|
||||
private readonly workOsAuthProvider: WorkOsAuthProvider,
|
||||
private readonly editDecorationManager: EditDecorationManager,
|
||||
private readonly context: vscode.ExtensionContext,
|
||||
private readonly vsCodeExtension: VsCodeExtension,
|
||||
) {
|
||||
/** WEBVIEW ONLY LISTENERS **/
|
||||
this.onWebview("showFile", (msg) => {
|
||||
|
|
@ -249,6 +255,49 @@ export class VsCodeMessenger {
|
|||
editDecorationManager.clear();
|
||||
});
|
||||
|
||||
this.onWebview("optInNextEditFeature", async (msg) => {
|
||||
if (msg.data.optIn) {
|
||||
// Set up next edit window manager only for Continue team members
|
||||
await setupNextEditWindowManager(context, {
|
||||
applyText: async (editor, diff, position) => {
|
||||
const editableRegionStartLine = Math.max(0, position.line - 5);
|
||||
const editableRegionEndLine = Math.min(
|
||||
editor.document.lineCount - 1,
|
||||
position.line + 5,
|
||||
);
|
||||
const startPos = new vscode.Position(editableRegionStartLine, 0);
|
||||
const endPosChar = editor.document.lineAt(editableRegionEndLine)
|
||||
.text.length;
|
||||
|
||||
const endPos = new vscode.Position(
|
||||
editableRegionEndLine,
|
||||
endPosChar,
|
||||
);
|
||||
const editRange = new vscode.Range(startPos, endPos);
|
||||
|
||||
return await editor.edit((editBuilder) => {
|
||||
editBuilder.replace(editRange, diff);
|
||||
});
|
||||
},
|
||||
});
|
||||
|
||||
this.vsCodeExtension.activateNextEdit();
|
||||
await vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"nextEditWindowActive",
|
||||
false,
|
||||
);
|
||||
} else {
|
||||
NextEditWindowManager.clearInstance();
|
||||
this.vsCodeExtension.deactivateNextEdit();
|
||||
await vscode.commands.executeCommand(
|
||||
"setContext",
|
||||
"nextEditWindowActive",
|
||||
false,
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
/** PASS THROUGH FROM WEBVIEW TO CORE AND BACK **/
|
||||
WEBVIEW_TO_CORE_PASS_THROUGH.forEach((messageType) => {
|
||||
this.onWebview(messageType, async (msg) => {
|
||||
|
|
|
|||
|
|
@ -45,6 +45,14 @@ function parseThemeString(themeString: string | undefined): any {
|
|||
return JSON.parse(themeString ?? "{}");
|
||||
}
|
||||
|
||||
export function getThemeString(): string {
|
||||
const workbenchConfig = vscode.workspace.getConfiguration();
|
||||
const themeString =
|
||||
workbenchConfig.get<string>("workbench.colorTheme") ??
|
||||
"Default Dark Modern";
|
||||
return themeString;
|
||||
}
|
||||
|
||||
export function getTheme() {
|
||||
let currentTheme: string | undefined = undefined;
|
||||
// Get color theme from settings
|
||||
|
|
|
|||
5
gui/package-lock.json
generated
5
gui/package-lock.json
generated
|
|
@ -36,7 +36,6 @@
|
|||
"minisearch": "^7.0.2",
|
||||
"mustache": "^4.2.0",
|
||||
"posthog-js": "^1.130.1",
|
||||
"prismjs": "^1.29.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-error-boundary": "^4.0.11",
|
||||
|
|
@ -116,7 +115,7 @@
|
|||
"@continuedev/config-yaml": "file:../packages/config-yaml",
|
||||
"@continuedev/fetch": "^1.0.13",
|
||||
"@continuedev/llm-info": "^1.0.8",
|
||||
"@continuedev/openai-adapters": "^1.0.32",
|
||||
"@continuedev/openai-adapters": "file:../packages/openai-adapters",
|
||||
"@modelcontextprotocol/sdk": "^1.12.0",
|
||||
"@mozilla/readability": "^0.5.0",
|
||||
"@octokit/rest": "^20.1.1",
|
||||
|
|
@ -162,6 +161,7 @@
|
|||
"quick-lru": "^7.0.0",
|
||||
"replicate": "^0.26.0",
|
||||
"request": "^2.88.2",
|
||||
"satori": "^0.15.2",
|
||||
"socket.io-client": "^4.7.3",
|
||||
"sqlite": "^5.1.1",
|
||||
"sqlite3": "^5.1.7",
|
||||
|
|
@ -205,6 +205,7 @@
|
|||
"myers-diff": "^2.1.0",
|
||||
"onnxruntime-common": "1.14.0",
|
||||
"onnxruntime-web": "1.14.0",
|
||||
"shiki": "^3.6.0",
|
||||
"ts-jest": "^29.1.1",
|
||||
"typescript": "^5.6.3",
|
||||
"vitest": "^3.1.4"
|
||||
|
|
|
|||
|
|
@ -45,7 +45,6 @@
|
|||
"minisearch": "^7.0.2",
|
||||
"mustache": "^4.2.0",
|
||||
"posthog-js": "^1.130.1",
|
||||
"prismjs": "^1.29.0",
|
||||
"react": "^18.2.0",
|
||||
"react-dom": "^18.2.0",
|
||||
"react-error-boundary": "^4.0.11",
|
||||
|
|
|
|||
|
|
@ -1,7 +1,4 @@
|
|||
import { ArrowPathIcon } from "@heroicons/react/24/outline";
|
||||
import { useState } from "react";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { cn } from "../../util/cn";
|
||||
import { AssistantOption } from "./AssistantOption";
|
||||
|
||||
interface AssistantOptionsProps {
|
||||
|
|
@ -13,30 +10,13 @@ export function AssistantOptions({
|
|||
selectedProfileId,
|
||||
onClose,
|
||||
}: AssistantOptionsProps) {
|
||||
const [loading, setLoading] = useState(false);
|
||||
const { profiles, refreshProfiles } = useAuth();
|
||||
const { profiles } = useAuth();
|
||||
|
||||
return (
|
||||
<>
|
||||
{/* Assistants Section Header */}
|
||||
<div className="flex gap-1.5 px-3 pb-1 pt-2">
|
||||
<label className="text-vsc-foreground font-semibold">Assistants</label>
|
||||
<div
|
||||
className="flex cursor-pointer flex-row items-center gap-1 hover:brightness-125"
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
setLoading(true);
|
||||
await refreshProfiles();
|
||||
setLoading(false);
|
||||
}}
|
||||
>
|
||||
<ArrowPathIcon
|
||||
className={cn(
|
||||
"text-description h-2.5 w-2.5",
|
||||
loading && "animate-spin-slow",
|
||||
)}
|
||||
/>
|
||||
</div>
|
||||
<div className="flex cursor-pointer flex-row items-center gap-1 hover:brightness-125"></div>
|
||||
</div>
|
||||
|
||||
<div className="thin-scrollbar flex max-h-[300px] flex-col overflow-y-auto">
|
||||
|
|
|
|||
|
|
@ -1,6 +1,9 @@
|
|||
import { ChevronDownIcon } from "@heroicons/react/24/outline";
|
||||
import { ArrowPathIcon } from "@heroicons/react/24/solid";
|
||||
import type { ProfileDescription } from "core/config/ConfigHandler";
|
||||
import { useAppSelector } from "../../redux/hooks";
|
||||
import { fontSize } from "../../util";
|
||||
import { cn } from "../../util/cn";
|
||||
import { useLump } from "../mainInput/Lump/LumpContext";
|
||||
import { ListboxButton } from "../ui";
|
||||
import { AssistantIcon } from "./AssistantIcon";
|
||||
|
|
@ -13,6 +16,8 @@ export function SelectedAssistantButton({
|
|||
selectedProfile,
|
||||
}: SelectedAssistantButtonProps) {
|
||||
const { isToolbarExpanded } = useLump();
|
||||
const configLoading = useAppSelector((store) => store.config.loading);
|
||||
|
||||
return (
|
||||
<ListboxButton
|
||||
data-testid="assistant-select-button"
|
||||
|
|
@ -20,14 +25,28 @@ export function SelectedAssistantButton({
|
|||
style={{ fontSize: fontSize(-3) }}
|
||||
>
|
||||
<div className="flex flex-row items-center gap-1.5">
|
||||
<div className="h-3 w-3 flex-shrink-0 select-none">
|
||||
<AssistantIcon size={3} assistant={selectedProfile} />
|
||||
</div>
|
||||
<span
|
||||
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
>
|
||||
{selectedProfile.title}
|
||||
</span>
|
||||
{configLoading ? (
|
||||
<span className="text-description flex flex-row items-center">
|
||||
<ArrowPathIcon
|
||||
className={cn(
|
||||
"text-description mr-1.5 h-3 w-3",
|
||||
configLoading && "animate-spin-slow",
|
||||
)}
|
||||
/>
|
||||
Loading
|
||||
</span>
|
||||
) : (
|
||||
<>
|
||||
<div className="h-3 w-3 flex-shrink-0 select-none">
|
||||
<AssistantIcon size={3} assistant={selectedProfile} />
|
||||
</div>
|
||||
<span
|
||||
className={`line-clamp-1 select-none break-all ${isToolbarExpanded ? "xs:hidden sm:line-clamp-1" : ""}`}
|
||||
>
|
||||
{selectedProfile.title}
|
||||
</span>
|
||||
</>
|
||||
)}
|
||||
</div>
|
||||
<ChevronDownIcon
|
||||
className="h-2 w-2 flex-shrink-0 select-none"
|
||||
|
|
|
|||
|
|
@ -1,4 +1,4 @@
|
|||
import { PlusIcon } from "@heroicons/react/24/outline";
|
||||
import { ArrowPathIcon, PlusIcon } from "@heroicons/react/24/outline";
|
||||
import { isOnPremSession } from "core/control-plane/AuthTypes";
|
||||
import { useContext, useEffect, useRef } from "react";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
|
|
@ -9,6 +9,7 @@ import {
|
|||
setSelectedProfile,
|
||||
} from "../../redux/slices/profilesSlice";
|
||||
import { getMetaKeyLabel, isMetaEquivalentKeyPressed } from "../../util";
|
||||
import { cn } from "../../util/cn";
|
||||
import { useLump } from "../mainInput/Lump/LumpContext";
|
||||
import {
|
||||
Listbox,
|
||||
|
|
@ -28,8 +29,15 @@ export function AssistantAndOrgListbox() {
|
|||
const currentOrg = useAppSelector(selectCurrentOrg);
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { isToolbarExpanded } = useLump();
|
||||
const { profiles, selectedProfile, session, login, organizations } =
|
||||
useAuth();
|
||||
const {
|
||||
profiles,
|
||||
selectedProfile,
|
||||
session,
|
||||
login,
|
||||
organizations,
|
||||
refreshProfiles,
|
||||
} = useAuth();
|
||||
const configLoading = useAppSelector((store) => store.config.loading);
|
||||
const smallFont = useFontSize(-3);
|
||||
const tinyFont = useFontSize(-4);
|
||||
const shouldRenderOrgInfo =
|
||||
|
|
@ -152,6 +160,30 @@ export function AssistantAndOrgListbox() {
|
|||
</span>
|
||||
</ListboxOption>
|
||||
|
||||
<ListboxOption
|
||||
value="new-assistant"
|
||||
fontSizeModifier={-2}
|
||||
className="border-border border-b px-2 py-1.5"
|
||||
onClick={session ? onNewAssistant : () => login(false)}
|
||||
>
|
||||
<span
|
||||
className="text-description flex flex-row items-center"
|
||||
style={{ fontSize: tinyFont }}
|
||||
onClick={async (e) => {
|
||||
e.stopPropagation();
|
||||
await refreshProfiles();
|
||||
}}
|
||||
>
|
||||
<ArrowPathIcon
|
||||
className={cn(
|
||||
"mr-1 h-3 w-3",
|
||||
configLoading && "animate-spin-slow",
|
||||
)}
|
||||
/>
|
||||
Reload config
|
||||
</span>
|
||||
</ListboxOption>
|
||||
|
||||
<AccountOption onClose={close} />
|
||||
|
||||
<div
|
||||
|
|
|
|||
|
|
@ -4,6 +4,7 @@ import { useContext } from "react";
|
|||
import { Button, SecondaryButton, vscButtonBackground } from ".";
|
||||
import { IdeMessengerContext } from "../context/IdeMessenger";
|
||||
import { fontSize } from "../util";
|
||||
import { setLocalStorage } from "../util/localStorage";
|
||||
import { Listbox, ListboxButton, ListboxOptions, Transition } from "./ui";
|
||||
|
||||
interface ProgressBarProps {
|
||||
|
|
@ -79,6 +80,15 @@ export default function FreeTrialButton({
|
|||
}: FreeTrialButtonProps) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
|
||||
const onExitFreeTrial = async () => {
|
||||
setLocalStorage("hasExitedFreeTrial", true);
|
||||
|
||||
await ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "setup-models",
|
||||
orgSlug: undefined,
|
||||
});
|
||||
};
|
||||
|
||||
return (
|
||||
<Listbox>
|
||||
<div className="relative">
|
||||
|
|
@ -134,15 +144,7 @@ export default function FreeTrialButton({
|
|||
)}
|
||||
|
||||
<div className="mt-4 flex gap-2">
|
||||
<SecondaryButton
|
||||
className="flex-1"
|
||||
onClick={async () => {
|
||||
await ideMessenger.request("controlPlane/openUrl", {
|
||||
path: "setup-models",
|
||||
orgSlug: undefined,
|
||||
});
|
||||
}}
|
||||
>
|
||||
<SecondaryButton className="flex-1" onClick={onExitFreeTrial}>
|
||||
Exit trial
|
||||
</SecondaryButton>
|
||||
<Button
|
||||
|
|
|
|||
|
|
@ -24,6 +24,7 @@ import { ToolsSectionTooltip } from "../sections/tool-policies/ToolPoliciesSecti
|
|||
|
||||
import { usesFreeTrialApiKey } from "core/config/usesFreeTrialApiKey";
|
||||
import type { FreeTrialStatus } from "core/control-plane/client";
|
||||
import { getLocalStorage } from "../../../../util/localStorage";
|
||||
import { AssistantAndOrgListbox } from "../../../AssistantAndOrgListbox";
|
||||
|
||||
interface BlockSettingsToolbarIcon {
|
||||
|
|
@ -151,7 +152,8 @@ export function BlockSettingsTopToolbar() {
|
|||
|
||||
const [freeTrialStatus, setFreeTrialStatus] =
|
||||
useState<FreeTrialStatus | null>(null);
|
||||
const isUsingFreeTrial = usesFreeTrialApiKey(config);
|
||||
const hasExitedFreeTrial = getLocalStorage("hasExitedFreeTrial");
|
||||
const isUsingFreeTrial = usesFreeTrialApiKey(config) && !hasExitedFreeTrial;
|
||||
|
||||
useEffect(() => {
|
||||
const fetchFreeTrialStatus = () => {
|
||||
|
|
|
|||
|
|
@ -12,6 +12,7 @@ import React, {
|
|||
} from "react";
|
||||
import { useWebviewListener } from "../hooks/useWebviewListener";
|
||||
import { useAppDispatch, useAppSelector } from "../redux/hooks";
|
||||
import { setConfigLoading } from "../redux/slices/configSlice";
|
||||
import {
|
||||
selectCurrentOrg,
|
||||
selectSelectedProfile,
|
||||
|
|
@ -94,17 +95,21 @@ export const AuthProvider: React.FC<{ children: React.ReactNode }> = ({
|
|||
"sessionUpdate",
|
||||
async (data) => {
|
||||
setSession(data.sessionInfo);
|
||||
void refreshProfiles();
|
||||
},
|
||||
[],
|
||||
);
|
||||
|
||||
const refreshProfiles = useCallback(async () => {
|
||||
try {
|
||||
dispatch(setConfigLoading(true));
|
||||
await ideMessenger.request("config/refreshProfiles", undefined);
|
||||
ideMessenger.post("showToast", ["info", "Config refreshed"]);
|
||||
} catch (e) {
|
||||
console.error("Failed to refresh profiles", e);
|
||||
ideMessenger.post("showToast", ["error", "Failed to refresh config"]);
|
||||
} finally {
|
||||
dispatch(setConfigLoading(false));
|
||||
}
|
||||
}, [ideMessenger]);
|
||||
|
||||
|
|
|
|||
|
|
@ -5,7 +5,7 @@ import { EDIT_MODE_STREAM_ID } from "core/edit/constants";
|
|||
import { FromCoreProtocol } from "core/protocol";
|
||||
import { useAppDispatch, useAppSelector } from "../redux/hooks";
|
||||
import { selectCurrentToolCallApplyState } from "../redux/selectors/selectCurrentToolCall";
|
||||
import { setConfigResult } from "../redux/slices/configSlice";
|
||||
import { setConfigLoading, setConfigResult } from "../redux/slices/configSlice";
|
||||
import {
|
||||
setLastNonEditSessionEmpty,
|
||||
updateEditStateApplyState,
|
||||
|
|
@ -100,6 +100,7 @@ function ParallelListeners() {
|
|||
|
||||
const initialLoadAuthAndConfig = useCallback(
|
||||
async (initial: boolean) => {
|
||||
dispatch(setConfigLoading(true));
|
||||
const result = await ideMessenger.request(
|
||||
"config/getSerializedProfileInfo",
|
||||
undefined,
|
||||
|
|
@ -107,6 +108,7 @@ function ParallelListeners() {
|
|||
if (result.status === "success") {
|
||||
await handleConfigUpdate(initial, result.content);
|
||||
}
|
||||
dispatch(setConfigLoading(false));
|
||||
},
|
||||
[ideMessenger, handleConfigUpdate],
|
||||
);
|
||||
|
|
|
|||
62
gui/src/pages/config/ContinueFeaturesMenu.tsx
Normal file
62
gui/src/pages/config/ContinueFeaturesMenu.tsx
Normal file
|
|
@ -0,0 +1,62 @@
|
|||
import { SharedConfigSchema } from "core/config/sharedConfig";
|
||||
import { HubSessionInfo } from "core/control-plane/AuthTypes";
|
||||
import { useContext, useEffect } from "react";
|
||||
import ToggleSwitch from "../../components/gui/Switch";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
|
||||
interface ContinueFeaturesMenuProps {
|
||||
optInNextEditFeature: boolean;
|
||||
handleUpdate: (sharedConfig: SharedConfigSchema) => void;
|
||||
}
|
||||
|
||||
export function ContinueFeaturesMenu({
|
||||
optInNextEditFeature,
|
||||
handleUpdate,
|
||||
}: ContinueFeaturesMenuProps) {
|
||||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const { session } = useAuth();
|
||||
useEffect(() => {
|
||||
// Only run this effect when both optInNextEditFeature is true and session is available.
|
||||
// This still sets up the next edit window manager when the user leaves the setting on
|
||||
// before exiting vscode.
|
||||
if (optInNextEditFeature && session) {
|
||||
const continueEmail = (session as HubSessionInfo)?.account?.id ?? null;
|
||||
if (continueEmail) {
|
||||
ideMessenger.post("optInNextEditFeature", {
|
||||
email: continueEmail,
|
||||
optIn: true,
|
||||
});
|
||||
}
|
||||
}
|
||||
}, []);
|
||||
|
||||
const handleOptInToggle = (value: boolean) => {
|
||||
handleUpdate({
|
||||
optInNextEditFeature: value,
|
||||
});
|
||||
// Send message to VSCode extension with the email
|
||||
const continueEmail = (session as HubSessionInfo)?.account?.id ?? null;
|
||||
if (continueEmail) {
|
||||
ideMessenger.post("optInNextEditFeature", {
|
||||
email: continueEmail,
|
||||
optIn: value,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return (
|
||||
<div className="flex w-full flex-col gap-y-4">
|
||||
<div className="my-2 text-center text-xs font-medium text-slate-400">
|
||||
🚧 INTERNAL SETTINGS 🚧
|
||||
</div>
|
||||
<div className="w-full">
|
||||
<ToggleSwitch
|
||||
isToggled={optInNextEditFeature}
|
||||
onToggle={() => handleOptInToggle(!optInNextEditFeature)}
|
||||
text="Enable Next Edit Over Autocomplete"
|
||||
/>
|
||||
</div>
|
||||
</div>
|
||||
);
|
||||
}
|
||||
|
|
@ -8,6 +8,7 @@ import {
|
|||
SharedConfigSchema,
|
||||
modifyAnyConfigWithSharedConfig,
|
||||
} from "core/config/sharedConfig";
|
||||
import { HubSessionInfo } from "core/control-plane/AuthTypes";
|
||||
import { useContext, useEffect, useState } from "react";
|
||||
import { Input } from "../../components";
|
||||
import NumberInput from "../../components/gui/NumberInput";
|
||||
|
|
@ -15,10 +16,12 @@ import { Select } from "../../components/gui/Select";
|
|||
import ToggleSwitch from "../../components/gui/Switch";
|
||||
import { ToolTip } from "../../components/gui/Tooltip";
|
||||
import { useFontSize } from "../../components/ui/font";
|
||||
import { useAuth } from "../../context/Auth";
|
||||
import { IdeMessengerContext } from "../../context/IdeMessenger";
|
||||
import { useAppDispatch, useAppSelector } from "../../redux/hooks";
|
||||
import { updateConfig } from "../../redux/slices/configSlice";
|
||||
import { setLocalStorage } from "../../util/localStorage";
|
||||
import { ContinueFeaturesMenu } from "./ContinueFeaturesMenu";
|
||||
|
||||
export function UserSettingsForm() {
|
||||
/////// User settings section //////
|
||||
|
|
@ -26,6 +29,7 @@ export function UserSettingsForm() {
|
|||
const ideMessenger = useContext(IdeMessengerContext);
|
||||
const config = useAppSelector((state) => state.config.config);
|
||||
const [showExperimental, setShowExperimental] = useState(false);
|
||||
const { session } = useAuth();
|
||||
|
||||
function handleUpdate(sharedConfig: SharedConfigSchema) {
|
||||
// Optimistic update
|
||||
|
|
@ -79,6 +83,8 @@ export function UserSettingsForm() {
|
|||
const disableSessionTitles = config.disableSessionTitles ?? false;
|
||||
const useCurrentFileAsContext =
|
||||
config.experimental?.useCurrentFileAsContext ?? false;
|
||||
const optInNextEditFeature =
|
||||
config.experimental?.optInNextEditFeature ?? false;
|
||||
|
||||
const allowAnonymousTelemetry = config.allowAnonymousTelemetry ?? true;
|
||||
const disableIndexing = config.disableIndexing ?? false;
|
||||
|
|
@ -112,6 +118,10 @@ export function UserSettingsForm() {
|
|||
});
|
||||
}, [ideMessenger]);
|
||||
|
||||
const hasContinueEmail = (session as HubSessionInfo)?.account?.id.includes(
|
||||
"@continue.dev",
|
||||
);
|
||||
|
||||
return (
|
||||
<div className="flex flex-col">
|
||||
{/* {selectedProfile && isLocalProfile(selectedProfile) ? (
|
||||
|
|
@ -353,7 +363,9 @@ export function UserSettingsForm() {
|
|||
</div>
|
||||
<div
|
||||
className={`duration-400 overflow-hidden transition-all ease-in-out ${
|
||||
showExperimental ? "max-h-40" : "max-h-0"
|
||||
showExperimental
|
||||
? "max-h-96" /* Increased from max-h-40 to max-h-96 to accommodate ContinueFeaturesMenu */
|
||||
: "max-h-0"
|
||||
}`}
|
||||
>
|
||||
<div className="flex flex-col gap-x-1 gap-y-4 pl-6">
|
||||
|
|
@ -408,6 +420,13 @@ export function UserSettingsForm() {
|
|||
</>
|
||||
}
|
||||
/>
|
||||
|
||||
{hasContinueEmail && (
|
||||
<ContinueFeaturesMenu
|
||||
optInNextEditFeature={optInNextEditFeature}
|
||||
handleUpdate={handleUpdate}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
|
|
|
|||
|
|
@ -6,6 +6,7 @@ import { DEFAULT_MAX_TOKENS } from "core/llm/constants";
|
|||
export type ConfigState = {
|
||||
configError: ConfigValidationError[] | undefined;
|
||||
config: BrowserSerializedContinueConfig;
|
||||
loading: boolean;
|
||||
};
|
||||
|
||||
export const EMPTY_CONFIG: BrowserSerializedContinueConfig = {
|
||||
|
|
@ -47,6 +48,7 @@ export const EMPTY_CONFIG: BrowserSerializedContinueConfig = {
|
|||
const initialState: ConfigState = {
|
||||
configError: undefined,
|
||||
config: EMPTY_CONFIG,
|
||||
loading: false,
|
||||
};
|
||||
|
||||
export const configSlice = createSlice({
|
||||
|
|
@ -82,6 +84,9 @@ export const configSlice = createSlice({
|
|||
) => {
|
||||
state.config = config;
|
||||
},
|
||||
setConfigLoading: (state, { payload: loading }: PayloadAction<boolean>) => {
|
||||
state.loading = loading;
|
||||
},
|
||||
},
|
||||
selectors: {
|
||||
selectSelectedChatModelContextLength: (state): number => {
|
||||
|
|
@ -99,7 +104,8 @@ export const configSlice = createSlice({
|
|||
},
|
||||
});
|
||||
|
||||
export const { updateConfig, setConfigResult } = configSlice.actions;
|
||||
export const { updateConfig, setConfigResult, setConfigLoading } =
|
||||
configSlice.actions;
|
||||
|
||||
export const {
|
||||
selectSelectedChatModelContextLength,
|
||||
|
|
|
|||
|
|
@ -1,6 +1,7 @@
|
|||
import { createAsyncThunk, unwrapResult } from "@reduxjs/toolkit";
|
||||
import { ContextItem } from "core";
|
||||
import { CLIENT_TOOLS_IMPLS } from "core/tools/builtIn";
|
||||
import posthog from "posthog-js";
|
||||
import { callClientTool } from "../../util/clientTools/callClientTool";
|
||||
import { selectCurrentToolCall } from "../selectors/selectCurrentToolCall";
|
||||
import { selectSelectedChatModel } from "../slices/configSlice";
|
||||
|
|
@ -45,6 +46,9 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
|
|||
let errorMessage: string | undefined = undefined;
|
||||
let streamResponse: boolean;
|
||||
|
||||
// Check if telemetry is enabled
|
||||
const allowAnonymousTelemetry = state.config.config.allowAnonymousTelemetry;
|
||||
|
||||
// IMPORTANT:
|
||||
// Errors that occur while calling tool call implementations
|
||||
// Are caught and passed in output as context items
|
||||
|
|
@ -110,6 +114,17 @@ export const callCurrentTool = createAsyncThunk<void, undefined, ThunkApiType>(
|
|||
);
|
||||
}
|
||||
|
||||
// Because we don't have access to use hooks, we check `allowAnonymousTelemetry`
|
||||
// directly rather than using `CustomPostHogProvider`
|
||||
if (allowAnonymousTelemetry) {
|
||||
// Capture telemetry for tool calls
|
||||
posthog.capture("gui_tool_call_outcome", {
|
||||
succeeded: errorMessage === undefined,
|
||||
toolName: toolCallState.toolCall.function.name,
|
||||
errorMessage: errorMessage,
|
||||
});
|
||||
}
|
||||
|
||||
if (streamResponse) {
|
||||
if (errorMessage) {
|
||||
dispatch(
|
||||
|
|
|
|||
|
|
@ -16,11 +16,13 @@ type LocalStorageTypes = {
|
|||
showTutorialCard: boolean;
|
||||
shownProfilesIntroduction: boolean;
|
||||
disableIndexing: boolean;
|
||||
hasExitedFreeTrial: boolean;
|
||||
};
|
||||
|
||||
export enum LocalStorageKey {
|
||||
IsExploreDialogOpen = "isExploreDialogOpen",
|
||||
HasDismissedExploreDialog = "hasDismissedExploreDialog",
|
||||
HasExitedFreeTrial = "hasExitedFreeTrial",
|
||||
}
|
||||
|
||||
export function getLocalStorage<T extends keyof LocalStorageTypes>(
|
||||
|
|
|
|||
81
manual-testing-sandbox/next-edit/next-edit-1-1-sol.ts
Normal file
81
manual-testing-sandbox/next-edit/next-edit-1-1-sol.ts
Normal file
|
|
@ -0,0 +1,81 @@
|
|||
// A clean implementation of the price calculation utility
|
||||
// Solution for: next-edit-1-1.ts
|
||||
|
||||
/**
|
||||
* Interface for a purchasable item
|
||||
*/
|
||||
interface PricedItem {
|
||||
name: string;
|
||||
price: number;
|
||||
}
|
||||
|
||||
/**
|
||||
* Calculates the total price of items with an optional discount
|
||||
*
|
||||
* @param items - Array of priced items
|
||||
* @param discountPercentage - Optional discount to apply (percentage)
|
||||
* @returns The final price after discount
|
||||
*/
|
||||
function calculateTotalPrice(
|
||||
items: PricedItem[],
|
||||
discountPercentage = 0,
|
||||
): number {
|
||||
// Calculate total price
|
||||
const subtotal = items.reduce((total, item) => total + item.price, 0);
|
||||
|
||||
// Apply discount
|
||||
const discount = (subtotal * discountPercentage) / 100;
|
||||
const finalPrice = subtotal - discount;
|
||||
|
||||
return finalPrice;
|
||||
}
|
||||
|
||||
// Example usage
|
||||
const cart: PricedItem[] = [
|
||||
{ name: "Shirt", price: 25 },
|
||||
{ name: "Pants", price: 50 },
|
||||
{ name: "Shoes", price: 100 },
|
||||
];
|
||||
|
||||
// Calculate price with 10% discount
|
||||
const finalPrice = calculateTotalPrice(cart, 10);
|
||||
console.log(`Final price: $${finalPrice}`);
|
||||
|
||||
// Export function
|
||||
export default calculateTotalPrice;
|
||||
|
||||
/*
|
||||
Single Responsibility Principle:
|
||||
|
||||
The function now has a clearer, more descriptive name: calculateTotalPrice instead of calc_price
|
||||
Used proper camelCase naming convention for JavaScript/TypeScript functions
|
||||
|
||||
|
||||
Type Safety:
|
||||
|
||||
Created a proper PricedItem interface instead of using any[]
|
||||
Added proper type annotations throughout the code
|
||||
|
||||
|
||||
Code Quality Improvements:
|
||||
|
||||
Replaced the for loop with a more functional reduce() approach
|
||||
Used const instead of let where variables aren't reassigned
|
||||
Used default parameter syntax instead of conditional checking
|
||||
Improved variable naming for clarity
|
||||
Added JSDoc comments for better documentation
|
||||
Used template literals instead of string concatenation
|
||||
|
||||
|
||||
Fixed Potential Issues:
|
||||
|
||||
Replaced loose inequality check (!=) with default parameter
|
||||
Changed var to const in the loop to avoid scope issues
|
||||
Made intermediate calculations more explicit with named variables
|
||||
|
||||
|
||||
Maintainability:
|
||||
|
||||
Added proper documentation with JSDoc comments
|
||||
Used more explicit and descriptive variable names
|
||||
*/
|
||||
32
manual-testing-sandbox/next-edit/next-edit-1-1.ts
Normal file
32
manual-testing-sandbox/next-edit/next-edit-1-1.ts
Normal file
|
|
@ -0,0 +1,32 @@
|
|||
// A simple utility function with minor issues
|
||||
// Difficulty: 1 - Easy fixes needed
|
||||
|
||||
// Function to calculate total price with discount
|
||||
function calc_price(items: any[], discountPercentage?: number) {
|
||||
// Calculate total price
|
||||
let total = 0;
|
||||
for (var i = 0; i < items.length; i++) {
|
||||
total = total + items[i].price;
|
||||
}
|
||||
|
||||
// Apply discount
|
||||
if (discountPercentage != undefined) {
|
||||
total = total - (total * discountPercentage) / 100;
|
||||
}
|
||||
|
||||
return total;
|
||||
}
|
||||
|
||||
// Example usage
|
||||
const cart = [
|
||||
{ name: "Shirt", price: 25 },
|
||||
{ name: "Pants", price: 50 },
|
||||
{ name: "Shoes", price: 100 },
|
||||
];
|
||||
|
||||
// Calculate price with 10% discount
|
||||
const finalPrice = calc_price(cart, 10);
|
||||
console.log("Final price: $" + finalPrice);
|
||||
|
||||
// Export function
|
||||
export default calc_price;
|
||||
1110
manual-testing-sandbox/next-edit/next-edit-10-5-sol.ts
Normal file
1110
manual-testing-sandbox/next-edit/next-edit-10-5-sol.ts
Normal file
File diff suppressed because it is too large
Load diff
445
manual-testing-sandbox/next-edit/next-edit-10-5.ts
Normal file
445
manual-testing-sandbox/next-edit/next-edit-10-5.ts
Normal file
|
|
@ -0,0 +1,445 @@
|
|||
// A messy project management application with tangled dependencies and responsibilities
|
||||
// Difficulty: 5/5
|
||||
|
||||
// Global state
|
||||
let globalTasks: any[] = [];
|
||||
let globalUsers: any[] = [];
|
||||
let globalProjects: any[] = [];
|
||||
let currentUser: any = null;
|
||||
let lastActivityTime = Date.now();
|
||||
let _config = {
|
||||
maxTasksPerUser: 20,
|
||||
maxProjectsPerUser: 5,
|
||||
defaultPriority: "medium",
|
||||
enableNotifications: true,
|
||||
serverUrl: "https://api.example.com/v1",
|
||||
};
|
||||
|
||||
// Mixed utility functions and business logic
|
||||
const util = {
|
||||
generateId: (prefix: string) =>
|
||||
`${prefix}_${Math.random().toString(36).substring(2, 15)}${Date.now()}`,
|
||||
calculateProgress: (tasks: any[]) => {
|
||||
const completed = tasks.filter((t) => t.status === "completed").length;
|
||||
return tasks.length ? Math.round((completed / tasks.length) * 100) : 0;
|
||||
},
|
||||
sendNotification: (type: string, message: string, user: any) => {
|
||||
if (!_config.enableNotifications) return;
|
||||
console.log(`[NOTIFICATION to ${user.email}]: ${message}`);
|
||||
// Side effects directly inside utility function
|
||||
if (typeof window !== "undefined") {
|
||||
// DOM manipulation in utility
|
||||
const notification = document.createElement("div");
|
||||
notification.className = `notification ${type}`;
|
||||
notification.innerText = message;
|
||||
document.body.appendChild(notification);
|
||||
setTimeout(() => notification.remove(), 5000);
|
||||
}
|
||||
},
|
||||
logger: (action: string, data: any) => {
|
||||
console.log(`[${new Date().toISOString()}] ${action}:`, data);
|
||||
// Side effect - updating activity time
|
||||
lastActivityTime = Date.now();
|
||||
},
|
||||
};
|
||||
|
||||
// Data validation mixed with business logic
|
||||
function validateTask(task: any) {
|
||||
if (!task.title) throw new Error("Task title is required");
|
||||
if (!task.projectId) throw new Error("Task must belong to a project");
|
||||
if (!globalProjects.some((p) => p.id === task.projectId)) {
|
||||
throw new Error("Project does not exist");
|
||||
}
|
||||
|
||||
// Validation mixed with business rules
|
||||
const userTasks = globalTasks.filter(
|
||||
(t) => t.assignedTo === task.assignedTo && t.status !== "completed",
|
||||
);
|
||||
|
||||
if (userTasks.length >= _config.maxTasksPerUser) {
|
||||
throw new Error(
|
||||
`User cannot have more than ${_config.maxTasksPerUser} active tasks`,
|
||||
);
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Authentication mixed with data fetching
|
||||
function authenticate(username: string, password: string) {
|
||||
// Direct data manipulation and mocked authentication
|
||||
const user = globalUsers.find((u) => u.username === username);
|
||||
if (!user || user.password !== password) {
|
||||
util.logger("auth_failed", { username });
|
||||
throw new Error("Invalid credentials");
|
||||
}
|
||||
|
||||
currentUser = user;
|
||||
util.logger("auth_success", { userId: user.id });
|
||||
|
||||
// Mixing data fetching with authentication
|
||||
loadUserData(user.id);
|
||||
|
||||
return user;
|
||||
}
|
||||
|
||||
// Data fetching with side effects
|
||||
function loadUserData(userId: string) {
|
||||
// This would be an API call in real app
|
||||
console.log(`Loading data for user ${userId}`);
|
||||
|
||||
// Direct global state manipulation
|
||||
globalTasks = globalTasks.filter(
|
||||
(t) => t.createdBy === userId || t.assignedTo === userId,
|
||||
);
|
||||
|
||||
globalProjects = globalProjects.filter(
|
||||
(p) => p.members.includes(userId) || p.createdBy === userId,
|
||||
);
|
||||
|
||||
// Direct DOM manipulation
|
||||
if (typeof document !== "undefined") {
|
||||
const taskCount = document.getElementById("task-count");
|
||||
if (taskCount) {
|
||||
taskCount.innerText = String(globalTasks.length);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Task management with mixed responsibilities
|
||||
class TaskManager {
|
||||
// Creates a task with mixed concerns
|
||||
createTask(taskData: any) {
|
||||
if (!currentUser) throw new Error("Not authenticated");
|
||||
|
||||
// Authentication check mixed with business logic
|
||||
if (taskData.projectId) {
|
||||
const project = globalProjects.find((p) => p.id === taskData.projectId);
|
||||
if (
|
||||
!project.members.includes(currentUser.id) &&
|
||||
project.createdBy !== currentUser.id
|
||||
) {
|
||||
throw new Error("You do not have access to this project");
|
||||
}
|
||||
}
|
||||
|
||||
const task = {
|
||||
id: util.generateId("task"),
|
||||
title: taskData.title,
|
||||
description: taskData.description || "",
|
||||
status: "new",
|
||||
priority: taskData.priority || _config.defaultPriority,
|
||||
createdAt: new Date(),
|
||||
createdBy: currentUser.id,
|
||||
assignedTo: taskData.assignedTo || currentUser.id,
|
||||
projectId: taskData.projectId,
|
||||
dueDate: taskData.dueDate || null,
|
||||
comments: [],
|
||||
attachments: [],
|
||||
tags: taskData.tags || [],
|
||||
timeSpent: 0,
|
||||
lastUpdated: new Date(),
|
||||
};
|
||||
|
||||
// Validation mixed with creation
|
||||
validateTask(task);
|
||||
|
||||
// Global state mutation
|
||||
globalTasks.push(task);
|
||||
|
||||
// Side effects - email notification mixed with task creation
|
||||
if (task.assignedTo !== currentUser.id) {
|
||||
const assignee = globalUsers.find((u) => u.id === task.assignedTo);
|
||||
if (assignee) {
|
||||
console.log(
|
||||
`Sending email to ${assignee.email} about new task assignment`,
|
||||
);
|
||||
util.sendNotification(
|
||||
"task_assigned",
|
||||
`You've been assigned a new task: ${task.title}`,
|
||||
assignee,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// More side effects - updating project data
|
||||
if (task.projectId) {
|
||||
const project = globalProjects.find((p) => p.id === task.projectId);
|
||||
if (project) {
|
||||
project.taskCount = (project.taskCount || 0) + 1;
|
||||
project.lastActivity = new Date();
|
||||
// Recalculating project progress on each task addition
|
||||
const projectTasks = globalTasks.filter(
|
||||
(t) => t.projectId === project.id,
|
||||
);
|
||||
project.progress = util.calculateProgress(projectTasks);
|
||||
}
|
||||
}
|
||||
|
||||
// Logging
|
||||
util.logger("task_created", { taskId: task.id, title: task.title });
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
// Update task with mixed concerns
|
||||
updateTask(taskId: string, updates: any) {
|
||||
if (!currentUser) throw new Error("Not authenticated");
|
||||
|
||||
const taskIndex = globalTasks.findIndex((t) => t.id === taskId);
|
||||
if (taskIndex === -1) throw new Error("Task not found");
|
||||
|
||||
const task = globalTasks[taskIndex];
|
||||
|
||||
// Permission check mixed with update logic
|
||||
if (
|
||||
task.createdBy !== currentUser.id &&
|
||||
task.assignedTo !== currentUser.id &&
|
||||
!currentUser.isAdmin
|
||||
) {
|
||||
throw new Error("You do not have permission to update this task");
|
||||
}
|
||||
|
||||
// Status transition logic mixed with update
|
||||
if (updates.status && updates.status !== task.status) {
|
||||
if (task.status === "completed" && updates.status !== "completed") {
|
||||
// Re-opening completed task
|
||||
task.reopenCount = (task.reopenCount || 0) + 1;
|
||||
util.logger("task_reopened", { taskId, previousStatus: task.status });
|
||||
}
|
||||
|
||||
if (updates.status === "completed") {
|
||||
// Completing task
|
||||
task.completedAt = new Date();
|
||||
task.completedBy = currentUser.id;
|
||||
|
||||
// Side effect - updating user stats
|
||||
const user = globalUsers.find((u) => u.id === currentUser.id);
|
||||
if (user) {
|
||||
user.completedTasks = (user.completedTasks || 0) + 1;
|
||||
// More side effects - achievement system
|
||||
if (
|
||||
user.completedTasks >= 10 &&
|
||||
!user.achievements?.includes("productive")
|
||||
) {
|
||||
user.achievements = [...(user.achievements || []), "productive"];
|
||||
util.sendNotification(
|
||||
"achievement",
|
||||
"You earned the Productive badge!",
|
||||
user,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Main update logic - directly modifying the object
|
||||
Object.keys(updates).forEach((key) => {
|
||||
// Skip protected fields
|
||||
if (!["id", "createdAt", "createdBy"].includes(key)) {
|
||||
task[key] = updates[key];
|
||||
}
|
||||
});
|
||||
|
||||
task.lastUpdated = new Date();
|
||||
|
||||
// Validation after update (inconsistent)
|
||||
validateTask(task);
|
||||
|
||||
// Update global state
|
||||
globalTasks[taskIndex] = task;
|
||||
|
||||
// More side effects - project update
|
||||
if (task.projectId) {
|
||||
const project = globalProjects.find((p) => p.id === task.projectId);
|
||||
if (project) {
|
||||
const projectTasks = globalTasks.filter(
|
||||
(t) => t.projectId === project.id,
|
||||
);
|
||||
project.progress = util.calculateProgress(projectTasks);
|
||||
project.lastActivity = new Date();
|
||||
}
|
||||
}
|
||||
|
||||
// Notification side effects
|
||||
if (updates.assignedTo && updates.assignedTo !== task.assignedTo) {
|
||||
const assignee = globalUsers.find((u) => u.id === updates.assignedTo);
|
||||
if (assignee) {
|
||||
util.sendNotification(
|
||||
"task_assigned",
|
||||
`You've been assigned to task: ${task.title}`,
|
||||
assignee,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
util.logger("task_updated", { taskId, changes: Object.keys(updates) });
|
||||
|
||||
return task;
|
||||
}
|
||||
|
||||
// Delete task with side effects
|
||||
deleteTask(taskId: string) {
|
||||
if (!currentUser) throw new Error("Not authenticated");
|
||||
|
||||
const taskIndex = globalTasks.findIndex((t) => t.id === taskId);
|
||||
if (taskIndex === -1) throw new Error("Task not found");
|
||||
|
||||
const task = globalTasks[taskIndex];
|
||||
|
||||
// Permission check
|
||||
if (task.createdBy !== currentUser.id && !currentUser.isAdmin) {
|
||||
throw new Error("Only the creator or an admin can delete a task");
|
||||
}
|
||||
|
||||
// Side effects before deletion
|
||||
if (task.projectId) {
|
||||
const project = globalProjects.find((p) => p.id === task.projectId);
|
||||
if (project) {
|
||||
project.taskCount = Math.max(0, (project.taskCount || 0) - 1);
|
||||
project.lastActivity = new Date();
|
||||
// More side effects - recalculating metrics
|
||||
setTimeout(() => {
|
||||
const projectTasks = globalTasks.filter(
|
||||
(t) => t.projectId === project.id && t.id !== taskId,
|
||||
);
|
||||
project.progress = util.calculateProgress(projectTasks);
|
||||
}, 0);
|
||||
}
|
||||
}
|
||||
|
||||
// Global state mutation
|
||||
globalTasks.splice(taskIndex, 1);
|
||||
|
||||
// Notification side effects
|
||||
if (task.assignedTo !== currentUser.id) {
|
||||
const assignee = globalUsers.find((u) => u.id === task.assignedTo);
|
||||
if (assignee) {
|
||||
util.sendNotification(
|
||||
"task_deleted",
|
||||
`A task assigned to you was deleted: ${task.title}`,
|
||||
assignee,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
util.logger("task_deleted", { taskId, title: task.title });
|
||||
|
||||
return { success: true };
|
||||
}
|
||||
|
||||
// Search with mixed concerns
|
||||
searchTasks(criteria: any) {
|
||||
if (!currentUser) throw new Error("Not authenticated");
|
||||
|
||||
// Filtering with complex inline logic
|
||||
let results = globalTasks.filter((task) => {
|
||||
// Basic visibility check
|
||||
const isVisible =
|
||||
task.createdBy === currentUser.id ||
|
||||
task.assignedTo === currentUser.id ||
|
||||
(task.projectId &&
|
||||
globalProjects.some(
|
||||
(p) =>
|
||||
p.id === task.projectId &&
|
||||
(p.members.includes(currentUser.id) || p.isPublic),
|
||||
));
|
||||
|
||||
if (!isVisible) return false;
|
||||
|
||||
// Apply search criteria
|
||||
if (criteria.status && task.status !== criteria.status) return false;
|
||||
if (criteria.priority && task.priority !== criteria.priority)
|
||||
return false;
|
||||
if (criteria.assignedTo && task.assignedTo !== criteria.assignedTo)
|
||||
return false;
|
||||
if (criteria.projectId && task.projectId !== criteria.projectId)
|
||||
return false;
|
||||
|
||||
// Text search
|
||||
if (criteria.searchText) {
|
||||
const searchText = criteria.searchText.toLowerCase();
|
||||
const matchesTitle = task.title.toLowerCase().includes(searchText);
|
||||
const matchesDescription = task.description
|
||||
?.toLowerCase()
|
||||
.includes(searchText);
|
||||
const matchesTags = task.tags?.some((tag: string) =>
|
||||
tag.toLowerCase().includes(searchText),
|
||||
);
|
||||
|
||||
if (!matchesTitle && !matchesDescription && !matchesTags) return false;
|
||||
}
|
||||
|
||||
// Date filters
|
||||
if (
|
||||
criteria.createdAfter &&
|
||||
new Date(task.createdAt) < new Date(criteria.createdAfter)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
criteria.createdBefore &&
|
||||
new Date(task.createdAt) > new Date(criteria.createdBefore)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
criteria.dueBefore &&
|
||||
task.dueDate &&
|
||||
new Date(task.dueDate) > new Date(criteria.dueBefore)
|
||||
)
|
||||
return false;
|
||||
if (
|
||||
criteria.dueAfter &&
|
||||
task.dueDate &&
|
||||
new Date(task.dueDate) < new Date(criteria.dueAfter)
|
||||
)
|
||||
return false;
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
// Sorting mixed with filtering
|
||||
if (criteria.sortBy) {
|
||||
results.sort((a, b) => {
|
||||
if (criteria.sortBy === "dueDate") {
|
||||
if (!a.dueDate) return criteria.sortDir === "asc" ? 1 : -1;
|
||||
if (!b.dueDate) return criteria.sortDir === "asc" ? -1 : 1;
|
||||
return criteria.sortDir === "asc"
|
||||
? new Date(a.dueDate).getTime() - new Date(b.dueDate).getTime()
|
||||
: new Date(b.dueDate).getTime() - new Date(a.dueDate).getTime();
|
||||
}
|
||||
|
||||
if (criteria.sortBy === "priority") {
|
||||
const priorityMap: Record<string, number> = {
|
||||
high: 3,
|
||||
medium: 2,
|
||||
low: 1,
|
||||
};
|
||||
return criteria.sortDir === "asc"
|
||||
? priorityMap[a.priority] - priorityMap[b.priority]
|
||||
: priorityMap[b.priority] - priorityMap[a.priority];
|
||||
}
|
||||
|
||||
// Default sort by creation date
|
||||
return criteria.sortDir === "asc"
|
||||
? new Date(a.createdAt).getTime() - new Date(b.createdAt).getTime()
|
||||
: new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime();
|
||||
});
|
||||
}
|
||||
|
||||
// Pagination mixed with core functionality
|
||||
if (criteria.limit) {
|
||||
const page = criteria.page || 1;
|
||||
const start = (page - 1) * criteria.limit;
|
||||
results = results.slice(start, start + criteria.limit);
|
||||
}
|
||||
|
||||
util.logger("tasks_searched", { criteria, resultCount: results.length });
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
// Usage would be like:
|
||||
// const tm = new TaskManager();
|
||||
// tm.createTask({ title: 'Implement login', projectId: 'proj_123', priority: 'high' });
|
||||
// tm.updateTask('task_123', { status: 'in_progress', assignedTo: 'user_456' });
|
||||
142
manual-testing-sandbox/next-edit/next-edit-2-1-sol.ts
Normal file
142
manual-testing-sandbox/next-edit/next-edit-2-1-sol.ts
Normal file
|
|
@ -0,0 +1,142 @@
|
|||
// A refactored user validation utility following SOLID principles
|
||||
// Solution for next-edit-2-1.ts
|
||||
|
||||
type UserData = {
|
||||
id?: number;
|
||||
name: string;
|
||||
email: string;
|
||||
age?: number;
|
||||
isActive: boolean;
|
||||
};
|
||||
|
||||
// Define a validation result interface
|
||||
interface ValidationResult {
|
||||
isValid: boolean;
|
||||
error?: string;
|
||||
}
|
||||
|
||||
// Create a validator interface (Interface Segregation Principle)
|
||||
interface Validator {
|
||||
validate(data: any): ValidationResult;
|
||||
}
|
||||
|
||||
// Individual validators with single responsibilities (Single Responsibility Principle)
|
||||
class NameValidator implements Validator {
|
||||
validate(name: string): ValidationResult {
|
||||
if (name.length < 2) {
|
||||
return { isValid: false, error: "Name is too short" };
|
||||
}
|
||||
return { isValid: true };
|
||||
}
|
||||
}
|
||||
|
||||
class EmailValidator implements Validator {
|
||||
validate(email: string): ValidationResult {
|
||||
if (!email.includes("@")) {
|
||||
return { isValid: false, error: "Invalid email format" };
|
||||
}
|
||||
return { isValid: true };
|
||||
}
|
||||
}
|
||||
|
||||
class AgeValidator implements Validator {
|
||||
validate(age: number | undefined): ValidationResult {
|
||||
if (age !== undefined && age < 18) {
|
||||
return { isValid: false, error: "User must be 18 or older" };
|
||||
}
|
||||
return { isValid: true };
|
||||
}
|
||||
}
|
||||
|
||||
// Composite validator that uses individual validators (Open/Closed Principle)
|
||||
class UserValidator {
|
||||
private validators: { [key: string]: Validator } = {
|
||||
name: new NameValidator(),
|
||||
email: new EmailValidator(),
|
||||
age: new AgeValidator(),
|
||||
};
|
||||
|
||||
validate(user: UserData): ValidationResult {
|
||||
// Validate name
|
||||
const nameResult = this.validators.name.validate(user.name);
|
||||
if (!nameResult.isValid) {
|
||||
return nameResult;
|
||||
}
|
||||
|
||||
// Validate email
|
||||
const emailResult = this.validators.email.validate(user.email);
|
||||
if (!emailResult.isValid) {
|
||||
return emailResult;
|
||||
}
|
||||
|
||||
// Validate age
|
||||
const ageResult = this.validators.age.validate(user.age);
|
||||
if (!ageResult.isValid) {
|
||||
return ageResult;
|
||||
}
|
||||
|
||||
// All validations passed
|
||||
return { isValid: true };
|
||||
}
|
||||
}
|
||||
|
||||
// Example usage
|
||||
const user = {
|
||||
name: "Jo",
|
||||
email: "jo.example.com",
|
||||
age: 25,
|
||||
isActive: true,
|
||||
};
|
||||
|
||||
const userValidator = new UserValidator();
|
||||
const result = userValidator.validate(user);
|
||||
|
||||
if (result.isValid) {
|
||||
console.log("User is valid");
|
||||
} else {
|
||||
console.log("Error: " + result.error);
|
||||
}
|
||||
|
||||
export {
|
||||
AgeValidator,
|
||||
EmailValidator,
|
||||
NameValidator,
|
||||
UserValidator,
|
||||
ValidationResult,
|
||||
Validator,
|
||||
};
|
||||
|
||||
/*
|
||||
Code Smells:
|
||||
Using global state (validationError variable)
|
||||
Single validation function doing multiple things
|
||||
No clear error handling mechanism
|
||||
Tightly coupled validation logic
|
||||
|
||||
Fix:
|
||||
1. Single Responsibility Principle (SRP)
|
||||
Created separate validator classes for each validation concern
|
||||
Each validator is responsible for only one type of validation (name, email, age)
|
||||
|
||||
|
||||
2. Open/Closed Principle (OCP)
|
||||
The validation system is open for extension (you can add new validators)
|
||||
The core UserValidator class doesn't need to change when adding new validation rules
|
||||
|
||||
|
||||
3. Interface Segregation Principle (ISP)
|
||||
Created a clean Validator interface that all validators implement
|
||||
Each validator only needs to implement a single validation method
|
||||
|
||||
|
||||
4. Dependency Inversion Principle (DIP)
|
||||
The UserValidator depends on abstractions (the Validator interface)
|
||||
Specific validators are injected into the UserValidator
|
||||
|
||||
|
||||
5. Other improvements:
|
||||
Eliminated global state by using return values instead of global variables
|
||||
Created a proper ValidationResult interface for structured error reporting
|
||||
Made the validation logic more modular and testable
|
||||
Each class and function has a clear, single responsibility
|
||||
*/
|
||||
58
manual-testing-sandbox/next-edit/next-edit-2-1.ts
Normal file
58
manual-testing-sandbox/next-edit/next-edit-2-1.ts
Normal file
|
|
@ -0,0 +1,58 @@
|
|||
// A simple user validation utility with poor organization
|
||||
// Difficulty: 1 - Easy fixes needed
|
||||
|
||||
type UserData = {
|
||||
id?: number;
|
||||
name: string;
|
||||
email: string;
|
||||
age?: number;
|
||||
isActive: boolean;
|
||||
};
|
||||
|
||||
// Global variable to store error messages
|
||||
let validationError = "";
|
||||
|
||||
// Function to validate user data
|
||||
function validateUser(data: UserData) {
|
||||
// Reset error
|
||||
validationError = "";
|
||||
|
||||
// Check name
|
||||
if (data.name.length < 2) {
|
||||
validationError = "Name is too short";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check email
|
||||
if (!data.email.includes("@")) {
|
||||
validationError = "Invalid email format";
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check age if provided
|
||||
if (data.age != undefined) {
|
||||
if (data.age < 18) {
|
||||
validationError = "User must be 18 or older";
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// All validations passed
|
||||
return true;
|
||||
}
|
||||
|
||||
// Example usage
|
||||
const user = {
|
||||
name: "Jo",
|
||||
email: "jo.example.com",
|
||||
age: 25,
|
||||
isActive: true,
|
||||
};
|
||||
|
||||
if (validateUser(user)) {
|
||||
console.log("User is valid");
|
||||
} else {
|
||||
console.log("Error: " + validationError);
|
||||
}
|
||||
|
||||
export { validateUser, validationError };
|
||||
188
manual-testing-sandbox/next-edit/next-edit-3-2-sol.ts
Normal file
188
manual-testing-sandbox/next-edit/next-edit-3-2-sol.ts
Normal file
|
|
@ -0,0 +1,188 @@
|
|||
// A well-structured todo list manager following SOLID principles
|
||||
// Refactored solution for next-edit-3-2.ts
|
||||
|
||||
// Define types for better maintainability
|
||||
type Priority = "low" | "medium" | "high";
|
||||
|
||||
interface Todo {
|
||||
id: number;
|
||||
text: string;
|
||||
completed: boolean;
|
||||
priority: Priority;
|
||||
}
|
||||
|
||||
// TodoManager class following Single Responsibility Principle
|
||||
class TodoManager {
|
||||
private todos: Map<number, Todo> = new Map();
|
||||
private lastId: number = 0;
|
||||
|
||||
// Create a new todo
|
||||
addTodo(text: string, priority: Priority = "medium"): Todo {
|
||||
// Input validation
|
||||
if (!text.trim()) {
|
||||
throw new Error("Todo text cannot be empty");
|
||||
}
|
||||
|
||||
const newTodo: Todo = {
|
||||
id: ++this.lastId,
|
||||
text: text.trim(),
|
||||
completed: false,
|
||||
priority,
|
||||
};
|
||||
|
||||
this.todos.set(newTodo.id, newTodo);
|
||||
return { ...newTodo }; // Return a copy to prevent direct modification
|
||||
}
|
||||
|
||||
// Delete a todo by id
|
||||
deleteTodo(id: number): boolean {
|
||||
return this.todos.delete(id);
|
||||
}
|
||||
|
||||
// Toggle todo completion status
|
||||
toggleTodo(id: number): Todo | null {
|
||||
const todo = this.todos.get(id);
|
||||
if (!todo) return null;
|
||||
|
||||
const updatedTodo = { ...todo, completed: !todo.completed };
|
||||
this.todos.set(id, updatedTodo);
|
||||
return { ...updatedTodo };
|
||||
}
|
||||
|
||||
// Update todo text
|
||||
updateTodoText(id: number, newText: string): Todo | null {
|
||||
if (!newText.trim()) {
|
||||
throw new Error("Todo text cannot be empty");
|
||||
}
|
||||
|
||||
const todo = this.todos.get(id);
|
||||
if (!todo) return null;
|
||||
|
||||
const updatedTodo = { ...todo, text: newText.trim() };
|
||||
this.todos.set(id, updatedTodo);
|
||||
return { ...updatedTodo };
|
||||
}
|
||||
|
||||
// Change todo priority
|
||||
changePriority(id: number, newPriority: Priority): Todo | null {
|
||||
const todo = this.todos.get(id);
|
||||
if (!todo) return null;
|
||||
|
||||
const updatedTodo = { ...todo, priority: newPriority };
|
||||
this.todos.set(id, updatedTodo);
|
||||
return { ...updatedTodo };
|
||||
}
|
||||
|
||||
// Get all todos
|
||||
getAllTodos(): Todo[] {
|
||||
return Array.from(this.todos.values()).map((todo) => ({ ...todo }));
|
||||
}
|
||||
|
||||
// Filter todos by various criteria (following Open/Closed Principle)
|
||||
filterTodos(predicate: (todo: Todo) => boolean): Todo[] {
|
||||
return this.getAllTodos().filter(predicate);
|
||||
}
|
||||
|
||||
// Helper methods built on top of filterTodos
|
||||
getCompletedTodos(): Todo[] {
|
||||
return this.filterTodos((todo) => todo.completed);
|
||||
}
|
||||
|
||||
getActiveTodos(): Todo[] {
|
||||
return this.filterTodos((todo) => !todo.completed);
|
||||
}
|
||||
|
||||
getTodosByPriority(priority: Priority): Todo[] {
|
||||
return this.filterTodos((todo) => todo.priority === priority);
|
||||
}
|
||||
}
|
||||
|
||||
// Create a singleton instance
|
||||
const todoManager = new TodoManager();
|
||||
|
||||
// Example usage
|
||||
todoManager.addTodo("Buy groceries", "high");
|
||||
todoManager.addTodo("Clean house");
|
||||
todoManager.addTodo("Pay bills", "high");
|
||||
todoManager.toggleTodo(2);
|
||||
|
||||
console.log("All todos:", todoManager.getAllTodos());
|
||||
console.log("High priority todos:", todoManager.getTodosByPriority("high"));
|
||||
console.log("Completed todos:", todoManager.getCompletedTodos());
|
||||
|
||||
// Export the TodoManager class and its instance
|
||||
export { Priority, Todo, TodoManager, todoManager };
|
||||
|
||||
/*
|
||||
Code Smells in next-edit-3-2.ts:
|
||||
Global state - using global variables for todos and lastId
|
||||
Single Responsibility Principle violation - mixing data management with business logic
|
||||
Duplicated code in several functions that iterate through todos
|
||||
No clear abstraction layers - direct manipulation of the data structure
|
||||
No validation or error handling
|
||||
No proper typing for priority values
|
||||
No encapsulation - direct access to the todos array
|
||||
No use of more efficient data structures (using array iteration instead of maps/objects)
|
||||
|
||||
Improvements Made in the Refactored Solution:
|
||||
|
||||
Encapsulation and Data Hiding
|
||||
|
||||
Created a TodoManager class to encapsulate all operations and data
|
||||
Made todos and lastId private members of the class
|
||||
Used a Map instead of an array for more efficient lookup by id
|
||||
|
||||
|
||||
Proper Type Definitions
|
||||
|
||||
Defined a proper Todo interface
|
||||
Created a union type for Priority with specific allowed values
|
||||
|
||||
|
||||
Single Responsibility Principle
|
||||
|
||||
Each method has a clear, single responsibility
|
||||
Separated data structure management from business logic
|
||||
|
||||
|
||||
Open/Closed Principle
|
||||
|
||||
Introduced a general filterTodos method that accepts a predicate
|
||||
Built specialized filter methods on top of this generic one
|
||||
|
||||
|
||||
Data Integrity and Validation
|
||||
|
||||
Added validation for todo text to prevent empty todos
|
||||
Return copies of todos to prevent direct modification of internal state
|
||||
|
||||
|
||||
Reduced Code Duplication
|
||||
|
||||
Eliminated repeated code for finding todos by id
|
||||
Consolidated filtering logic into a single method
|
||||
|
||||
|
||||
Improved Performance
|
||||
|
||||
Used a Map data structure for O(1) lookups by id instead of O(n) array iterations
|
||||
More efficient todo retrieval and manipulation
|
||||
|
||||
|
||||
Better API Design
|
||||
|
||||
Added more helper methods for common operations
|
||||
Created a consistent interface with descriptive method names
|
||||
Added a method to get all todos instead of directly accessing the array
|
||||
|
||||
|
||||
Error Handling
|
||||
|
||||
Added basic input validation with meaningful error messages
|
||||
|
||||
|
||||
Immutability
|
||||
|
||||
Returned copies of objects rather than references to internal state
|
||||
Used object spread to create new objects when updating
|
||||
*/
|
||||
111
manual-testing-sandbox/next-edit/next-edit-3-2.ts
Normal file
111
manual-testing-sandbox/next-edit/next-edit-3-2.ts
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
// A poorly structured todo list manager
|
||||
// Difficulty: 2 - Multiple issues to fix
|
||||
|
||||
// Global variables
|
||||
let todos: {
|
||||
id: number;
|
||||
text: string;
|
||||
completed: boolean;
|
||||
priority: string;
|
||||
}[] = [];
|
||||
let lastId = 0;
|
||||
|
||||
// Add a new todo
|
||||
function addTodo(text: string, priority = "medium") {
|
||||
const newTodo = {
|
||||
id: ++lastId,
|
||||
text: text,
|
||||
completed: false,
|
||||
priority: priority,
|
||||
};
|
||||
todos.push(newTodo);
|
||||
return newTodo;
|
||||
}
|
||||
|
||||
// Delete a todo by id
|
||||
function deleteTodo(id: number) {
|
||||
for (let i = 0; i < todos.length; i++) {
|
||||
if (todos[i].id === id) {
|
||||
todos.splice(i, 1);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Toggle todo completion status
|
||||
function toggleTodo(id: number) {
|
||||
for (let i = 0; i < todos.length; i++) {
|
||||
const todo = todos[i];
|
||||
if (todo.id === id) {
|
||||
todo.completed = !todo.completed;
|
||||
return todo;
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Update todo text
|
||||
function updateTodoText(id: number, newText: string) {
|
||||
for (let i = 0; i < todos.length; i++) {
|
||||
if (todos[i].id === id) {
|
||||
todos[i].text = newText;
|
||||
return todos[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Change todo priority
|
||||
function changePriority(id: number, newPriority: string) {
|
||||
for (let i = 0; i < todos.length; i++) {
|
||||
if (todos[i].id === id) {
|
||||
todos[i].priority = newPriority;
|
||||
return todos[i];
|
||||
}
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
// Filter todos by status
|
||||
function filterByStatus(completed: boolean) {
|
||||
const result = [];
|
||||
for (let i = 0; i < todos.length; i++) {
|
||||
if (todos[i].completed === completed) {
|
||||
result.push(todos[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Filter todos by priority
|
||||
function filterByPriority(priority: string) {
|
||||
const result = [];
|
||||
for (let i = 0; i < todos.length; i++) {
|
||||
if (todos[i].priority === priority) {
|
||||
result.push(todos[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Example usage
|
||||
addTodo("Buy groceries", "high");
|
||||
addTodo("Clean house");
|
||||
addTodo("Pay bills", "high");
|
||||
toggleTodo(2);
|
||||
|
||||
console.log("All todos:", todos);
|
||||
console.log("High priority todos:", filterByPriority("high"));
|
||||
console.log("Completed todos:", filterByStatus(true));
|
||||
|
||||
export {
|
||||
addTodo,
|
||||
changePriority,
|
||||
deleteTodo,
|
||||
filterByPriority,
|
||||
filterByStatus,
|
||||
todos,
|
||||
toggleTodo,
|
||||
updateTodoText,
|
||||
};
|
||||
323
manual-testing-sandbox/next-edit/next-edit-4-2-sol.ts
Normal file
323
manual-testing-sandbox/next-edit/next-edit-4-2-sol.ts
Normal file
|
|
@ -0,0 +1,323 @@
|
|||
// Event Tracker System - Refactored Solution
|
||||
// Original: next-edit-4-2.ts
|
||||
// Refactored to follow SOLID principles
|
||||
|
||||
// Types
|
||||
type EventCategory = "meeting" | "conference" | "workshop" | "other";
|
||||
|
||||
interface Event {
|
||||
id: number;
|
||||
name: string;
|
||||
date: Date;
|
||||
attendees: string[];
|
||||
location?: string;
|
||||
category?: EventCategory;
|
||||
}
|
||||
|
||||
// EventRepository - Handles data storage and retrieval
|
||||
class EventRepository {
|
||||
private events: Event[] = [];
|
||||
private nextEventId = 1;
|
||||
|
||||
getAll(): Event[] {
|
||||
return [...this.events];
|
||||
}
|
||||
|
||||
getById(eventId: number): Event | undefined {
|
||||
return this.events.find((event) => event.id === eventId);
|
||||
}
|
||||
|
||||
add(event: Omit<Event, "id">): number {
|
||||
const newEvent: Event = {
|
||||
...event,
|
||||
id: this.nextEventId++,
|
||||
};
|
||||
|
||||
this.events.push(newEvent);
|
||||
return newEvent.id;
|
||||
}
|
||||
|
||||
update(eventId: number, eventUpdates: Partial<Omit<Event, "id">>): boolean {
|
||||
const eventIndex = this.findEventIndex(eventId);
|
||||
if (eventIndex === -1) return false;
|
||||
|
||||
this.events[eventIndex] = {
|
||||
...this.events[eventIndex],
|
||||
...eventUpdates,
|
||||
};
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
remove(eventId: number): boolean {
|
||||
const eventIndex = this.findEventIndex(eventId);
|
||||
if (eventIndex === -1) return false;
|
||||
|
||||
this.events.splice(eventIndex, 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
findByDateRange(startDate: Date, endDate: Date): Event[] {
|
||||
return this.events.filter(
|
||||
(event) => event.date >= startDate && event.date <= endDate,
|
||||
);
|
||||
}
|
||||
|
||||
findByCategory(category: EventCategory): Event[] {
|
||||
return this.events.filter((event) => event.category === category);
|
||||
}
|
||||
|
||||
private findEventIndex(eventId: number): number {
|
||||
return this.events.findIndex((event) => event.id === eventId);
|
||||
}
|
||||
}
|
||||
|
||||
// EventService - Handles business logic
|
||||
class EventService {
|
||||
constructor(private repository: EventRepository) {}
|
||||
|
||||
createEvent(
|
||||
name: string,
|
||||
date: Date,
|
||||
attendees: string[],
|
||||
location?: string,
|
||||
category?: EventCategory,
|
||||
): number {
|
||||
return this.repository.add({
|
||||
name,
|
||||
date,
|
||||
attendees,
|
||||
location,
|
||||
category,
|
||||
});
|
||||
}
|
||||
|
||||
updateEvent(eventId: number, updates: Partial<Omit<Event, "id">>): boolean {
|
||||
return this.repository.update(eventId, updates);
|
||||
}
|
||||
|
||||
removeEvent(eventId: number): boolean {
|
||||
return this.repository.remove(eventId);
|
||||
}
|
||||
|
||||
addAttendee(eventId: number, attendeeName: string): boolean {
|
||||
const event = this.repository.getById(eventId);
|
||||
if (!event) return false;
|
||||
|
||||
// Don't add if already exists
|
||||
if (event.attendees.includes(attendeeName)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return this.repository.update(eventId, {
|
||||
attendees: [...event.attendees, attendeeName],
|
||||
});
|
||||
}
|
||||
|
||||
removeAttendee(eventId: number, attendeeName: string): boolean {
|
||||
const event = this.repository.getById(eventId);
|
||||
if (!event) return false;
|
||||
|
||||
const initialCount = event.attendees.length;
|
||||
const updatedAttendees = event.attendees.filter(
|
||||
(name) => name !== attendeeName,
|
||||
);
|
||||
|
||||
if (initialCount === updatedAttendees.length) {
|
||||
return false; // Attendee wasn't in the list
|
||||
}
|
||||
|
||||
return this.repository.update(eventId, {
|
||||
attendees: updatedAttendees,
|
||||
});
|
||||
}
|
||||
|
||||
getEventsByDateRange(startDate: Date, endDate: Date): Event[] {
|
||||
return this.repository.findByDateRange(startDate, endDate);
|
||||
}
|
||||
|
||||
getEventsByCategory(category: EventCategory): Event[] {
|
||||
return this.repository.findByCategory(category);
|
||||
}
|
||||
|
||||
getAllEvents(): Event[] {
|
||||
return this.repository.getAll();
|
||||
}
|
||||
}
|
||||
|
||||
// Create instances for use
|
||||
const eventRepository = new EventRepository();
|
||||
const eventService = new EventService(eventRepository);
|
||||
|
||||
// Example usage
|
||||
eventService.createEvent(
|
||||
"Team Meeting",
|
||||
new Date("2023-06-15T10:00:00"),
|
||||
["Alice", "Bob", "Charlie"],
|
||||
"Conference Room A",
|
||||
"meeting",
|
||||
);
|
||||
|
||||
eventService.createEvent(
|
||||
"JavaScript Workshop",
|
||||
new Date("2023-06-20T14:00:00"),
|
||||
["David", "Eve"],
|
||||
"Training Center",
|
||||
"workshop",
|
||||
);
|
||||
|
||||
console.log("All events:", eventService.getAllEvents());
|
||||
eventService.addAttendee(1, "Frank");
|
||||
console.log("Events after adding Frank:", eventService.getAllEvents());
|
||||
|
||||
// Export functions with the same interface as the original for backward compatibility
|
||||
export const events = eventService.getAllEvents();
|
||||
|
||||
export function add_event(
|
||||
eventName: string,
|
||||
eventDate: Date,
|
||||
attendees: string[],
|
||||
location?: string,
|
||||
category?: EventCategory,
|
||||
): number {
|
||||
return eventService.createEvent(
|
||||
eventName,
|
||||
eventDate,
|
||||
attendees,
|
||||
location,
|
||||
category,
|
||||
);
|
||||
}
|
||||
|
||||
export function removeEvent(eventId: number): boolean {
|
||||
return eventService.removeEvent(eventId);
|
||||
}
|
||||
|
||||
export function updateEvent(
|
||||
eventId: number,
|
||||
name?: string,
|
||||
date?: Date,
|
||||
attendees?: string[],
|
||||
location?: string,
|
||||
category?: EventCategory,
|
||||
): boolean {
|
||||
return eventService.updateEvent(eventId, {
|
||||
name,
|
||||
date,
|
||||
attendees,
|
||||
location,
|
||||
category,
|
||||
});
|
||||
}
|
||||
|
||||
export function addAttendeeToEvent(
|
||||
eventId: number,
|
||||
attendeeName: string,
|
||||
): boolean {
|
||||
return eventService.addAttendee(eventId, attendeeName);
|
||||
}
|
||||
|
||||
export function removeAttendeeFromEvent(
|
||||
eventId: number,
|
||||
attendeeName: string,
|
||||
): boolean {
|
||||
return eventService.removeAttendee(eventId, attendeeName);
|
||||
}
|
||||
|
||||
export function getEventsByDateRange(startDate: Date, endDate: Date): Event[] {
|
||||
return eventService.getEventsByDateRange(startDate, endDate);
|
||||
}
|
||||
|
||||
export function getEventsByCategory(category: EventCategory): Event[] {
|
||||
return eventService.getEventsByCategory(category);
|
||||
}
|
||||
|
||||
// For direct use of the service in new code
|
||||
export { Event, EventCategory, EventRepository, EventService };
|
||||
|
||||
/*
|
||||
Code Smells in next-edit-4-2.ts:
|
||||
Violation of Single Responsibility Principle:
|
||||
|
||||
The code mixes data storage, business logic, and usage in one flat file
|
||||
Global state management with events array and nextEventId variable
|
||||
Poor Encapsulation:
|
||||
|
||||
Direct manipulation of the global events array
|
||||
No protection against external modification of data
|
||||
Inconsistent Naming Conventions:
|
||||
|
||||
Mix of snake_case (add_event) and camelCase (removeEvent)
|
||||
Lack of consistent function naming patterns
|
||||
Duplicated Logic:
|
||||
|
||||
Repeated event lookup code in multiple functions
|
||||
Multiple loops to find events by ID
|
||||
Inefficient Algorithms:
|
||||
|
||||
Linear searches through arrays instead of using more efficient methods
|
||||
Manual implementation of array operations that have built-in methods
|
||||
No Separation of Concerns:
|
||||
|
||||
No distinction between data access and business logic
|
||||
No clear architecture or organization
|
||||
Mutable Shared State:
|
||||
|
||||
Direct modification of the global events array
|
||||
No immutability principles
|
||||
|
||||
|
||||
Improvements Made:
|
||||
|
||||
Applied SOLID Principles:
|
||||
|
||||
Single Responsibility: Split into EventRepository (data storage) and EventService (business logic)
|
||||
Open/Closed: Better structure for extending functionality without modifying existing code
|
||||
Interface Segregation: Cleaner interfaces with focused responsibilities
|
||||
Dependency Inversion: Service depends on repository abstraction
|
||||
|
||||
|
||||
Improved Encapsulation:
|
||||
|
||||
Added proper classes with private fields
|
||||
Controlled access to data through methods
|
||||
Immutable return values (using spreads and filters)
|
||||
|
||||
|
||||
Consistent Naming:
|
||||
|
||||
All methods follow camelCase convention
|
||||
More descriptive and consistent naming patterns
|
||||
|
||||
|
||||
Removed Duplication:
|
||||
|
||||
Centralized event lookup in the repository
|
||||
Reused code through proper method calls
|
||||
|
||||
|
||||
More Efficient Algorithms:
|
||||
|
||||
Used built-in array methods (find, filter, etc.) instead of manual loops
|
||||
Simplified attendee management logic
|
||||
|
||||
|
||||
Clear Separation of Concerns:
|
||||
|
||||
Repository handles data access
|
||||
Service handles business logic
|
||||
Maintained backward compatibility with original exports
|
||||
|
||||
|
||||
Better Type Definitions:
|
||||
|
||||
Extracted EventCategory type
|
||||
Used TypeScript features like Partial and Omit for more precise typing
|
||||
Added proper interfaces
|
||||
|
||||
|
||||
Maintained Backward Compatibility:
|
||||
|
||||
Kept original function exports to ensure existing code can work
|
||||
Added additional exports for new usage patterns
|
||||
*/
|
||||
161
manual-testing-sandbox/next-edit/next-edit-4-2.ts
Normal file
161
manual-testing-sandbox/next-edit/next-edit-4-2.ts
Normal file
|
|
@ -0,0 +1,161 @@
|
|||
// A messy event tracker system
|
||||
// Difficulty: 2 - Multiple issues to fix
|
||||
|
||||
type Event = {
|
||||
id: number;
|
||||
name: string;
|
||||
date: Date;
|
||||
attendees: string[];
|
||||
location?: string;
|
||||
category?: "meeting" | "conference" | "workshop" | "other";
|
||||
};
|
||||
|
||||
// Global event store
|
||||
let events: Event[] = [];
|
||||
let nextEventId = 1;
|
||||
|
||||
// Add event
|
||||
function add_event(
|
||||
eventName: string,
|
||||
eventDate: Date,
|
||||
attendees: string[],
|
||||
location?: string,
|
||||
category?: "meeting" | "conference" | "workshop" | "other",
|
||||
) {
|
||||
const event: Event = {
|
||||
id: nextEventId++,
|
||||
name: eventName,
|
||||
date: eventDate,
|
||||
attendees: attendees,
|
||||
location: location,
|
||||
category: category,
|
||||
};
|
||||
|
||||
events.push(event);
|
||||
return event.id;
|
||||
}
|
||||
|
||||
// Remove event
|
||||
function removeEvent(eventId: number) {
|
||||
let idx = -1;
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
if (events[i].id === eventId) {
|
||||
idx = i;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (idx >= 0) {
|
||||
events.splice(idx, 1);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update event
|
||||
function updateEvent(
|
||||
eventId: number,
|
||||
name?: string,
|
||||
date?: Date,
|
||||
attendees?: string[],
|
||||
location?: string,
|
||||
category?: "meeting" | "conference" | "workshop" | "other",
|
||||
) {
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
if (events[i].id === eventId) {
|
||||
if (name !== undefined) events[i].name = name;
|
||||
if (date !== undefined) events[i].date = date;
|
||||
if (attendees !== undefined) events[i].attendees = attendees;
|
||||
if (location !== undefined) events[i].location = location;
|
||||
if (category !== undefined) events[i].category = category;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Add attendee to event
|
||||
function addAttendeeToEvent(eventId: number, attendeeName: string) {
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
if (events[i].id === eventId) {
|
||||
// Check if attendee already exists
|
||||
let exists = false;
|
||||
for (let j = 0; j < events[i].attendees.length; j++) {
|
||||
if (events[i].attendees[j] === attendeeName) {
|
||||
exists = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
if (!exists) {
|
||||
events[i].attendees.push(attendeeName);
|
||||
}
|
||||
return !exists;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Remove attendee from event
|
||||
function removeAttendeeFromEvent(eventId: number, attendeeName: string) {
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
if (events[i].id === eventId) {
|
||||
const initialLength = events[i].attendees.length;
|
||||
events[i].attendees = events[i].attendees.filter(
|
||||
(a) => a !== attendeeName,
|
||||
);
|
||||
return events[i].attendees.length !== initialLength;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Get events by date range
|
||||
function getEventsByDateRange(startDate: Date, endDate: Date) {
|
||||
const result = [];
|
||||
for (let i = 0; i < events.length; i++) {
|
||||
if (events[i].date >= startDate && events[i].date <= endDate) {
|
||||
result.push(events[i]);
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
// Get events by category
|
||||
function getEventsByCategory(
|
||||
category: "meeting" | "conference" | "workshop" | "other",
|
||||
) {
|
||||
return events.filter((e) => e.category === category);
|
||||
}
|
||||
|
||||
// Example usage
|
||||
add_event(
|
||||
"Team Meeting",
|
||||
new Date("2023-06-15T10:00:00"),
|
||||
["Alice", "Bob", "Charlie"],
|
||||
"Conference Room A",
|
||||
"meeting",
|
||||
);
|
||||
|
||||
add_event(
|
||||
"JavaScript Workshop",
|
||||
new Date("2023-06-20T14:00:00"),
|
||||
["David", "Eve"],
|
||||
"Training Center",
|
||||
"workshop",
|
||||
);
|
||||
|
||||
console.log("All events:", events);
|
||||
addAttendeeToEvent(1, "Frank");
|
||||
console.log("Events after adding Frank:", events);
|
||||
|
||||
export {
|
||||
add_event,
|
||||
addAttendeeToEvent,
|
||||
events,
|
||||
getEventsByCategory,
|
||||
getEventsByDateRange,
|
||||
removeAttendeeFromEvent,
|
||||
removeEvent,
|
||||
updateEvent,
|
||||
};
|
||||
371
manual-testing-sandbox/next-edit/next-edit-5-3-sol.ts
Normal file
371
manual-testing-sandbox/next-edit/next-edit-5-3-sol.ts
Normal file
|
|
@ -0,0 +1,371 @@
|
|||
// Refactored shopping cart implementation following SOLID principles
|
||||
|
||||
// Types and interfaces
|
||||
interface Product {
|
||||
id: number;
|
||||
name: string;
|
||||
price: number;
|
||||
stock: number;
|
||||
category: string;
|
||||
}
|
||||
|
||||
interface CartItem {
|
||||
productId: number;
|
||||
quantity: number;
|
||||
price: number;
|
||||
}
|
||||
|
||||
interface Discount {
|
||||
percentage: number;
|
||||
minPurchase: number;
|
||||
category?: string;
|
||||
}
|
||||
|
||||
interface UserInfo {
|
||||
name: string;
|
||||
email: string;
|
||||
address?: Address;
|
||||
}
|
||||
|
||||
interface Address {
|
||||
street: string;
|
||||
city: string;
|
||||
zipCode: string;
|
||||
country: string;
|
||||
}
|
||||
|
||||
interface CartSummary {
|
||||
items: CartItem[];
|
||||
total: number;
|
||||
discountCode: string | null;
|
||||
user: UserInfo | null;
|
||||
}
|
||||
|
||||
// Product catalog
|
||||
const PRODUCTS: Record<number, Product> = {
|
||||
1: {
|
||||
id: 1,
|
||||
name: "Laptop",
|
||||
price: 999.99,
|
||||
stock: 10,
|
||||
category: "electronics",
|
||||
},
|
||||
2: {
|
||||
id: 2,
|
||||
name: "Smartphone",
|
||||
price: 699.99,
|
||||
stock: 15,
|
||||
category: "electronics",
|
||||
},
|
||||
3: {
|
||||
id: 3,
|
||||
name: "Headphones",
|
||||
price: 149.99,
|
||||
stock: 20,
|
||||
category: "electronics",
|
||||
},
|
||||
4: { id: 4, name: "Desk", price: 249.99, stock: 5, category: "furniture" },
|
||||
5: { id: 5, name: "Chair", price: 179.99, stock: 8, category: "furniture" },
|
||||
};
|
||||
|
||||
// Discount codes
|
||||
const DISCOUNT_CODES: Record<string, Discount> = {
|
||||
SAVE10: { percentage: 10, minPurchase: 0 },
|
||||
SAVE20: { percentage: 20, minPurchase: 500 },
|
||||
FURNITURE15: { percentage: 15, minPurchase: 0, category: "furniture" },
|
||||
};
|
||||
|
||||
// Shopping cart class that follows Single Responsibility Principle
|
||||
class ShoppingCart {
|
||||
private items: CartItem[] = [];
|
||||
private total: number = 0;
|
||||
private discountCode: string | null = null;
|
||||
private userInfo: UserInfo | null = null;
|
||||
|
||||
// Add product to cart
|
||||
public addToCart(productId: number, quantity: number = 1): boolean {
|
||||
// Check if product exists
|
||||
if (!PRODUCTS[productId]) {
|
||||
console.error("Product not found!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if enough stock
|
||||
if (PRODUCTS[productId].stock < quantity) {
|
||||
console.error("Not enough stock!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if product already in cart
|
||||
const existingItemIndex = this.findItemIndex(productId);
|
||||
|
||||
if (existingItemIndex !== -1) {
|
||||
// Update quantity if product already in cart
|
||||
this.items[existingItemIndex].quantity += quantity;
|
||||
} else {
|
||||
// Add new item if not already in cart
|
||||
this.items.push({
|
||||
productId,
|
||||
quantity,
|
||||
price: PRODUCTS[productId].price,
|
||||
});
|
||||
}
|
||||
|
||||
// Update stock
|
||||
PRODUCTS[productId].stock -= quantity;
|
||||
|
||||
// Recalculate cart total
|
||||
this.calculateCartTotal();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Remove product from cart
|
||||
public removeFromCart(productId: number, quantity: number = 1): boolean {
|
||||
const itemIndex = this.findItemIndex(productId);
|
||||
|
||||
if (itemIndex === -1) {
|
||||
console.error("Product not in cart!");
|
||||
return false;
|
||||
}
|
||||
|
||||
const item = this.items[itemIndex];
|
||||
|
||||
// Determine quantity to remove
|
||||
const qtyToRemove = Math.min(item.quantity, quantity);
|
||||
|
||||
// Return stock
|
||||
PRODUCTS[productId].stock += qtyToRemove;
|
||||
|
||||
// Update cart item
|
||||
item.quantity -= qtyToRemove;
|
||||
|
||||
// Remove item if quantity is 0
|
||||
if (item.quantity === 0) {
|
||||
this.items.splice(itemIndex, 1);
|
||||
}
|
||||
|
||||
// Recalculate cart total
|
||||
this.calculateCartTotal();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Calculate cart total
|
||||
public calculateCartTotal(): number {
|
||||
let total = this.calculateSubtotal();
|
||||
|
||||
// Apply discount if any
|
||||
if (this.discountCode) {
|
||||
total = this.applyDiscountToTotal(total);
|
||||
}
|
||||
|
||||
this.total = total;
|
||||
return this.total;
|
||||
}
|
||||
|
||||
// Calculate subtotal without discounts
|
||||
private calculateSubtotal(): number {
|
||||
return this.items.reduce(
|
||||
(sum, item) => sum + item.price * item.quantity,
|
||||
0,
|
||||
);
|
||||
}
|
||||
|
||||
// Apply discount to total
|
||||
private applyDiscountToTotal(total: number): number {
|
||||
if (!this.discountCode) return total;
|
||||
|
||||
const discount = DISCOUNT_CODES[this.discountCode];
|
||||
|
||||
// Check if discount applies to specific category
|
||||
if (discount.category) {
|
||||
return this.applyCategoryDiscount(total, discount);
|
||||
} else {
|
||||
// Apply discount to entire cart
|
||||
const discountAmount = total * (discount.percentage / 100);
|
||||
return total - discountAmount;
|
||||
}
|
||||
}
|
||||
|
||||
// Apply category-specific discount
|
||||
private applyCategoryDiscount(total: number, discount: Discount): number {
|
||||
let categoryTotal = 0;
|
||||
|
||||
for (const item of this.items) {
|
||||
if (PRODUCTS[item.productId].category === discount.category) {
|
||||
categoryTotal += item.price * item.quantity;
|
||||
}
|
||||
}
|
||||
|
||||
// Apply discount to category total
|
||||
const discountAmount = categoryTotal * (discount.percentage / 100);
|
||||
return total - discountAmount;
|
||||
}
|
||||
|
||||
// Apply discount code
|
||||
public applyDiscountCode(code: string): boolean {
|
||||
// Check if discount code exists
|
||||
if (!DISCOUNT_CODES[code]) {
|
||||
console.error("Invalid discount code!");
|
||||
return false;
|
||||
}
|
||||
|
||||
const discount = DISCOUNT_CODES[code];
|
||||
|
||||
// Check minimum purchase requirement
|
||||
if (this.total < discount.minPurchase) {
|
||||
console.error(
|
||||
`Minimum purchase of $${discount.minPurchase} required for this code!`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Apply discount code
|
||||
this.discountCode = code;
|
||||
|
||||
// Recalculate total
|
||||
this.calculateCartTotal();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Set user information
|
||||
public setUserInfo(name: string, email: string, address?: Address): boolean {
|
||||
this.userInfo = { name, email, address };
|
||||
return true;
|
||||
}
|
||||
|
||||
// Find item index in cart
|
||||
private findItemIndex(productId: number): number {
|
||||
return this.items.findIndex((item) => item.productId === productId);
|
||||
}
|
||||
|
||||
// Checkout
|
||||
public checkout(): boolean {
|
||||
// Validate cart
|
||||
if (this.items.length === 0) {
|
||||
console.error("Cart is empty!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Validate user info
|
||||
if (!this.userInfo || !this.userInfo.name || !this.userInfo.email) {
|
||||
console.error("User information incomplete!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Process payment (simplified)
|
||||
console.log("Processing payment for $" + this.total);
|
||||
console.log("Items:", this.items);
|
||||
console.log("User:", this.userInfo);
|
||||
|
||||
// Clear cart after successful checkout
|
||||
this.clearCart();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Clear cart
|
||||
private clearCart(): void {
|
||||
this.items = [];
|
||||
this.total = 0;
|
||||
this.discountCode = null;
|
||||
}
|
||||
|
||||
// Get cart summary
|
||||
public getCartSummary(): CartSummary {
|
||||
return {
|
||||
items: [...this.items], // Return a copy to prevent direct mutation
|
||||
total: this.total,
|
||||
discountCode: this.discountCode,
|
||||
user: this.userInfo,
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
// Create cart instance
|
||||
const cart = new ShoppingCart();
|
||||
|
||||
// Example usage
|
||||
cart.addToCart(1, 2); // Add 2 laptops
|
||||
cart.addToCart(3, 1); // Add 1 headphones
|
||||
cart.applyDiscountCode("SAVE10");
|
||||
cart.setUserInfo("John Doe", "john@example.com", {
|
||||
street: "123 Main St",
|
||||
city: "Anytown",
|
||||
zipCode: "12345",
|
||||
country: "USA",
|
||||
});
|
||||
|
||||
console.log(cart.getCartSummary());
|
||||
|
||||
// Export for module usage
|
||||
export {
|
||||
Address,
|
||||
cart,
|
||||
CartItem,
|
||||
CartSummary,
|
||||
Discount,
|
||||
DISCOUNT_CODES,
|
||||
Product,
|
||||
PRODUCTS,
|
||||
ShoppingCart,
|
||||
UserInfo,
|
||||
};
|
||||
|
||||
/*
|
||||
Code Smells in the Original File
|
||||
Global State: The code uses global variables for cart state, making it difficult to track changes and prone to side effects.
|
||||
|
||||
Lack of Encapsulation: Data and functions are not properly encapsulated, allowing direct manipulation of state from anywhere.
|
||||
|
||||
No Type Definitions: Lack of proper TypeScript interfaces for the domain entities.
|
||||
|
||||
Procedural Code: Functions operating on global state rather than object-oriented approach.
|
||||
|
||||
Poor Data Structure Access: Using for loops with indexes instead of more expressive array methods.
|
||||
|
||||
Mixed Responsibilities: Functions are handling multiple concerns (validation, business logic, data modification).
|
||||
|
||||
Duplicated Logic: Same validation and calculation logic repeated in multiple places.
|
||||
|
||||
No Clear Separation of Concerns: Business logic mixed with presentation logic (console logs).
|
||||
|
||||
No Protection Against Direct Mutation: The cart data can be modified directly.
|
||||
|
||||
|
||||
Improvements Made
|
||||
|
||||
Created a Class-Based Design: Encapsulated cart functionality in a ShoppingCart class
|
||||
|
||||
Added Strong Typing: Defined interfaces for all domain entities (Product, CartItem, Discount, UserInfo, Address, CartSummary)
|
||||
|
||||
Single Responsibility Principle: Separated methods for different concerns (e.g., split discount calculation into multiple methods)
|
||||
|
||||
Encapsulation: Made cart items and state private, only accessible through methods
|
||||
|
||||
Immutability: Return copies of data structures to prevent external modification
|
||||
|
||||
Modern JavaScript/TypeScript Patterns:
|
||||
|
||||
Used array methods like reduce, findIndex instead of for loops
|
||||
Used parameter defaults, array spread operators
|
||||
|
||||
|
||||
Better Method Organization:
|
||||
|
||||
Split large methods into smaller, focused ones
|
||||
Created private helper methods for internal operations
|
||||
|
||||
|
||||
Improved Validation: Centralized validation logic in appropriate methods
|
||||
|
||||
Better Error Handling: Consistent error reporting approach
|
||||
|
||||
Code Reusability: Extracted reusable logic into dedicated methods
|
||||
|
||||
Defensive Programming: Added checks to prevent invalid operations
|
||||
|
||||
Cleaner API Design: Created a clear public interface for the cart functionality
|
||||
*/
|
||||
262
manual-testing-sandbox/next-edit/next-edit-5-3.ts
Normal file
262
manual-testing-sandbox/next-edit/next-edit-5-3.ts
Normal file
|
|
@ -0,0 +1,262 @@
|
|||
// A disorganized shopping cart implementation
|
||||
// Difficulty: 3 - Moderate refactoring needed
|
||||
|
||||
// Product catalog
|
||||
const PRODUCTS = {
|
||||
1: {
|
||||
id: 1,
|
||||
name: "Laptop",
|
||||
price: 999.99,
|
||||
stock: 10,
|
||||
category: "electronics",
|
||||
},
|
||||
2: {
|
||||
id: 2,
|
||||
name: "Smartphone",
|
||||
price: 699.99,
|
||||
stock: 15,
|
||||
category: "electronics",
|
||||
},
|
||||
3: {
|
||||
id: 3,
|
||||
name: "Headphones",
|
||||
price: 149.99,
|
||||
stock: 20,
|
||||
category: "electronics",
|
||||
},
|
||||
4: { id: 4, name: "Desk", price: 249.99, stock: 5, category: "furniture" },
|
||||
5: { id: 5, name: "Chair", price: 179.99, stock: 8, category: "furniture" },
|
||||
};
|
||||
|
||||
// Discount codes
|
||||
const DISCOUNT_CODES = {
|
||||
SAVE10: { percentage: 10, minPurchase: 0 },
|
||||
SAVE20: { percentage: 20, minPurchase: 500 },
|
||||
FURNITURE15: { percentage: 15, minPurchase: 0, category: "furniture" },
|
||||
};
|
||||
|
||||
// Cart state
|
||||
let cartItems: { productId: number; quantity: number; price: number }[] = [];
|
||||
let cartTotal = 0;
|
||||
let appliedDiscountCode: string | null = null;
|
||||
|
||||
// User info
|
||||
let userInfo: {
|
||||
name: string;
|
||||
email: string;
|
||||
address?: {
|
||||
street: string;
|
||||
city: string;
|
||||
zipCode: string;
|
||||
country: string;
|
||||
};
|
||||
} | null = null;
|
||||
|
||||
// Add product to cart
|
||||
function addToCart(productId: number, quantity: number = 1) {
|
||||
// Check if product exists
|
||||
if (!PRODUCTS[productId]) {
|
||||
console.error("Product not found!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if enough stock
|
||||
if (PRODUCTS[productId].stock < quantity) {
|
||||
console.error("Not enough stock!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if product already in cart
|
||||
let existingItem = false;
|
||||
for (let i = 0; i < cartItems.length; i++) {
|
||||
if (cartItems[i].productId === productId) {
|
||||
// Update quantity
|
||||
cartItems[i].quantity += quantity;
|
||||
existingItem = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
// Add new item if not already in cart
|
||||
if (!existingItem) {
|
||||
cartItems.push({
|
||||
productId,
|
||||
quantity,
|
||||
price: PRODUCTS[productId].price,
|
||||
});
|
||||
}
|
||||
|
||||
// Update stock
|
||||
PRODUCTS[productId].stock -= quantity;
|
||||
|
||||
// Recalculate cart total
|
||||
calculateCartTotal();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Remove product from cart
|
||||
function removeFromCart(productId: number, quantity: number = 1) {
|
||||
for (let i = 0; i < cartItems.length; i++) {
|
||||
if (cartItems[i].productId === productId) {
|
||||
// Determine quantity to remove
|
||||
const qtyToRemove = Math.min(cartItems[i].quantity, quantity);
|
||||
|
||||
// Return stock
|
||||
PRODUCTS[productId].stock += qtyToRemove;
|
||||
|
||||
// Update cart item
|
||||
cartItems[i].quantity -= qtyToRemove;
|
||||
|
||||
// Remove item if quantity is 0
|
||||
if (cartItems[i].quantity === 0) {
|
||||
cartItems.splice(i, 1);
|
||||
}
|
||||
|
||||
// Recalculate cart total
|
||||
calculateCartTotal();
|
||||
|
||||
return true;
|
||||
}
|
||||
}
|
||||
|
||||
console.error("Product not in cart!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Calculate cart total
|
||||
function calculateCartTotal() {
|
||||
let total = 0;
|
||||
|
||||
// Sum all items
|
||||
for (let i = 0; i < cartItems.length; i++) {
|
||||
const item = cartItems[i];
|
||||
total += item.price * item.quantity;
|
||||
}
|
||||
|
||||
// Apply discount if any
|
||||
if (appliedDiscountCode) {
|
||||
const discount = DISCOUNT_CODES[appliedDiscountCode];
|
||||
|
||||
// Check if discount applies to specific category
|
||||
if (discount.category) {
|
||||
let categoryTotal = 0;
|
||||
for (let i = 0; i < cartItems.length; i++) {
|
||||
const item = cartItems[i];
|
||||
if (PRODUCTS[item.productId].category === discount.category) {
|
||||
categoryTotal += item.price * item.quantity;
|
||||
}
|
||||
}
|
||||
|
||||
// Apply discount to category total
|
||||
const discountAmount = categoryTotal * (discount.percentage / 100);
|
||||
total -= discountAmount;
|
||||
} else {
|
||||
// Apply discount to entire cart
|
||||
const discountAmount = total * (discount.percentage / 100);
|
||||
total -= discountAmount;
|
||||
}
|
||||
}
|
||||
|
||||
cartTotal = total;
|
||||
return cartTotal;
|
||||
}
|
||||
|
||||
// Apply discount code
|
||||
function applyDiscountCode(code: string) {
|
||||
// Check if discount code exists
|
||||
if (!DISCOUNT_CODES[code]) {
|
||||
console.error("Invalid discount code!");
|
||||
return false;
|
||||
}
|
||||
|
||||
const discount = DISCOUNT_CODES[code];
|
||||
|
||||
// Check minimum purchase requirement
|
||||
if (cartTotal < discount.minPurchase) {
|
||||
console.error(
|
||||
`Minimum purchase of $${discount.minPurchase} required for this code!`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Apply discount code
|
||||
appliedDiscountCode = code;
|
||||
|
||||
// Recalculate total
|
||||
calculateCartTotal();
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Set user information
|
||||
function setUserInfo(
|
||||
name: string,
|
||||
email: string,
|
||||
address?: { street: string; city: string; zipCode: string; country: string },
|
||||
) {
|
||||
userInfo = { name, email, address };
|
||||
return true;
|
||||
}
|
||||
|
||||
// Checkout
|
||||
function checkout() {
|
||||
// Validate cart
|
||||
if (cartItems.length === 0) {
|
||||
console.error("Cart is empty!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Validate user info
|
||||
if (!userInfo || !userInfo.name || !userInfo.email) {
|
||||
console.error("User information incomplete!");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Process payment (simplified)
|
||||
console.log("Processing payment for $" + cartTotal);
|
||||
console.log("Items:", cartItems);
|
||||
console.log("User:", userInfo);
|
||||
|
||||
// Clear cart after successful checkout
|
||||
cartItems = [];
|
||||
cartTotal = 0;
|
||||
appliedDiscountCode = null;
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Get cart summary
|
||||
function getCartSummary() {
|
||||
return {
|
||||
items: cartItems,
|
||||
total: cartTotal,
|
||||
discountCode: appliedDiscountCode,
|
||||
user: userInfo,
|
||||
};
|
||||
}
|
||||
|
||||
// Example usage
|
||||
addToCart(1, 2); // Add 2 laptops
|
||||
addToCart(3, 1); // Add 1 headphones
|
||||
applyDiscountCode("SAVE10");
|
||||
setUserInfo("John Doe", "john@example.com", {
|
||||
street: "123 Main St",
|
||||
city: "Anytown",
|
||||
zipCode: "12345",
|
||||
country: "USA",
|
||||
});
|
||||
|
||||
console.log(getCartSummary());
|
||||
|
||||
export {
|
||||
addToCart,
|
||||
applyDiscountCode,
|
||||
calculateCartTotal,
|
||||
checkout,
|
||||
DISCOUNT_CODES,
|
||||
getCartSummary,
|
||||
PRODUCTS,
|
||||
removeFromCart,
|
||||
setUserInfo,
|
||||
};
|
||||
668
manual-testing-sandbox/next-edit/next-edit-6-3-sol.ts
Normal file
668
manual-testing-sandbox/next-edit/next-edit-6-3-sol.ts
Normal file
|
|
@ -0,0 +1,668 @@
|
|||
// Refactored file upload and management system following SOLID principles
|
||||
// Original: next-edit-6-3.ts
|
||||
|
||||
// Types
|
||||
interface FileData {
|
||||
id: string;
|
||||
name: string;
|
||||
size: number;
|
||||
type: string;
|
||||
uploadDate: Date;
|
||||
uploadedBy: string;
|
||||
path: string;
|
||||
isPublic: boolean;
|
||||
tags?: string[];
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: "admin" | "user" | "guest";
|
||||
}
|
||||
|
||||
interface FileQuery {
|
||||
name?: string;
|
||||
type?: string;
|
||||
tags?: string[];
|
||||
uploadedBy?: string;
|
||||
isPublic?: boolean;
|
||||
minSize?: number;
|
||||
maxSize?: number;
|
||||
uploadedAfter?: Date;
|
||||
uploadedBefore?: Date;
|
||||
}
|
||||
|
||||
interface FileMetadataUpdate {
|
||||
name?: string;
|
||||
isPublic?: boolean;
|
||||
tags?: string[];
|
||||
metadata?: Record<string, any>;
|
||||
}
|
||||
|
||||
interface StorageStats {
|
||||
used: number;
|
||||
total: number;
|
||||
available: number;
|
||||
fileCount: number;
|
||||
}
|
||||
|
||||
// Constants
|
||||
const MAX_STORAGE = 1024 * 1024 * 1024; // 1GB
|
||||
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
|
||||
|
||||
// User Management
|
||||
class UserManager {
|
||||
private users: Record<string, User>;
|
||||
private currentUser: string | null = null;
|
||||
|
||||
constructor(initialUsers: Record<string, User> = {}) {
|
||||
this.users = initialUsers;
|
||||
}
|
||||
|
||||
login(userId: string): boolean {
|
||||
if (this.users[userId]) {
|
||||
this.currentUser = userId;
|
||||
console.log(`Logged in as ${this.users[userId].name}`);
|
||||
return true;
|
||||
} else {
|
||||
console.error("User not found");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
logout(): boolean {
|
||||
this.currentUser = null;
|
||||
console.log("Logged out");
|
||||
return true;
|
||||
}
|
||||
|
||||
getCurrentUser(): string | null {
|
||||
return this.currentUser;
|
||||
}
|
||||
|
||||
getUser(userId: string): User | null {
|
||||
return this.users[userId] || null;
|
||||
}
|
||||
|
||||
getCurrentUserData(): User | null {
|
||||
return this.currentUser ? this.users[this.currentUser] : null;
|
||||
}
|
||||
|
||||
userExists(userId: string): boolean {
|
||||
return !!this.users[userId];
|
||||
}
|
||||
}
|
||||
|
||||
// File Storage Management
|
||||
class FileStorageManager {
|
||||
private fileStorage: Record<string, FileData> = {};
|
||||
private storageUsed = 0;
|
||||
private readonly maxStorage: number;
|
||||
private readonly maxFileSize: number;
|
||||
private userManager: UserManager;
|
||||
|
||||
constructor(
|
||||
userManager: UserManager,
|
||||
maxStorage = MAX_STORAGE,
|
||||
maxFileSize = MAX_FILE_SIZE,
|
||||
) {
|
||||
this.userManager = userManager;
|
||||
this.maxStorage = maxStorage;
|
||||
this.maxFileSize = maxFileSize;
|
||||
}
|
||||
|
||||
uploadFile(
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
fileType: string,
|
||||
isPublic = false,
|
||||
tags: string[] = [],
|
||||
metadata: Record<string, any> = {},
|
||||
): string | false {
|
||||
const currentUser = this.userManager.getCurrentUser();
|
||||
|
||||
// Check if user is logged in
|
||||
if (!currentUser) {
|
||||
console.error("User not logged in");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check file size
|
||||
if (!this.validateFileSize(fileSize)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check available storage
|
||||
if (!this.hasEnoughStorage(fileSize)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Generate file data
|
||||
const fileId = this.generateFileId();
|
||||
const path = this.createFilePath(currentUser, fileId, fileName);
|
||||
const fileData: FileData = {
|
||||
id: fileId,
|
||||
name: fileName,
|
||||
size: fileSize,
|
||||
type: fileType,
|
||||
uploadDate: new Date(),
|
||||
uploadedBy: currentUser,
|
||||
path,
|
||||
isPublic,
|
||||
tags,
|
||||
metadata,
|
||||
};
|
||||
|
||||
// Save file and update storage
|
||||
this.fileStorage[fileId] = fileData;
|
||||
this.storageUsed += fileSize;
|
||||
|
||||
console.log(`File ${fileName} uploaded successfully`);
|
||||
return fileId;
|
||||
}
|
||||
|
||||
deleteFile(fileId: string): boolean {
|
||||
const currentUser = this.userManager.getCurrentUser();
|
||||
const currentUserData = this.userManager.getCurrentUserData();
|
||||
|
||||
// Check if user is logged in
|
||||
if (!currentUser || !currentUserData) {
|
||||
console.error("User not logged in");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
const file = this.getFileById(fileId);
|
||||
if (!file) {
|
||||
console.error("File not found");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check permissions
|
||||
if (!this.canModifyFile(file, currentUser, currentUserData.role)) {
|
||||
console.error("Permission denied");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update storage and remove file
|
||||
this.storageUsed -= file.size;
|
||||
delete this.fileStorage[fileId];
|
||||
|
||||
console.log(`File ${file.name} deleted successfully`);
|
||||
return true;
|
||||
}
|
||||
|
||||
updateFileMetadata(fileId: string, updates: FileMetadataUpdate): boolean {
|
||||
const currentUser = this.userManager.getCurrentUser();
|
||||
const currentUserData = this.userManager.getCurrentUserData();
|
||||
|
||||
// Check if user is logged in
|
||||
if (!currentUser || !currentUserData) {
|
||||
console.error("User not logged in");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
const file = this.getFileById(fileId);
|
||||
if (!file) {
|
||||
console.error("File not found");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check permissions
|
||||
if (!this.canModifyFile(file, currentUser, currentUserData.role)) {
|
||||
console.error("Permission denied");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update file data
|
||||
if (updates.name !== undefined)
|
||||
this.fileStorage[fileId].name = updates.name;
|
||||
if (updates.isPublic !== undefined)
|
||||
this.fileStorage[fileId].isPublic = updates.isPublic;
|
||||
if (updates.tags !== undefined)
|
||||
this.fileStorage[fileId].tags = updates.tags;
|
||||
if (updates.metadata !== undefined) {
|
||||
this.fileStorage[fileId].metadata = {
|
||||
...this.fileStorage[fileId].metadata,
|
||||
...updates.metadata,
|
||||
};
|
||||
}
|
||||
|
||||
console.log(`File ${file.name} updated successfully`);
|
||||
return true;
|
||||
}
|
||||
|
||||
getFileData(fileId: string): FileData | null {
|
||||
// Check if file exists
|
||||
const file = this.getFileById(fileId);
|
||||
if (!file) {
|
||||
console.error("File not found");
|
||||
return null;
|
||||
}
|
||||
|
||||
const currentUser = this.userManager.getCurrentUser();
|
||||
const currentUserData = this.userManager.getCurrentUserData();
|
||||
|
||||
// Check if user has permission to access
|
||||
if (
|
||||
!file.isPublic &&
|
||||
currentUser !== file.uploadedBy &&
|
||||
currentUserData?.role !== "admin" &&
|
||||
!this.isSharedWithUser(file, currentUser)
|
||||
) {
|
||||
console.error("Permission denied");
|
||||
return null;
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
searchFiles(query: FileQuery): FileData[] {
|
||||
const currentUser = this.userManager.getCurrentUser();
|
||||
const currentUserData = this.userManager.getCurrentUserData();
|
||||
|
||||
// Check if user is logged in
|
||||
if (!currentUser || !currentUserData) {
|
||||
console.error("User not logged in");
|
||||
return [];
|
||||
}
|
||||
|
||||
const results: FileData[] = [];
|
||||
|
||||
// Filter files
|
||||
for (const fileId in this.fileStorage) {
|
||||
const file = this.fileStorage[fileId];
|
||||
|
||||
// Skip files user doesn't have access to
|
||||
if (
|
||||
!file.isPublic &&
|
||||
file.uploadedBy !== currentUser &&
|
||||
currentUserData.role !== "admin" &&
|
||||
!this.isSharedWithUser(file, currentUser)
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
if (this.matchesQuery(file, query)) {
|
||||
results.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
getStorageStats(): StorageStats {
|
||||
return {
|
||||
used: this.storageUsed,
|
||||
total: this.maxStorage,
|
||||
available: this.maxStorage - this.storageUsed,
|
||||
fileCount: Object.keys(this.fileStorage).length,
|
||||
};
|
||||
}
|
||||
|
||||
shareFile(fileId: string, targetUserId: string): boolean {
|
||||
const currentUser = this.userManager.getCurrentUser();
|
||||
const currentUserData = this.userManager.getCurrentUserData();
|
||||
|
||||
// Check if user is logged in
|
||||
if (!currentUser || !currentUserData) {
|
||||
console.error("User not logged in");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
const file = this.getFileById(fileId);
|
||||
if (!file) {
|
||||
console.error("File not found");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if target user exists
|
||||
if (!this.userManager.userExists(targetUserId)) {
|
||||
console.error("Target user not found");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if user has permission
|
||||
if (!this.canModifyFile(file, currentUser, currentUserData.role)) {
|
||||
console.error("Permission denied");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Share file by adding metadata
|
||||
if (!file.metadata) {
|
||||
file.metadata = {};
|
||||
}
|
||||
|
||||
if (!file.metadata.sharedWith) {
|
||||
file.metadata.sharedWith = [];
|
||||
}
|
||||
|
||||
// Check if already shared
|
||||
if (!file.metadata.sharedWith.includes(targetUserId)) {
|
||||
file.metadata.sharedWith.push(targetUserId);
|
||||
}
|
||||
|
||||
const targetUser = this.userManager.getUser(targetUserId);
|
||||
console.log(`File ${file.name} shared with ${targetUser?.name}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Helper methods
|
||||
private generateFileId(): string {
|
||||
return "file_" + Date.now() + "_" + Math.floor(Math.random() * 1000);
|
||||
}
|
||||
|
||||
private createFilePath(
|
||||
userId: string,
|
||||
fileId: string,
|
||||
fileName: string,
|
||||
): string {
|
||||
return `/storage/${userId}/${fileId}_${fileName}`;
|
||||
}
|
||||
|
||||
private getFileById(fileId: string): FileData | null {
|
||||
return this.fileStorage[fileId] || null;
|
||||
}
|
||||
|
||||
private validateFileSize(fileSize: number): boolean {
|
||||
if (fileSize > this.maxFileSize) {
|
||||
console.error(
|
||||
`File too large. Maximum size is ${this.maxFileSize / (1024 * 1024)}MB`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private hasEnoughStorage(fileSize: number): boolean {
|
||||
if (this.storageUsed + fileSize > this.maxStorage) {
|
||||
console.error("Not enough storage space");
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
private canModifyFile(
|
||||
file: FileData,
|
||||
userId: string,
|
||||
userRole: string,
|
||||
): boolean {
|
||||
return file.uploadedBy === userId || userRole === "admin";
|
||||
}
|
||||
|
||||
private isSharedWithUser(file: FileData, userId: string | null): boolean {
|
||||
if (!userId) return false;
|
||||
return !!file.metadata?.sharedWith?.includes(userId);
|
||||
}
|
||||
|
||||
private matchesQuery(file: FileData, query: FileQuery): boolean {
|
||||
// Name filter
|
||||
if (
|
||||
query.name &&
|
||||
!file.name.toLowerCase().includes(query.name.toLowerCase())
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Type filter
|
||||
if (query.type && file.type !== query.type) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Upload user filter
|
||||
if (query.uploadedBy && file.uploadedBy !== query.uploadedBy) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Public/private filter
|
||||
if (query.isPublic !== undefined && file.isPublic !== query.isPublic) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Size range filter
|
||||
if (query.minSize !== undefined && file.size < query.minSize) {
|
||||
return false;
|
||||
}
|
||||
if (query.maxSize !== undefined && file.size > query.maxSize) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Date range filter
|
||||
if (query.uploadedAfter && file.uploadDate < query.uploadedAfter) {
|
||||
return false;
|
||||
}
|
||||
if (query.uploadedBefore && file.uploadDate > query.uploadedBefore) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Tags filter
|
||||
if (query.tags && query.tags.length > 0) {
|
||||
if (!file.tags) {
|
||||
return false;
|
||||
} else {
|
||||
for (const tag of query.tags) {
|
||||
if (!file.tags.includes(tag)) {
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// For testing/export purposes
|
||||
getFileStorage(): Record<string, FileData> {
|
||||
return this.fileStorage;
|
||||
}
|
||||
}
|
||||
|
||||
// Demo Application
|
||||
// Initialize system with users
|
||||
const initialUsers: Record<string, User> = {
|
||||
user1: {
|
||||
id: "user1",
|
||||
name: "Admin User",
|
||||
email: "admin@example.com",
|
||||
role: "admin",
|
||||
},
|
||||
user2: {
|
||||
id: "user2",
|
||||
name: "Regular User",
|
||||
email: "user@example.com",
|
||||
role: "user",
|
||||
},
|
||||
user3: {
|
||||
id: "user3",
|
||||
name: "Guest User",
|
||||
email: "guest@example.com",
|
||||
role: "guest",
|
||||
},
|
||||
};
|
||||
|
||||
// Create system instances
|
||||
const userManager = new UserManager(initialUsers);
|
||||
const fileManager = new FileStorageManager(userManager);
|
||||
|
||||
// Example usage
|
||||
userManager.login("user1");
|
||||
const fileId = fileManager.uploadFile(
|
||||
"document.pdf",
|
||||
1024 * 1024,
|
||||
"application/pdf",
|
||||
false,
|
||||
["important", "document"],
|
||||
);
|
||||
fileManager.updateFileMetadata(fileId as string, { isPublic: true });
|
||||
fileManager.shareFile(fileId as string, "user2");
|
||||
console.log(fileManager.getFileData(fileId as string));
|
||||
console.log(fileManager.getStorageStats());
|
||||
userManager.logout();
|
||||
|
||||
// Exported API for backward compatibility
|
||||
export const fileStorage = fileManager.getFileStorage();
|
||||
export const users = initialUsers;
|
||||
export function login(userId: string): boolean {
|
||||
return userManager.login(userId);
|
||||
}
|
||||
export function logout(): boolean {
|
||||
return userManager.logout();
|
||||
}
|
||||
export function uploadFile(
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
fileType: string,
|
||||
isPublic = false,
|
||||
tags: string[] = [],
|
||||
metadata: Record<string, any> = {},
|
||||
): string | false {
|
||||
return fileManager.uploadFile(
|
||||
fileName,
|
||||
fileSize,
|
||||
fileType,
|
||||
isPublic,
|
||||
tags,
|
||||
metadata,
|
||||
);
|
||||
}
|
||||
export function deleteFile(fileId: string): boolean {
|
||||
return fileManager.deleteFile(fileId);
|
||||
}
|
||||
export function updateFileMetadata(
|
||||
fileId: string,
|
||||
updates: FileMetadataUpdate,
|
||||
): boolean {
|
||||
return fileManager.updateFileMetadata(fileId, updates);
|
||||
}
|
||||
export function getFileData(fileId: string): FileData | null {
|
||||
return fileManager.getFileData(fileId);
|
||||
}
|
||||
export function searchFiles(query: FileQuery): FileData[] {
|
||||
return fileManager.searchFiles(query);
|
||||
}
|
||||
export function getStorageStats(): StorageStats {
|
||||
return fileManager.getStorageStats();
|
||||
}
|
||||
export function shareFile(fileId: string, targetUserId: string): boolean {
|
||||
return fileManager.shareFile(fileId, targetUserId);
|
||||
}
|
||||
|
||||
export {
|
||||
FileData,
|
||||
FileMetadataUpdate,
|
||||
FileQuery,
|
||||
FileStorageManager,
|
||||
StorageStats,
|
||||
User,
|
||||
UserManager,
|
||||
};
|
||||
|
||||
/*
|
||||
Code Smells in the Original File (next-edit-6-3.ts)
|
||||
|
||||
Violation of Single Responsibility Principle (SRP):
|
||||
|
||||
The code mixed user management, file storage, permissions, and business logic in a single file with global state.
|
||||
Functions were handling multiple responsibilities (authentication, validation, business logic).
|
||||
|
||||
|
||||
Global State and Poor Encapsulation:
|
||||
|
||||
Used global variables (fileStorage, users, currentUser, storageUsed) instead of encapsulated state.
|
||||
Direct manipulation of shared state led to potential side effects and made testing difficult.
|
||||
|
||||
|
||||
Lack of Proper Abstractions:
|
||||
|
||||
No separation between data access and business logic.
|
||||
No interfaces defined for the different components of the system.
|
||||
|
||||
|
||||
Repetitive Code:
|
||||
|
||||
Authentication and permission checks repeated in every function.
|
||||
File existence validation duplicated across functions.
|
||||
|
||||
|
||||
Poor Error Handling:
|
||||
|
||||
Inconsistent error reporting (some console.error, some boolean returns).
|
||||
No distinction between different types of errors.
|
||||
|
||||
|
||||
Primitive Obsession:
|
||||
|
||||
Using primitive types instead of creating proper domain objects.
|
||||
|
||||
|
||||
Tight Coupling:
|
||||
|
||||
Functions directly depend on global state.
|
||||
No dependency injection making the code hard to test or extend.
|
||||
|
||||
|
||||
Improvements Made in the Refactored Solution
|
||||
|
||||
Applied Single Responsibility Principle:
|
||||
|
||||
Created separate UserManager and FileStorageManager classes with clear responsibilities.
|
||||
Each method has a single purpose with helper methods for validation and common tasks.
|
||||
|
||||
|
||||
Proper Encapsulation:
|
||||
|
||||
Encapsulated state within classes using private fields.
|
||||
Provided controlled access to state through methods with proper validation.
|
||||
|
||||
|
||||
Improved Type Safety:
|
||||
|
||||
Converted types to interfaces for better type safety.
|
||||
Added specific interfaces for operations (FileQuery, FileMetadataUpdate, etc.).
|
||||
|
||||
|
||||
Dependency Injection:
|
||||
|
||||
FileStorageManager depends on UserManager through constructor injection.
|
||||
Made constants configurable through constructor parameters.
|
||||
|
||||
|
||||
Extracted Helper Methods:
|
||||
|
||||
Created private helper methods for validation logic.
|
||||
Extracted common operations like canModifyFile, isSharedWithUser, etc.
|
||||
|
||||
|
||||
Improved Code Structure:
|
||||
|
||||
Organized related functionality into classes.
|
||||
Added proper commenting and documentation.
|
||||
|
||||
|
||||
Preserved Backward Compatibility:
|
||||
|
||||
Maintained the original API through exported functions.
|
||||
Made it easy to migrate existing code to use the new object-oriented approach.
|
||||
|
||||
|
||||
Applied Open/Closed Principle:
|
||||
|
||||
The system is now extensible without modifying existing code.
|
||||
New behaviors can be added by extending or composing with existing classes.
|
||||
|
||||
|
||||
Applied Interface Segregation:
|
||||
|
||||
Split large interfaces into smaller, more specific ones.
|
||||
Created purpose-specific interfaces like FileQuery and FileMetadataUpdate.
|
||||
|
||||
|
||||
Improved Error Handling:
|
||||
|
||||
Consistent error reporting pattern.
|
||||
Clear validation in separate methods.
|
||||
*/
|
||||
406
manual-testing-sandbox/next-edit/next-edit-6-3.ts
Normal file
406
manual-testing-sandbox/next-edit/next-edit-6-3.ts
Normal file
|
|
@ -0,0 +1,406 @@
|
|||
// A chaotic file upload and management system
|
||||
// Difficulty: 3 - Moderate refactoring needed
|
||||
|
||||
// Types
|
||||
type FileData = {
|
||||
id: string;
|
||||
name: string;
|
||||
size: number;
|
||||
type: string;
|
||||
uploadDate: Date;
|
||||
uploadedBy: string;
|
||||
path: string;
|
||||
isPublic: boolean;
|
||||
tags?: string[];
|
||||
metadata?: Record<string, any>;
|
||||
};
|
||||
|
||||
type User = {
|
||||
id: string;
|
||||
name: string;
|
||||
email: string;
|
||||
role: "admin" | "user" | "guest";
|
||||
};
|
||||
|
||||
// Global storage
|
||||
const fileStorage: Record<string, FileData> = {};
|
||||
const users: Record<string, User> = {
|
||||
user1: {
|
||||
id: "user1",
|
||||
name: "Admin User",
|
||||
email: "admin@example.com",
|
||||
role: "admin",
|
||||
},
|
||||
user2: {
|
||||
id: "user2",
|
||||
name: "Regular User",
|
||||
email: "user@example.com",
|
||||
role: "user",
|
||||
},
|
||||
user3: {
|
||||
id: "user3",
|
||||
name: "Guest User",
|
||||
email: "guest@example.com",
|
||||
role: "guest",
|
||||
},
|
||||
};
|
||||
let currentUser: string | null = null;
|
||||
let storageUsed = 0;
|
||||
const MAX_STORAGE = 1024 * 1024 * 1024; // 1GB
|
||||
const MAX_FILE_SIZE = 100 * 1024 * 1024; // 100MB
|
||||
|
||||
// Login function
|
||||
function login(userId: string) {
|
||||
if (users[userId]) {
|
||||
currentUser = userId;
|
||||
console.log(`Logged in as ${users[userId].name}`);
|
||||
return true;
|
||||
} else {
|
||||
console.error("User not found");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Logout function
|
||||
function logout() {
|
||||
currentUser = null;
|
||||
console.log("Logged out");
|
||||
return true;
|
||||
}
|
||||
|
||||
// Upload file
|
||||
function uploadFile(
|
||||
fileName: string,
|
||||
fileSize: number,
|
||||
fileType: string,
|
||||
isPublic: boolean = false,
|
||||
tags: string[] = [],
|
||||
metadata: Record<string, any> = {},
|
||||
) {
|
||||
// Check if user is logged in
|
||||
if (!currentUser) {
|
||||
console.error("User not logged in");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check file size
|
||||
if (fileSize > MAX_FILE_SIZE) {
|
||||
console.error(
|
||||
`File too large. Maximum size is ${MAX_FILE_SIZE / (1024 * 1024)}MB`,
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check available storage
|
||||
if (storageUsed + fileSize > MAX_STORAGE) {
|
||||
console.error("Not enough storage space");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Generate ID
|
||||
const fileId = "file_" + Date.now() + "_" + Math.floor(Math.random() * 1000);
|
||||
|
||||
// Create file path
|
||||
const path = `/storage/${currentUser}/${fileId}_${fileName}`;
|
||||
|
||||
// Create file data
|
||||
const fileData: FileData = {
|
||||
id: fileId,
|
||||
name: fileName,
|
||||
size: fileSize,
|
||||
type: fileType,
|
||||
uploadDate: new Date(),
|
||||
uploadedBy: currentUser,
|
||||
path: path,
|
||||
isPublic: isPublic,
|
||||
tags: tags,
|
||||
metadata: metadata,
|
||||
};
|
||||
|
||||
// Save file data
|
||||
fileStorage[fileId] = fileData;
|
||||
|
||||
// Update storage used
|
||||
storageUsed += fileSize;
|
||||
|
||||
console.log(`File ${fileName} uploaded successfully`);
|
||||
return fileId;
|
||||
}
|
||||
|
||||
// Delete file
|
||||
function deleteFile(fileId: string) {
|
||||
// Check if user is logged in
|
||||
if (!currentUser) {
|
||||
console.error("User not logged in");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
if (!fileStorage[fileId]) {
|
||||
console.error("File not found");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if user has permission
|
||||
const file = fileStorage[fileId];
|
||||
const user = users[currentUser];
|
||||
if (file.uploadedBy !== currentUser && user.role !== "admin") {
|
||||
console.error("Permission denied");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update storage used
|
||||
storageUsed -= file.size;
|
||||
|
||||
// Remove file
|
||||
delete fileStorage[fileId];
|
||||
|
||||
console.log(`File ${file.name} deleted successfully`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Update file metadata
|
||||
function updateFileMetadata(
|
||||
fileId: string,
|
||||
updates: {
|
||||
name?: string;
|
||||
isPublic?: boolean;
|
||||
tags?: string[];
|
||||
metadata?: Record<string, any>;
|
||||
},
|
||||
) {
|
||||
// Check if user is logged in
|
||||
if (!currentUser) {
|
||||
console.error("User not logged in");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
if (!fileStorage[fileId]) {
|
||||
console.error("File not found");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if user has permission
|
||||
const file = fileStorage[fileId];
|
||||
const user = users[currentUser];
|
||||
if (file.uploadedBy !== currentUser && user.role !== "admin") {
|
||||
console.error("Permission denied");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update file data
|
||||
if (updates.name !== undefined) fileStorage[fileId].name = updates.name;
|
||||
if (updates.isPublic !== undefined)
|
||||
fileStorage[fileId].isPublic = updates.isPublic;
|
||||
if (updates.tags !== undefined) fileStorage[fileId].tags = updates.tags;
|
||||
if (updates.metadata !== undefined) {
|
||||
fileStorage[fileId].metadata = {
|
||||
...fileStorage[fileId].metadata,
|
||||
...updates.metadata,
|
||||
};
|
||||
}
|
||||
|
||||
console.log(`File ${file.name} updated successfully`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Get file data
|
||||
function getFileData(fileId: string) {
|
||||
// Check if file exists
|
||||
if (!fileStorage[fileId]) {
|
||||
console.error("File not found");
|
||||
return null;
|
||||
}
|
||||
|
||||
const file = fileStorage[fileId];
|
||||
|
||||
// Check if user has permission
|
||||
if (
|
||||
!file.isPublic &&
|
||||
currentUser !== file.uploadedBy &&
|
||||
users[currentUser]?.role !== "admin"
|
||||
) {
|
||||
console.error("Permission denied");
|
||||
return null;
|
||||
}
|
||||
|
||||
return file;
|
||||
}
|
||||
|
||||
// Search files
|
||||
function searchFiles(query: {
|
||||
name?: string;
|
||||
type?: string;
|
||||
tags?: string[];
|
||||
uploadedBy?: string;
|
||||
isPublic?: boolean;
|
||||
minSize?: number;
|
||||
maxSize?: number;
|
||||
uploadedAfter?: Date;
|
||||
uploadedBefore?: Date;
|
||||
}) {
|
||||
// Check if user is logged in
|
||||
if (!currentUser) {
|
||||
console.error("User not logged in");
|
||||
return [];
|
||||
}
|
||||
|
||||
const user = users[currentUser];
|
||||
const results: FileData[] = [];
|
||||
|
||||
// Filter files
|
||||
for (const fileId in fileStorage) {
|
||||
const file = fileStorage[fileId];
|
||||
|
||||
// Skip files user doesn't have access to
|
||||
if (
|
||||
!file.isPublic &&
|
||||
file.uploadedBy !== currentUser &&
|
||||
user.role !== "admin"
|
||||
) {
|
||||
continue;
|
||||
}
|
||||
|
||||
// Apply filters
|
||||
let match = true;
|
||||
|
||||
if (
|
||||
query.name &&
|
||||
!file.name.toLowerCase().includes(query.name.toLowerCase())
|
||||
) {
|
||||
match = false;
|
||||
}
|
||||
|
||||
if (query.type && file.type !== query.type) {
|
||||
match = false;
|
||||
}
|
||||
|
||||
if (query.uploadedBy && file.uploadedBy !== query.uploadedBy) {
|
||||
match = false;
|
||||
}
|
||||
|
||||
if (query.isPublic !== undefined && file.isPublic !== query.isPublic) {
|
||||
match = false;
|
||||
}
|
||||
|
||||
if (query.minSize !== undefined && file.size < query.minSize) {
|
||||
match = false;
|
||||
}
|
||||
|
||||
if (query.maxSize !== undefined && file.size > query.maxSize) {
|
||||
match = false;
|
||||
}
|
||||
|
||||
if (query.uploadedAfter && file.uploadDate < query.uploadedAfter) {
|
||||
match = false;
|
||||
}
|
||||
|
||||
if (query.uploadedBefore && file.uploadDate > query.uploadedBefore) {
|
||||
match = false;
|
||||
}
|
||||
|
||||
if (query.tags && query.tags.length > 0) {
|
||||
if (!file.tags) {
|
||||
match = false;
|
||||
} else {
|
||||
for (const tag of query.tags) {
|
||||
if (!file.tags.includes(tag)) {
|
||||
match = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
if (match) {
|
||||
results.push(file);
|
||||
}
|
||||
}
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
// Get storage stats
|
||||
function getStorageStats() {
|
||||
return {
|
||||
used: storageUsed,
|
||||
total: MAX_STORAGE,
|
||||
available: MAX_STORAGE - storageUsed,
|
||||
fileCount: Object.keys(fileStorage).length,
|
||||
};
|
||||
}
|
||||
|
||||
// Share file with user
|
||||
function shareFile(fileId: string, targetUserId: string) {
|
||||
// Check if user is logged in
|
||||
if (!currentUser) {
|
||||
console.error("User not logged in");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if file exists
|
||||
if (!fileStorage[fileId]) {
|
||||
console.error("File not found");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if target user exists
|
||||
if (!users[targetUserId]) {
|
||||
console.error("Target user not found");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Check if user has permission
|
||||
const file = fileStorage[fileId];
|
||||
if (file.uploadedBy !== currentUser && users[currentUser]?.role !== "admin") {
|
||||
console.error("Permission denied");
|
||||
return false;
|
||||
}
|
||||
|
||||
// Share file by adding metadata
|
||||
if (!file.metadata) {
|
||||
file.metadata = {};
|
||||
}
|
||||
|
||||
if (!file.metadata.sharedWith) {
|
||||
file.metadata.sharedWith = [];
|
||||
}
|
||||
|
||||
// Check if already shared
|
||||
if (!file.metadata.sharedWith.includes(targetUserId)) {
|
||||
file.metadata.sharedWith.push(targetUserId);
|
||||
}
|
||||
|
||||
console.log(`File ${file.name} shared with ${users[targetUserId].name}`);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Example usage
|
||||
login("user1");
|
||||
const fileId = uploadFile(
|
||||
"document.pdf",
|
||||
1024 * 1024,
|
||||
"application/pdf",
|
||||
false,
|
||||
["important", "document"],
|
||||
);
|
||||
updateFileMetadata(fileId, { isPublic: true });
|
||||
shareFile(fileId, "user2");
|
||||
console.log(getFileData(fileId));
|
||||
console.log(getStorageStats());
|
||||
logout();
|
||||
|
||||
export {
|
||||
deleteFile,
|
||||
fileStorage,
|
||||
getFileData,
|
||||
getStorageStats,
|
||||
login,
|
||||
logout,
|
||||
searchFiles,
|
||||
shareFile,
|
||||
updateFileMetadata,
|
||||
uploadFile,
|
||||
users,
|
||||
};
|
||||
489
manual-testing-sandbox/next-edit/next-edit-7-4-sol.ts
Normal file
489
manual-testing-sandbox/next-edit/next-edit-7-4-sol.ts
Normal file
|
|
@ -0,0 +1,489 @@
|
|||
// Refactored event processing system with proper separation of concerns
|
||||
// Solution for next-edit-7-4.ts
|
||||
|
||||
// Types
|
||||
export type EventType =
|
||||
| "click"
|
||||
| "hover"
|
||||
| "scroll"
|
||||
| "keypress"
|
||||
| "resize"
|
||||
| "load";
|
||||
export type EventData = Record<string, any>;
|
||||
export type EventCallback = (data: EventData) => void;
|
||||
export type ThemeType = "light" | "dark";
|
||||
export type PreferenceKey = "theme" | "fontSize" | "notifications";
|
||||
|
||||
// Event system
|
||||
export interface IEventEmitter {
|
||||
on(eventType: EventType, callback: EventCallback): void;
|
||||
emit(eventType: EventType, data: EventData): void;
|
||||
off(eventType: EventType, callback: EventCallback): void;
|
||||
}
|
||||
|
||||
export class EventEmitter implements IEventEmitter {
|
||||
private events: Map<EventType, Set<EventCallback>> = new Map();
|
||||
private processingQueue: Array<{ type: EventType; data: EventData }> = [];
|
||||
private isProcessing = false;
|
||||
|
||||
constructor() {
|
||||
// Initialize event collections
|
||||
this.events.set("click", new Set());
|
||||
this.events.set("hover", new Set());
|
||||
this.events.set("scroll", new Set());
|
||||
this.events.set("keypress", new Set());
|
||||
this.events.set("resize", new Set());
|
||||
this.events.set("load", new Set());
|
||||
}
|
||||
|
||||
public on(eventType: EventType, callback: EventCallback): void {
|
||||
const handlers = this.events.get(eventType) || new Set();
|
||||
handlers.add(callback);
|
||||
this.events.set(eventType, handlers);
|
||||
}
|
||||
|
||||
public off(eventType: EventType, callback: EventCallback): void {
|
||||
const handlers = this.events.get(eventType);
|
||||
if (handlers) {
|
||||
handlers.delete(callback);
|
||||
}
|
||||
}
|
||||
|
||||
public emit(eventType: EventType, data: EventData): void {
|
||||
if (this.isProcessing) {
|
||||
this.processingQueue.push({ type: eventType, data });
|
||||
return;
|
||||
}
|
||||
|
||||
this.isProcessing = true;
|
||||
|
||||
try {
|
||||
this.processEvent(eventType, data);
|
||||
|
||||
// Process queue
|
||||
while (this.processingQueue.length > 0) {
|
||||
const next = this.processingQueue.shift()!;
|
||||
this.processEvent(next.type, next.data);
|
||||
}
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
private processEvent(eventType: EventType, data: EventData): void {
|
||||
const handlers = this.events.get(eventType) || new Set();
|
||||
for (const handler of handlers) {
|
||||
handler(data);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// State management with proper encapsulation
|
||||
export class AppState {
|
||||
private _count = 0;
|
||||
private _lastEvent: {
|
||||
type: string;
|
||||
data: EventData;
|
||||
timestamp: number;
|
||||
} | null = null;
|
||||
private _eventHistory: string[] = [];
|
||||
|
||||
get count(): number {
|
||||
return this._count;
|
||||
}
|
||||
|
||||
set count(value: number) {
|
||||
this._count = value;
|
||||
}
|
||||
|
||||
get lastEvent(): { type: string; data: EventData; timestamp: number } | null {
|
||||
return this._lastEvent;
|
||||
}
|
||||
|
||||
get eventHistory(): ReadonlyArray<string> {
|
||||
return [...this._eventHistory];
|
||||
}
|
||||
|
||||
public recordEvent(type: string, data: EventData): void {
|
||||
this._lastEvent = { type, data, timestamp: Date.now() };
|
||||
this._eventHistory.push(`${type}:${JSON.stringify(data)}`);
|
||||
}
|
||||
|
||||
public incrementCount(): void {
|
||||
this._count++;
|
||||
}
|
||||
|
||||
public resetCount(): void {
|
||||
this._count = 0;
|
||||
}
|
||||
|
||||
public formatEventHistory(): string {
|
||||
return this._eventHistory
|
||||
.map((event, index) => `${index + 1}. ${event}`)
|
||||
.join("\n");
|
||||
}
|
||||
}
|
||||
|
||||
// User Authentication - separate concern
|
||||
export interface IAuthService {
|
||||
login(username: string, password: string): Promise<void>;
|
||||
logout(): void;
|
||||
isAuthenticated(): boolean;
|
||||
getUserData(): any;
|
||||
}
|
||||
|
||||
export class AuthService implements IAuthService {
|
||||
private isActive = false;
|
||||
private token = "";
|
||||
private userData: any = null;
|
||||
private username = "";
|
||||
|
||||
constructor(private eventEmitter: IEventEmitter) {}
|
||||
|
||||
public setUsername(name: string): void {
|
||||
this.username = name;
|
||||
}
|
||||
|
||||
public getUsername(): string {
|
||||
return this.username;
|
||||
}
|
||||
|
||||
public async login(username: string, password: string): Promise<void> {
|
||||
console.log(`Attempting login for ${username}...`);
|
||||
|
||||
return new Promise((resolve) => {
|
||||
// Simulate API call
|
||||
setTimeout(() => {
|
||||
this.isActive = true;
|
||||
this.token = `token-${Math.random().toString(36).substring(7)}`;
|
||||
this.userData = {
|
||||
name: username,
|
||||
role: "user",
|
||||
loginTime: new Date(),
|
||||
};
|
||||
|
||||
this.eventEmitter.emit("load", { user: username });
|
||||
resolve();
|
||||
}, 1000);
|
||||
});
|
||||
}
|
||||
|
||||
public logout(): void {
|
||||
this.isActive = false;
|
||||
this.token = "";
|
||||
this.userData = null;
|
||||
this.eventEmitter.emit("load", { user: null });
|
||||
}
|
||||
|
||||
public isAuthenticated(): boolean {
|
||||
return this.isActive;
|
||||
}
|
||||
|
||||
public getUserData(): any {
|
||||
return this.userData;
|
||||
}
|
||||
}
|
||||
|
||||
// Preferences management - separate concern
|
||||
export class PreferencesManager {
|
||||
private preferences = {
|
||||
theme: "light" as ThemeType,
|
||||
fontSize: 12,
|
||||
notifications: true,
|
||||
};
|
||||
|
||||
getPreference<K extends keyof typeof this.preferences>(
|
||||
key: K,
|
||||
): (typeof this.preferences)[K] {
|
||||
return this.preferences[key];
|
||||
}
|
||||
|
||||
updatePreference<K extends keyof typeof this.preferences>(
|
||||
key: K,
|
||||
value: (typeof this.preferences)[K],
|
||||
): void {
|
||||
this.preferences[key] = value;
|
||||
}
|
||||
}
|
||||
|
||||
// UI management - separate concern
|
||||
export class UIManager {
|
||||
constructor(
|
||||
private appState: AppState,
|
||||
private preferencesManager: PreferencesManager,
|
||||
private eventEmitter: IEventEmitter,
|
||||
) {
|
||||
// Set up default click handler
|
||||
this.eventEmitter.on("click", (data) => {
|
||||
console.log("Default click handler:", data);
|
||||
this.appState.incrementCount();
|
||||
this.appState.recordEvent("click", data);
|
||||
this.updateUI();
|
||||
});
|
||||
}
|
||||
|
||||
public updateUI(): void {
|
||||
const countElement = document.getElementById("count");
|
||||
if (countElement) {
|
||||
countElement.textContent = String(this.appState.count);
|
||||
}
|
||||
|
||||
// Apply theme
|
||||
document.body.className = this.preferencesManager.getPreference("theme");
|
||||
|
||||
// Update last event display
|
||||
const lastEventElement = document.getElementById("lastEvent");
|
||||
if (lastEventElement && this.appState.lastEvent) {
|
||||
lastEventElement.textContent = JSON.stringify(this.appState.lastEvent);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Analytics - separate concern
|
||||
export interface IAnalyticsService {
|
||||
trackEvent(category: string, action: string, label?: string): void;
|
||||
}
|
||||
|
||||
export class AnalyticsService implements IAnalyticsService {
|
||||
constructor(
|
||||
private appState: AppState,
|
||||
private authService: IAuthService,
|
||||
) {}
|
||||
|
||||
public trackEvent(category: string, action: string, label?: string): void {
|
||||
const eventData = { category, action, label, timestamp: Date.now() };
|
||||
console.log("Tracking event:", eventData);
|
||||
|
||||
this.appState.recordEvent("analytics", eventData);
|
||||
|
||||
if (this.authService.isAuthenticated()) {
|
||||
this.sendToAnalyticsService(eventData);
|
||||
}
|
||||
}
|
||||
|
||||
private sendToAnalyticsService(data: any): void {
|
||||
// Pretend API call
|
||||
console.log("Sending to analytics service:", data);
|
||||
}
|
||||
}
|
||||
|
||||
// Application class to orchestrate all components
|
||||
export class Application {
|
||||
private eventEmitter: IEventEmitter;
|
||||
private appState: AppState;
|
||||
private authService: IAuthService;
|
||||
private preferencesManager: PreferencesManager;
|
||||
private uiManager: UIManager;
|
||||
private analyticsService: IAnalyticsService;
|
||||
|
||||
constructor() {
|
||||
// Initialize all components with proper dependencies
|
||||
this.eventEmitter = new EventEmitter();
|
||||
this.appState = new AppState();
|
||||
this.authService = new AuthService(this.eventEmitter);
|
||||
this.preferencesManager = new PreferencesManager();
|
||||
this.uiManager = new UIManager(
|
||||
this.appState,
|
||||
this.preferencesManager,
|
||||
this.eventEmitter,
|
||||
);
|
||||
this.analyticsService = new AnalyticsService(
|
||||
this.appState,
|
||||
this.authService,
|
||||
);
|
||||
|
||||
this.setupEventListeners();
|
||||
}
|
||||
|
||||
private setupEventListeners(): void {
|
||||
// Setup DOM event listeners
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
this.eventEmitter.emit("load", { page: "home" });
|
||||
|
||||
document.addEventListener("click", (e) => {
|
||||
this.eventEmitter.emit("click", {
|
||||
target: e.target,
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
});
|
||||
|
||||
// Handle login button click
|
||||
if (e.target && (e.target as HTMLElement).id === "login-button") {
|
||||
this.authService.login(
|
||||
this.authService.getUsername(),
|
||||
"hardcoded-password",
|
||||
);
|
||||
}
|
||||
});
|
||||
|
||||
document.addEventListener("keypress", (e) => {
|
||||
this.eventEmitter.emit("keypress", { key: e.key, code: e.code });
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Public API for application
|
||||
public on(eventType: EventType, callback: EventCallback): void {
|
||||
this.eventEmitter.on(eventType, callback);
|
||||
}
|
||||
|
||||
public emit(eventType: EventType, data: EventData): void {
|
||||
this.eventEmitter.emit(eventType, data);
|
||||
}
|
||||
|
||||
public getCurrentCount(): number {
|
||||
return this.appState.count;
|
||||
}
|
||||
|
||||
public resetCount(): void {
|
||||
this.appState.resetCount();
|
||||
this.eventEmitter.emit("click", { action: "reset" });
|
||||
this.uiManager.updateUI();
|
||||
}
|
||||
|
||||
public setUsername(name: string): void {
|
||||
this.authService.setUsername(name);
|
||||
}
|
||||
|
||||
public updatePreference(key: PreferenceKey, value: any): void {
|
||||
this.preferencesManager.updatePreference(key, value);
|
||||
this.uiManager.updateUI();
|
||||
this.analyticsService.trackEvent(
|
||||
"preferences",
|
||||
"update",
|
||||
`${key}:${value}`,
|
||||
);
|
||||
}
|
||||
|
||||
public trackEvent(category: string, action: string, label?: string): void {
|
||||
this.analyticsService.trackEvent(category, action, label);
|
||||
}
|
||||
|
||||
public formatEventHistory(): string {
|
||||
return this.appState.formatEventHistory();
|
||||
}
|
||||
}
|
||||
|
||||
// Create and export singleton application instance
|
||||
export const app = new Application();
|
||||
|
||||
// Simplified API for backward compatibility
|
||||
export function getCurrentCount(): number {
|
||||
return app.getCurrentCount();
|
||||
}
|
||||
|
||||
export function resetCount(): void {
|
||||
app.resetCount();
|
||||
}
|
||||
|
||||
export function setUsername(name: string): void {
|
||||
app.setUsername(name);
|
||||
}
|
||||
|
||||
/*
|
||||
Code Smells in the Original Code
|
||||
|
||||
Violation of Single Responsibility Principle (SRP):
|
||||
|
||||
The EventManager class was a "God class" handling events, UI updates, authentication, analytics, and preferences
|
||||
Functions had multiple responsibilities mixed together
|
||||
|
||||
|
||||
Global State Abuse:
|
||||
|
||||
Direct manipulation of a global mutable state object
|
||||
No encapsulation or proper state management
|
||||
|
||||
|
||||
Tight Coupling:
|
||||
|
||||
Direct DOM manipulation in the event manager
|
||||
Hard dependencies between unrelated concerns (events, auth, UI)
|
||||
|
||||
|
||||
Poor Extensibility:
|
||||
|
||||
Singleton pattern limiting testability and flexibility
|
||||
Hardcoded event types and handlers
|
||||
No interface-based design
|
||||
|
||||
|
||||
Dependency Issues:
|
||||
|
||||
Direct instantiation of dependencies
|
||||
No dependency injection
|
||||
High-level modules depending on low-level details
|
||||
|
||||
|
||||
Security Concerns:
|
||||
|
||||
Hardcoded password in code
|
||||
No proper authentication flow
|
||||
|
||||
|
||||
Maintainability Problems:
|
||||
|
||||
Scattered responsibilities making the code hard to maintain
|
||||
Side effects hidden throughout the codebase
|
||||
|
||||
|
||||
Improvements Made in the Solution
|
||||
|
||||
Applied Single Responsibility Principle:
|
||||
|
||||
Split the monolithic EventManager into specialized classes (EventEmitter, AppState, AuthService, etc.)
|
||||
Each class now has a clear, focused responsibility
|
||||
|
||||
|
||||
Improved Encapsulation:
|
||||
|
||||
Replaced global state with proper encapsulated classes
|
||||
Added getters/setters to control state access
|
||||
Private fields to protect internal state
|
||||
|
||||
|
||||
Implemented Interface-based Design:
|
||||
|
||||
Created interfaces like IEventEmitter, IAuthService, and IAnalyticsService
|
||||
Enables future extension and easier testing
|
||||
|
||||
|
||||
Applied Dependency Inversion:
|
||||
|
||||
Components depend on abstractions rather than concrete implementations
|
||||
Dependencies are injected through constructors
|
||||
High-level modules no longer depend directly on low-level modules
|
||||
|
||||
|
||||
Better Organization:
|
||||
|
||||
Segregated interfaces to follow Interface Segregation Principle
|
||||
Clear separation between UI, state, authentication, and event handling
|
||||
|
||||
|
||||
Enhanced Extensibility:
|
||||
|
||||
Event system now uses Sets instead of Arrays for better performance and to avoid duplicate handlers
|
||||
Added ability to remove event listeners with the off method
|
||||
Created proper type definitions for better type safety
|
||||
|
||||
|
||||
Improved State Management:
|
||||
|
||||
Centralized state in the AppState class with proper access controls
|
||||
Immutable collection returns (using spreads and readonly)
|
||||
Clear state manipulation methods
|
||||
|
||||
|
||||
Better Event Processing:
|
||||
|
||||
Cleaner event queue handling
|
||||
More efficient event processing
|
||||
|
||||
|
||||
Application Orchestration:
|
||||
|
||||
Created an Application class to coordinate all components
|
||||
Maintains backward compatibility with the original API
|
||||
Provides a cleaner facade for all operations
|
||||
*/
|
||||
211
manual-testing-sandbox/next-edit/next-edit-7-4.ts
Normal file
211
manual-testing-sandbox/next-edit/next-edit-7-4.ts
Normal file
|
|
@ -0,0 +1,211 @@
|
|||
// A messy and tightly coupled event processing system with poor separation of concerns
|
||||
// Difficulty: 4
|
||||
|
||||
type EventType = "click" | "hover" | "scroll" | "keypress" | "resize" | "load";
|
||||
type EventCallback = (data: any) => void;
|
||||
|
||||
// Global state - everything is mixed together
|
||||
const globalState = {
|
||||
count: 0,
|
||||
lastEvent: null as any,
|
||||
isActive: false,
|
||||
username: "",
|
||||
token: "",
|
||||
preferences: { theme: "light", fontSize: 12, notifications: true },
|
||||
eventHistory: [] as string[],
|
||||
userData: null as any,
|
||||
};
|
||||
|
||||
// God class that handles everything
|
||||
class EventManager {
|
||||
private events: Map<EventType, EventCallback[]> = new Map();
|
||||
private static instance: EventManager;
|
||||
private isProcessing = false;
|
||||
private processingQueue: Array<{ type: EventType; data: any }> = [];
|
||||
|
||||
private constructor() {
|
||||
// Initialize default handlers
|
||||
this.events.set("click", []);
|
||||
this.events.set("hover", []);
|
||||
this.events.set("scroll", []);
|
||||
this.events.set("keypress", []);
|
||||
this.events.set("resize", []);
|
||||
this.events.set("load", []);
|
||||
|
||||
// Add default behavior
|
||||
this.on("click", (data) => {
|
||||
console.log("Default click handler:", data);
|
||||
globalState.count++;
|
||||
globalState.lastEvent = { type: "click", data, timestamp: Date.now() };
|
||||
globalState.eventHistory.push(`click:${JSON.stringify(data)}`);
|
||||
|
||||
// Side effects directly in handler
|
||||
this.updateUI();
|
||||
|
||||
// Mixes concerns by also handling auth
|
||||
if (data.target && data.target.id === "login-button") {
|
||||
this.login(globalState.username, "hardcoded-password");
|
||||
}
|
||||
});
|
||||
}
|
||||
|
||||
// Singleton pattern
|
||||
public static getInstance(): EventManager {
|
||||
if (!EventManager.instance) {
|
||||
EventManager.instance = new EventManager();
|
||||
}
|
||||
return EventManager.instance;
|
||||
}
|
||||
|
||||
public on(eventType: EventType, callback: EventCallback): void {
|
||||
const handlers = this.events.get(eventType) || [];
|
||||
handlers.push(callback);
|
||||
this.events.set(eventType, handlers);
|
||||
}
|
||||
|
||||
public emit(eventType: EventType, data: any): void {
|
||||
globalState.lastEvent = { type: eventType, data, timestamp: Date.now() };
|
||||
|
||||
if (this.isProcessing) {
|
||||
this.processingQueue.push({ type: eventType, data });
|
||||
return;
|
||||
}
|
||||
|
||||
this.isProcessing = true;
|
||||
|
||||
try {
|
||||
const handlers = this.events.get(eventType) || [];
|
||||
for (const handler of handlers) {
|
||||
handler(data);
|
||||
|
||||
// Random state modifications scattered throughout code
|
||||
globalState.eventHistory.push(`${eventType}:${JSON.stringify(data)}`);
|
||||
}
|
||||
|
||||
// UI Update with every event
|
||||
this.updateUI();
|
||||
|
||||
// Process queue
|
||||
while (this.processingQueue.length > 0) {
|
||||
const next = this.processingQueue.shift()!;
|
||||
const queueHandlers = this.events.get(next.type) || [];
|
||||
for (const handler of queueHandlers) {
|
||||
handler(next.data);
|
||||
}
|
||||
}
|
||||
} finally {
|
||||
this.isProcessing = false;
|
||||
}
|
||||
}
|
||||
|
||||
// Mixed UI concerns with event handling
|
||||
private updateUI(): void {
|
||||
// Directly manipulates DOM
|
||||
const countElement = document.getElementById("count");
|
||||
if (countElement) {
|
||||
countElement.textContent = String(globalState.count);
|
||||
}
|
||||
|
||||
// Apply theme
|
||||
document.body.className = globalState.preferences.theme;
|
||||
|
||||
// Update last event display
|
||||
const lastEventElement = document.getElementById("lastEvent");
|
||||
if (lastEventElement && globalState.lastEvent) {
|
||||
lastEventElement.textContent = JSON.stringify(globalState.lastEvent);
|
||||
}
|
||||
}
|
||||
|
||||
// Authentication logic mixed with event handling
|
||||
private login(username: string, password: string): void {
|
||||
console.log(`Attempting login for ${username}...`);
|
||||
|
||||
// Simulate API call
|
||||
setTimeout(() => {
|
||||
globalState.isActive = true;
|
||||
globalState.token = `token-${Math.random().toString(36).substring(7)}`;
|
||||
globalState.userData = {
|
||||
name: username,
|
||||
role: "user",
|
||||
loginTime: new Date(),
|
||||
};
|
||||
|
||||
// Update UI after login
|
||||
this.updateUI();
|
||||
|
||||
// Emit another event
|
||||
this.emit("load", { user: username });
|
||||
}, 1000);
|
||||
}
|
||||
|
||||
// Analytics mixed in
|
||||
public trackEvent(category: string, action: string, label?: string): void {
|
||||
const eventData = { category, action, label, timestamp: Date.now() };
|
||||
console.log("Tracking event:", eventData);
|
||||
|
||||
// Update global state
|
||||
globalState.eventHistory.push(`analytics:${JSON.stringify(eventData)}`);
|
||||
|
||||
// Send to analytics service
|
||||
if (globalState.isActive) {
|
||||
this.sendToAnalyticsService(eventData);
|
||||
}
|
||||
}
|
||||
|
||||
private sendToAnalyticsService(data: any): void {
|
||||
// Pretend API call
|
||||
console.log("Sending to analytics service:", data);
|
||||
}
|
||||
|
||||
// Utility functions mixed in
|
||||
public formatEventHistory(): string {
|
||||
return globalState.eventHistory
|
||||
.map((event, index) => `${index + 1}. ${event}`)
|
||||
.join("\n");
|
||||
}
|
||||
|
||||
// Settings management mixed in
|
||||
public updatePreference(
|
||||
key: "theme" | "fontSize" | "notifications",
|
||||
value: any,
|
||||
): void {
|
||||
globalState.preferences[key] = value;
|
||||
this.updateUI();
|
||||
this.trackEvent("preferences", "update", `${key}:${value}`);
|
||||
}
|
||||
}
|
||||
|
||||
// Export singleton
|
||||
export const eventManager = EventManager.getInstance();
|
||||
|
||||
// Helper functions that directly use global state
|
||||
export function getCurrentCount(): number {
|
||||
return globalState.count;
|
||||
}
|
||||
|
||||
export function resetCount(): void {
|
||||
globalState.count = 0;
|
||||
eventManager.emit("click", { action: "reset" });
|
||||
}
|
||||
|
||||
export function setUsername(name: string): void {
|
||||
globalState.username = name;
|
||||
}
|
||||
|
||||
// Example usage
|
||||
document.addEventListener("DOMContentLoaded", () => {
|
||||
eventManager.emit("load", { page: "home" });
|
||||
|
||||
// Add event listeners
|
||||
document.addEventListener("click", (e) => {
|
||||
eventManager.emit("click", {
|
||||
target: e.target,
|
||||
x: e.clientX,
|
||||
y: e.clientY,
|
||||
});
|
||||
});
|
||||
|
||||
document.addEventListener("keypress", (e) => {
|
||||
eventManager.emit("keypress", { key: e.key, code: e.code });
|
||||
});
|
||||
});
|
||||
697
manual-testing-sandbox/next-edit/next-edit-8-4-sol.ts
Normal file
697
manual-testing-sandbox/next-edit/next-edit-8-4-sol.ts
Normal file
|
|
@ -0,0 +1,697 @@
|
|||
// User management system refactored with SOLID principles
|
||||
// Original difficulty: 4/5
|
||||
|
||||
// Types
|
||||
type UserStatus = "active" | "inactive" | "suspended" | "deleted";
|
||||
type LogLevel = "debug" | "info" | "warn" | "error";
|
||||
|
||||
interface User {
|
||||
id?: number;
|
||||
firstName: string;
|
||||
lastName: string;
|
||||
email: string;
|
||||
status?: UserStatus;
|
||||
}
|
||||
|
||||
interface Logger {
|
||||
log(message: string, level?: LogLevel): void;
|
||||
}
|
||||
|
||||
interface Database {
|
||||
query(sql: string, params?: any[]): Promise<any>;
|
||||
close(): void;
|
||||
}
|
||||
|
||||
interface StorageService {
|
||||
getItem(key: string): string | null;
|
||||
setItem(key: string, value: string): void;
|
||||
}
|
||||
|
||||
// Configuration interfaces
|
||||
interface SystemConfig {
|
||||
debugMode: boolean;
|
||||
apiToken: string;
|
||||
}
|
||||
|
||||
// Logger implementation - Single Responsibility
|
||||
class ConsoleLogger implements Logger {
|
||||
constructor(private notificationService?: NotificationService) {}
|
||||
|
||||
log(message: string, level: LogLevel = "info"): void {
|
||||
const timestamp = new Date().toISOString();
|
||||
console.log(`[${level.toUpperCase()}] ${timestamp}: ${message}`);
|
||||
|
||||
// If error, send notification
|
||||
if (level === "error" && this.notificationService) {
|
||||
this.notificationService.sendNotification(message);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Storage service implementation
|
||||
class LocalStorageService implements StorageService {
|
||||
getItem(key: string): string | null {
|
||||
return localStorage.getItem(key);
|
||||
}
|
||||
|
||||
setItem(key: string, value: string): void {
|
||||
localStorage.setItem(key, value);
|
||||
}
|
||||
}
|
||||
|
||||
// Logger decorator to add persistent storage
|
||||
class PersistentLogger implements Logger {
|
||||
constructor(
|
||||
private baseLogger: Logger,
|
||||
private storageService: StorageService,
|
||||
) {}
|
||||
|
||||
log(message: string, level: LogLevel = "info"): void {
|
||||
// First use the base logger
|
||||
this.baseLogger.log(message, level);
|
||||
|
||||
// Then persist the log
|
||||
const timestamp = new Date().toISOString();
|
||||
try {
|
||||
const logs = JSON.parse(
|
||||
this.storageService.getItem("system_logs") || "[]",
|
||||
);
|
||||
logs.push({ timestamp, level, message });
|
||||
this.storageService.setItem("system_logs", JSON.stringify(logs));
|
||||
} catch (e) {
|
||||
this.baseLogger.log("Failed to persist log", "error");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Notification service - Single Responsibility
|
||||
class NotificationService {
|
||||
sendNotification(message: string): void {
|
||||
console.log(`Sending notification: ${message}`);
|
||||
// Simulate email sending
|
||||
setTimeout(() => {
|
||||
console.log("Notification sent!");
|
||||
}, 1000);
|
||||
}
|
||||
}
|
||||
|
||||
// Database service - Single Responsibility
|
||||
class DatabaseService implements Database {
|
||||
private logger: Logger;
|
||||
|
||||
constructor(logger: Logger) {
|
||||
this.logger = logger;
|
||||
this.logger.log("Database service initialized", "debug");
|
||||
}
|
||||
|
||||
query(sql: string, params: any[] = []): Promise<any> {
|
||||
this.logger.log(`Executing query: ${sql}`, "debug");
|
||||
// Simulate database query
|
||||
return Promise.resolve({ rows: [], success: true });
|
||||
}
|
||||
|
||||
close(): void {
|
||||
this.logger.log("Closing database connection", "debug");
|
||||
}
|
||||
}
|
||||
|
||||
// Config service - Single Responsibility
|
||||
class ConfigService {
|
||||
private config: SystemConfig;
|
||||
private storageService: StorageService;
|
||||
private logger: Logger;
|
||||
|
||||
constructor(storageService: StorageService, logger: Logger) {
|
||||
this.storageService = storageService;
|
||||
this.logger = logger;
|
||||
this.config = this.loadConfig();
|
||||
}
|
||||
|
||||
private loadConfig(): SystemConfig {
|
||||
try {
|
||||
return JSON.parse(
|
||||
this.storageService.getItem("user_system_config") || "{}",
|
||||
) as SystemConfig;
|
||||
} catch (e) {
|
||||
this.logger.log("Failed to load configuration", "error");
|
||||
return { debugMode: false, apiToken: "" };
|
||||
}
|
||||
}
|
||||
|
||||
getConfig(): SystemConfig {
|
||||
return { ...this.config }; // Return a copy to prevent direct modification
|
||||
}
|
||||
}
|
||||
|
||||
// Authentication service - Single Responsibility
|
||||
class AuthService {
|
||||
private db: Database;
|
||||
private logger: Logger;
|
||||
private storageService: StorageService;
|
||||
private currentUserId: number | null = null;
|
||||
private loggedInUsers: User[] = [];
|
||||
|
||||
constructor(db: Database, logger: Logger, storageService: StorageService) {
|
||||
this.db = db;
|
||||
this.logger = logger;
|
||||
this.storageService = storageService;
|
||||
}
|
||||
|
||||
async login(email: string, password: string): Promise<boolean> {
|
||||
try {
|
||||
const result = await this.db.query(
|
||||
"SELECT * FROM users WHERE email = ? AND password_hash = ?",
|
||||
[email, this.hashPassword(password)],
|
||||
);
|
||||
|
||||
if (result.rows.length === 0) {
|
||||
this.logger.log(`Failed login attempt: ${email}`, "warn");
|
||||
return false;
|
||||
}
|
||||
|
||||
const user = result.rows[0];
|
||||
if (user.status !== "active") {
|
||||
this.logger.log(
|
||||
`Login attempt from inactive account: ${email}`,
|
||||
"warn",
|
||||
);
|
||||
return false;
|
||||
}
|
||||
|
||||
// Update state
|
||||
this.currentUserId = user.id;
|
||||
this.loggedInUsers.push(user);
|
||||
this.storageService.setItem("current_user", JSON.stringify(user));
|
||||
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.log(`Login error: ${err.message}`, "error");
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
this.currentUserId = null;
|
||||
this.storageService.setItem("current_user", "");
|
||||
}
|
||||
|
||||
getCurrentUserId(): number | null {
|
||||
return this.currentUserId;
|
||||
}
|
||||
|
||||
private hashPassword(password: string): string {
|
||||
// Not a real hash, just base64 encoding - in a real app, use a proper hashing library
|
||||
return btoa(password);
|
||||
}
|
||||
}
|
||||
|
||||
// User repository - Data access layer
|
||||
class UserRepository {
|
||||
private db: Database;
|
||||
private logger: Logger;
|
||||
|
||||
constructor(db: Database, logger: Logger) {
|
||||
this.db = db;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
async getAllActiveUsers(): Promise<User[]> {
|
||||
try {
|
||||
const result = await this.db.query(
|
||||
'SELECT * FROM users WHERE status != "deleted"',
|
||||
);
|
||||
return result.rows;
|
||||
} catch (err: any) {
|
||||
this.logger.log(`Failed to fetch users: ${err.message}`, "error");
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async createUser(userData: User): Promise<boolean> {
|
||||
try {
|
||||
await this.db.query(
|
||||
"INSERT INTO users (firstName, lastName, email, status) VALUES (?, ?, ?, ?)",
|
||||
[userData.firstName, userData.lastName, userData.email, "active"],
|
||||
);
|
||||
this.logger.log(`User created: ${userData.email}`, "info");
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.log(`Failed to create user: ${err.message}`, "error");
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async updateUser(userId: number, userData: User): Promise<boolean> {
|
||||
try {
|
||||
await this.db.query(
|
||||
"UPDATE users SET firstName = ?, lastName = ?, email = ? WHERE id = ?",
|
||||
[userData.firstName, userData.lastName, userData.email, userId],
|
||||
);
|
||||
this.logger.log(`User updated: ${userId}`, "info");
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.log(`Failed to update user: ${err.message}`, "error");
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
|
||||
async updateUserStatus(userId: number, status: UserStatus): Promise<boolean> {
|
||||
try {
|
||||
await this.db.query("UPDATE users SET status = ? WHERE id = ?", [
|
||||
status,
|
||||
userId,
|
||||
]);
|
||||
this.logger.log(`User status updated to ${status}: ${userId}`, "info");
|
||||
return true;
|
||||
} catch (err: any) {
|
||||
this.logger.log(`Failed to update user status: ${err.message}`, "error");
|
||||
throw err;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// UI rendering service - Single Responsibility
|
||||
class UserUIService {
|
||||
private userRepository: UserRepository;
|
||||
private logger: Logger;
|
||||
|
||||
constructor(userRepository: UserRepository, logger: Logger) {
|
||||
this.userRepository = userRepository;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
async renderUserList(containerId: string): Promise<void> {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) {
|
||||
this.logger.log(`Container ${containerId} not found`, "error");
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear container
|
||||
container.innerHTML = "";
|
||||
|
||||
try {
|
||||
// Get users from repository
|
||||
const users = await this.userRepository.getAllActiveUsers();
|
||||
|
||||
// Generate HTML
|
||||
let html = '<ul class="user-list">';
|
||||
users.forEach((user) => {
|
||||
// User status determines CSS class
|
||||
const statusClass = this.getStatusClass(user.status || "active");
|
||||
|
||||
html += `
|
||||
<li class="user-item ${statusClass}" data-id="${user.id}">
|
||||
<div class="user-name">${user.firstName} ${user.lastName}</div>
|
||||
<div class="user-email">${user.email}</div>
|
||||
<div class="user-actions">
|
||||
<button onclick="userController.editUser(${user.id})">Edit</button>
|
||||
<button onclick="userController.deleteUser(${user.id})">Delete</button>
|
||||
${
|
||||
user.status === "active"
|
||||
? `<button onclick="userController.suspendUser(${user.id})">Suspend</button>`
|
||||
: `<button onclick="userController.activateUser(${user.id})">Activate</button>`
|
||||
}
|
||||
</div>
|
||||
</li>
|
||||
`;
|
||||
});
|
||||
html += "</ul>";
|
||||
|
||||
container.innerHTML = html;
|
||||
} catch (err: any) {
|
||||
this.logger.log(`Failed to render users: ${err.message}`, "error");
|
||||
container.innerHTML =
|
||||
"<p>Failed to load users. Please try again later.</p>";
|
||||
}
|
||||
}
|
||||
|
||||
private getStatusClass(status: UserStatus): string {
|
||||
switch (status) {
|
||||
case "active":
|
||||
return "user-active";
|
||||
case "inactive":
|
||||
return "user-inactive";
|
||||
case "suspended":
|
||||
return "user-suspended";
|
||||
default:
|
||||
return "";
|
||||
}
|
||||
}
|
||||
|
||||
populateEditForm(form: HTMLFormElement, user: User): void {
|
||||
if (!form) return;
|
||||
|
||||
(form.elements.namedItem("firstName") as HTMLInputElement).value =
|
||||
user.firstName;
|
||||
(form.elements.namedItem("lastName") as HTMLInputElement).value =
|
||||
user.lastName;
|
||||
(form.elements.namedItem("email") as HTMLInputElement).value = user.email;
|
||||
(form.elements.namedItem("userId") as HTMLInputElement).value = String(
|
||||
user.id,
|
||||
);
|
||||
|
||||
// Scroll to form
|
||||
form.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
|
||||
resetForm(formId: string): void {
|
||||
const form = document.getElementById(formId) as HTMLFormElement;
|
||||
if (form) {
|
||||
form.reset();
|
||||
(form.elements.namedItem("userId") as HTMLInputElement).value = "";
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// User Controller - Handles UI interactions and coordinates services
|
||||
class UserController {
|
||||
private userRepository: UserRepository;
|
||||
private userUIService: UserUIService;
|
||||
private logger: Logger;
|
||||
private lastOperation: string = "";
|
||||
|
||||
constructor(
|
||||
userRepository: UserRepository,
|
||||
userUIService: UserUIService,
|
||||
logger: Logger,
|
||||
) {
|
||||
this.userRepository = userRepository;
|
||||
this.userUIService = userUIService;
|
||||
this.logger = logger;
|
||||
}
|
||||
|
||||
async createUser(userData: User): Promise<void> {
|
||||
try {
|
||||
await this.userRepository.createUser(userData);
|
||||
this.lastOperation = "create";
|
||||
await this.userUIService.renderUserList("user-container");
|
||||
this.userUIService.resetForm("user-form");
|
||||
alert("User created successfully!");
|
||||
} catch (err: any) {
|
||||
alert(`Failed to create user: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async updateUser(userId: number, userData: User): Promise<void> {
|
||||
try {
|
||||
await this.userRepository.updateUser(userId, userData);
|
||||
this.lastOperation = "update";
|
||||
await this.userUIService.renderUserList("user-container");
|
||||
this.userUIService.resetForm("user-form");
|
||||
alert("User updated successfully!");
|
||||
} catch (err: any) {
|
||||
alert(`Failed to update user: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async editUser(userId: number): Promise<void> {
|
||||
try {
|
||||
const users = await this.userRepository.getAllActiveUsers();
|
||||
const user = users.find((u) => u.id === userId);
|
||||
|
||||
if (!user) {
|
||||
this.logger.log(`User not found: ${userId}`, "error");
|
||||
return;
|
||||
}
|
||||
|
||||
const form = document.getElementById("user-form") as HTMLFormElement;
|
||||
this.userUIService.populateEditForm(form, user);
|
||||
this.lastOperation = "edit";
|
||||
} catch (err: any) {
|
||||
this.logger.log(`Failed to edit user: ${err.message}`, "error");
|
||||
}
|
||||
}
|
||||
|
||||
async suspendUser(userId: number): Promise<void> {
|
||||
if (!confirm("Are you sure you want to suspend this user?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.userRepository.updateUserStatus(userId, "suspended");
|
||||
this.lastOperation = "suspend";
|
||||
await this.userUIService.renderUserList("user-container");
|
||||
alert("User suspended successfully!");
|
||||
} catch (err: any) {
|
||||
alert(`Failed to suspend user: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async activateUser(userId: number): Promise<void> {
|
||||
try {
|
||||
await this.userRepository.updateUserStatus(userId, "active");
|
||||
this.lastOperation = "activate";
|
||||
await this.userUIService.renderUserList("user-container");
|
||||
alert("User activated successfully!");
|
||||
} catch (err: any) {
|
||||
alert(`Failed to activate user: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
async deleteUser(userId: number): Promise<void> {
|
||||
if (!confirm("Are you sure you want to delete this user?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
try {
|
||||
await this.userRepository.updateUserStatus(userId, "deleted");
|
||||
this.lastOperation = "delete";
|
||||
await this.userUIService.renderUserList("user-container");
|
||||
alert("User deleted successfully!");
|
||||
} catch (err: any) {
|
||||
alert(`Failed to delete user: ${err.message}`);
|
||||
}
|
||||
}
|
||||
|
||||
getLastOperation(): string {
|
||||
return this.lastOperation;
|
||||
}
|
||||
}
|
||||
|
||||
// Application class - Manages services and their lifecycle
|
||||
class UserManagementApp {
|
||||
private logger: Logger;
|
||||
private db: Database;
|
||||
private userRepository: UserRepository;
|
||||
private userUIService: UserUIService;
|
||||
private userController: UserController;
|
||||
private authService: AuthService;
|
||||
private configService: ConfigService;
|
||||
private storageService: StorageService;
|
||||
|
||||
constructor() {
|
||||
// Initialize services
|
||||
this.storageService = new LocalStorageService();
|
||||
const notificationService = new NotificationService();
|
||||
const baseLogger = new ConsoleLogger(notificationService);
|
||||
this.logger = new PersistentLogger(baseLogger, this.storageService);
|
||||
this.configService = new ConfigService(this.storageService, this.logger);
|
||||
|
||||
// Initialize database
|
||||
this.db = new DatabaseService(this.logger);
|
||||
|
||||
// Initialize user repository
|
||||
this.userRepository = new UserRepository(this.db, this.logger);
|
||||
|
||||
// Initialize UI service
|
||||
this.userUIService = new UserUIService(this.userRepository, this.logger);
|
||||
|
||||
// Initialize controller
|
||||
this.userController = new UserController(
|
||||
this.userRepository,
|
||||
this.userUIService,
|
||||
this.logger,
|
||||
);
|
||||
|
||||
// Initialize auth service
|
||||
this.authService = new AuthService(
|
||||
this.db,
|
||||
this.logger,
|
||||
this.storageService,
|
||||
);
|
||||
|
||||
// Expose controller to global scope
|
||||
(window as any).userController = this.userController;
|
||||
|
||||
this.setupEventListeners();
|
||||
this.setupErrorHandlers();
|
||||
}
|
||||
|
||||
private setupEventListeners(): void {
|
||||
window.addEventListener("load", () => {
|
||||
const userForm = document.getElementById("user-form");
|
||||
if (userForm) {
|
||||
userForm.addEventListener(
|
||||
"submit",
|
||||
this.handleUserFormSubmit.bind(this),
|
||||
);
|
||||
}
|
||||
|
||||
// Initialize user list
|
||||
this.userUIService.renderUserList("user-container");
|
||||
});
|
||||
}
|
||||
|
||||
private setupErrorHandlers(): void {
|
||||
window.onerror = (msg, url, line) => {
|
||||
this.logger.log(`Global error: ${msg} at ${url}:${line}`, "error");
|
||||
return false;
|
||||
};
|
||||
}
|
||||
|
||||
private handleUserFormSubmit(event: Event): void {
|
||||
event.preventDefault();
|
||||
const form = event.target as HTMLFormElement;
|
||||
|
||||
const userData: User = {
|
||||
firstName: (form.elements.namedItem("firstName") as HTMLInputElement)
|
||||
.value,
|
||||
lastName: (form.elements.namedItem("lastName") as HTMLInputElement).value,
|
||||
email: (form.elements.namedItem("email") as HTMLInputElement).value,
|
||||
};
|
||||
|
||||
const userId = (form.elements.namedItem("userId") as HTMLInputElement)
|
||||
.value;
|
||||
|
||||
if (userId) {
|
||||
this.userController.updateUser(parseInt(userId), userData);
|
||||
} else {
|
||||
this.userController.createUser(userData);
|
||||
}
|
||||
}
|
||||
|
||||
async login(email: string, password: string): Promise<boolean> {
|
||||
const success = await this.authService.login(email, password);
|
||||
if (success) {
|
||||
// Redirect to dashboard
|
||||
window.location.href = "/dashboard.html";
|
||||
} else {
|
||||
alert("Invalid email or password");
|
||||
}
|
||||
return success;
|
||||
}
|
||||
|
||||
cleanup(): void {
|
||||
this.logger.log("Cleaning up resources", "debug");
|
||||
this.db.close();
|
||||
}
|
||||
}
|
||||
|
||||
// Initialize the application
|
||||
const app = new UserManagementApp();
|
||||
|
||||
/*
|
||||
Code Smells in the Original Code
|
||||
|
||||
Violation of Single Responsibility Principle:
|
||||
|
||||
UserManager was a "God class" handling database connection, UI rendering, user CRUD operations, authentication, and logging
|
||||
Logger mixed logging with email notifications
|
||||
User operations contained both business logic and UI manipulation
|
||||
|
||||
Violation of Open/Closed Principle:
|
||||
|
||||
Hardcoded dependencies that couldn't be extended without modifying code
|
||||
Direct UI manipulations embedded in business logic
|
||||
|
||||
High Coupling:
|
||||
|
||||
Direct references to the DOM throughout the codebase
|
||||
Global state used across different operations
|
||||
Direct database access from UI-related methods
|
||||
|
||||
Code Duplication:
|
||||
|
||||
Similar code repeated in suspendUser, activateUser, and deleteUser methods
|
||||
Repetitive UI update logic
|
||||
|
||||
Poor Security Practices:
|
||||
|
||||
API tokens exposed in console logs
|
||||
Weak password handling (just base64 encoding)
|
||||
Direct SQL queries vulnerable to injection
|
||||
|
||||
|
||||
Global Variables and Side Effects:
|
||||
|
||||
Multiple global variables (currentUserID, loggedInUsers, etc.)
|
||||
Global DOM event handlers
|
||||
|
||||
|
||||
Improvements Made
|
||||
|
||||
Applied Single Responsibility Principle:
|
||||
|
||||
Created specialized classes for each concern:
|
||||
|
||||
Logger and PersistentLogger for logging
|
||||
NotificationService for alerts/notifications
|
||||
DatabaseService for database operations
|
||||
UserRepository for user data access
|
||||
UserUIService for rendering UI
|
||||
UserController for handling user actions
|
||||
AuthService for authentication
|
||||
ConfigService for configuration management
|
||||
|
||||
|
||||
Applied Open/Closed Principle:
|
||||
|
||||
Used interfaces (Logger, Database, StorageService) to define contracts
|
||||
Implemented dependency injection to allow for extensions without modifications
|
||||
Created the decorator pattern for logging (base logger + persistent storage)
|
||||
|
||||
|
||||
Applied Interface Segregation Principle:
|
||||
|
||||
Created focused interfaces (e.g., Logger only handles logging)
|
||||
Split large interfaces into smaller, more specific ones
|
||||
|
||||
|
||||
Applied Dependency Inversion Principle:
|
||||
|
||||
High-level modules depend on abstractions, not concrete implementations
|
||||
Dependencies are injected through constructors
|
||||
Centralized service initialization in the UserManagementApp class
|
||||
|
||||
|
||||
Applied Liskov Substitution Principle:
|
||||
|
||||
Classes implementing interfaces fully satisfy their contracts
|
||||
Derived classes (like PersistentLogger) maintain the behavior expected from the base interface
|
||||
|
||||
|
||||
Reduced Duplication:
|
||||
|
||||
Consolidated common user operations in the repository
|
||||
Created reusable UI methods
|
||||
Extracted common logic into shared methods
|
||||
|
||||
|
||||
Improved Security:
|
||||
|
||||
Removed sensitive information from console logs
|
||||
Added proper encapsulation of sensitive data
|
||||
Note: The password hashing is still weak (commented as such) but is separated for easy replacement
|
||||
|
||||
|
||||
Better State Management:
|
||||
|
||||
Eliminated global state
|
||||
Encapsulated state within appropriate classes
|
||||
Provided proper methods for state access
|
||||
|
||||
|
||||
Improved Error Handling:
|
||||
|
||||
Consistent error handling approach
|
||||
Proper propagation of errors
|
||||
Clear error messages
|
||||
|
||||
|
||||
Proper Separation of Concerns:
|
||||
|
||||
UI logic separated from business logic
|
||||
Data access separated from business rules
|
||||
Authentication separated from user management
|
||||
*/
|
||||
409
manual-testing-sandbox/next-edit/next-edit-8-4.ts
Normal file
409
manual-testing-sandbox/next-edit/next-edit-8-4.ts
Normal file
|
|
@ -0,0 +1,409 @@
|
|||
// User management system with mixed concerns and entangled logic
|
||||
// Difficulty: 4/5
|
||||
|
||||
type UserStatus = "active" | "inactive" | "suspended" | "deleted";
|
||||
type LogLevel = "debug" | "info" | "warn" | "error";
|
||||
|
||||
// Global variables
|
||||
let currentUserID: number | null = null;
|
||||
let loggedInUsers: any[] = [];
|
||||
let systemStatus = "online";
|
||||
let DEBUG_MODE = true;
|
||||
|
||||
// Main user class that handles everything
|
||||
class UserManager {
|
||||
private users: any[] = [];
|
||||
private db: any = null;
|
||||
private logger: any = null;
|
||||
private apiToken: string = "secret-token-1234";
|
||||
public lastOperation: string = "";
|
||||
|
||||
constructor() {
|
||||
this.initializeSystem();
|
||||
// Connect to database directly in constructor
|
||||
this.connectToDatabase();
|
||||
console.log("UserManager initialized!");
|
||||
}
|
||||
|
||||
// Mixed responsibility - initialization, logging, and notification
|
||||
private initializeSystem() {
|
||||
// Set up logging
|
||||
this.logger = {
|
||||
log: function (message: string, level: LogLevel = "info") {
|
||||
const timestamp = new Date().toISOString();
|
||||
console.log(`[${level.toUpperCase()}] ${timestamp}: ${message}`);
|
||||
|
||||
// Store logs in localStorage too
|
||||
const logs = JSON.parse(localStorage.getItem("system_logs") || "[]");
|
||||
logs.push({ timestamp, level, message });
|
||||
localStorage.setItem("system_logs", JSON.stringify(logs));
|
||||
|
||||
// If error, send notification
|
||||
if (level === "error") {
|
||||
// Send email notification
|
||||
this.sendEmailAlert(message);
|
||||
}
|
||||
},
|
||||
|
||||
sendEmailAlert: function (message: string) {
|
||||
console.log(`Sending email alert: ${message}`);
|
||||
// Simulate email sending
|
||||
setTimeout(() => {
|
||||
console.log("Email sent!");
|
||||
}, 1000);
|
||||
},
|
||||
};
|
||||
|
||||
// Load configuration
|
||||
let config;
|
||||
try {
|
||||
config = JSON.parse(localStorage.getItem("user_system_config") || "{}");
|
||||
DEBUG_MODE = config.debugMode || DEBUG_MODE;
|
||||
this.apiToken = config.apiToken || this.apiToken;
|
||||
} catch (e) {
|
||||
this.logger.log("Failed to load configuration", "error");
|
||||
}
|
||||
}
|
||||
|
||||
// Database connection hardcoded
|
||||
private connectToDatabase() {
|
||||
this.logger.log("Connecting to database...", "debug");
|
||||
|
||||
// Simulate database connection
|
||||
this.db = {
|
||||
query: function (sql: string, params: any[] = []) {
|
||||
console.log(`Executing query: ${sql}`);
|
||||
console.log("Params:", params);
|
||||
return Promise.resolve({ rows: [], success: true });
|
||||
},
|
||||
|
||||
close: function () {
|
||||
console.log("Closing database connection");
|
||||
},
|
||||
};
|
||||
|
||||
// Log connection info to console in plain text
|
||||
console.log(`Connected to database with token: ${this.apiToken}`);
|
||||
|
||||
// Save connection timestamp
|
||||
localStorage.setItem("last_db_connection", new Date().toISOString());
|
||||
}
|
||||
|
||||
// UI generation mixed with business logic
|
||||
public renderUserList(containerId: string) {
|
||||
const container = document.getElementById(containerId);
|
||||
if (!container) {
|
||||
this.logger.log(`Container ${containerId} not found`, "error");
|
||||
return;
|
||||
}
|
||||
|
||||
// Clear container
|
||||
container.innerHTML = "";
|
||||
|
||||
// Get users - mixing data fetching and rendering
|
||||
this.db
|
||||
.query('SELECT * FROM users WHERE status != "deleted"')
|
||||
.then((result: any) => {
|
||||
this.users = result.rows;
|
||||
|
||||
// Generate HTML - UI logic mixed with business logic
|
||||
let html = '<ul class="user-list">';
|
||||
this.users.forEach((user) => {
|
||||
// User status determines CSS class
|
||||
let statusClass = "";
|
||||
switch (user.status) {
|
||||
case "active":
|
||||
statusClass = "user-active";
|
||||
break;
|
||||
case "inactive":
|
||||
statusClass = "user-inactive";
|
||||
break;
|
||||
case "suspended":
|
||||
statusClass = "user-suspended";
|
||||
break;
|
||||
}
|
||||
|
||||
html += `
|
||||
<li class="user-item ${statusClass}" data-id="${user.id}">
|
||||
<div class="user-name">${user.firstName} ${user.lastName}</div>
|
||||
<div class="user-email">${user.email}</div>
|
||||
<div class="user-actions">
|
||||
<button onclick="userManager.editUser(${user.id})">Edit</button>
|
||||
<button onclick="userManager.deleteUser(${user.id})">Delete</button>
|
||||
${
|
||||
user.status === "active"
|
||||
? `<button onclick="userManager.suspendUser(${user.id})">Suspend</button>`
|
||||
: `<button onclick="userManager.activateUser(${user.id})">Activate</button>`
|
||||
}
|
||||
</div>
|
||||
</li>
|
||||
`;
|
||||
});
|
||||
html += "</ul>";
|
||||
|
||||
container.innerHTML = html;
|
||||
})
|
||||
.catch((err: any) => {
|
||||
this.logger.log(`Failed to fetch users: ${err.message}`, "error");
|
||||
container.innerHTML =
|
||||
"<p>Failed to load users. Please try again later.</p>";
|
||||
});
|
||||
}
|
||||
|
||||
// No validation, directly manipulating UI and data
|
||||
public createUser(userData: any) {
|
||||
// Directly create user without validation
|
||||
this.db
|
||||
.query(
|
||||
"INSERT INTO users (firstName, lastName, email, status) VALUES (?, ?, ?, ?)",
|
||||
[userData.firstName, userData.lastName, userData.email, "active"],
|
||||
)
|
||||
.then((result: any) => {
|
||||
this.logger.log(`User created: ${userData.email}`, "info");
|
||||
|
||||
// Update UI directly here
|
||||
this.renderUserList("user-container");
|
||||
|
||||
// Update global state
|
||||
this.lastOperation = "create";
|
||||
|
||||
// Clear form - direct DOM manipulation
|
||||
document.getElementById("user-form")?.reset();
|
||||
|
||||
// Show success message
|
||||
alert("User created successfully!");
|
||||
})
|
||||
.catch((err: any) => {
|
||||
this.logger.log(`Failed to create user: ${err.message}`, "error");
|
||||
alert("Failed to create user! " + err.message);
|
||||
});
|
||||
}
|
||||
|
||||
// Logic duplicated for similar operations
|
||||
public editUser(userId: number) {
|
||||
// Directly edit UI elements based on user ID
|
||||
const userElement = document.querySelector(`li[data-id="${userId}"]`);
|
||||
if (!userElement) {
|
||||
this.logger.log(`User element not found: ${userId}`, "error");
|
||||
return;
|
||||
}
|
||||
|
||||
// Find user data
|
||||
const user = this.users.find((u) => u.id === userId);
|
||||
if (!user) {
|
||||
this.logger.log(`User not found: ${userId}`, "error");
|
||||
return;
|
||||
}
|
||||
|
||||
// Populate form - direct DOM manipulation
|
||||
const form = document.getElementById("user-form") as HTMLFormElement;
|
||||
if (form) {
|
||||
(form.elements.namedItem("firstName") as HTMLInputElement).value =
|
||||
user.firstName;
|
||||
(form.elements.namedItem("lastName") as HTMLInputElement).value =
|
||||
user.lastName;
|
||||
(form.elements.namedItem("email") as HTMLInputElement).value = user.email;
|
||||
(form.elements.namedItem("userId") as HTMLInputElement).value =
|
||||
String(userId);
|
||||
|
||||
// Scroll to form
|
||||
form.scrollIntoView({ behavior: "smooth" });
|
||||
}
|
||||
|
||||
// Update global state
|
||||
currentUserID = userId;
|
||||
this.lastOperation = "edit";
|
||||
}
|
||||
|
||||
// Logic duplicated, similar to deleteUser
|
||||
public suspendUser(userId: number) {
|
||||
if (!confirm("Are you sure you want to suspend this user?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
this.db
|
||||
.query("UPDATE users SET status = ? WHERE id = ?", ["suspended", userId])
|
||||
.then((result: any) => {
|
||||
this.logger.log(`User suspended: ${userId}`, "info");
|
||||
|
||||
// Update UI directly
|
||||
this.renderUserList("user-container");
|
||||
|
||||
// Update global state
|
||||
this.lastOperation = "suspend";
|
||||
|
||||
// Show success message
|
||||
alert("User suspended successfully!");
|
||||
})
|
||||
.catch((err: any) => {
|
||||
this.logger.log(`Failed to suspend user: ${err.message}`, "error");
|
||||
alert("Failed to suspend user! " + err.message);
|
||||
});
|
||||
}
|
||||
|
||||
// Nearly identical to suspendUser
|
||||
public activateUser(userId: number) {
|
||||
this.db
|
||||
.query("UPDATE users SET status = ? WHERE id = ?", ["active", userId])
|
||||
.then((result: any) => {
|
||||
this.logger.log(`User activated: ${userId}`, "info");
|
||||
|
||||
// Update UI directly
|
||||
this.renderUserList("user-container");
|
||||
|
||||
// Update global state
|
||||
this.lastOperation = "activate";
|
||||
|
||||
// Show success message
|
||||
alert("User activated successfully!");
|
||||
})
|
||||
.catch((err: any) => {
|
||||
this.logger.log(`Failed to activate user: ${err.message}`, "error");
|
||||
alert("Failed to activate user! " + err.message);
|
||||
});
|
||||
}
|
||||
|
||||
// Logic duplicated again
|
||||
public deleteUser(userId: number) {
|
||||
if (!confirm("Are you sure you want to delete this user?")) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Actually just updating status to 'deleted'
|
||||
this.db
|
||||
.query("UPDATE users SET status = ? WHERE id = ?", ["deleted", userId])
|
||||
.then((result: any) => {
|
||||
this.logger.log(`User deleted: ${userId}`, "info");
|
||||
|
||||
// Update UI directly
|
||||
this.renderUserList("user-container");
|
||||
|
||||
// Update global state
|
||||
this.lastOperation = "delete";
|
||||
|
||||
// Show success message
|
||||
alert("User deleted successfully!");
|
||||
})
|
||||
.catch((err: any) => {
|
||||
this.logger.log(`Failed to delete user: ${err.message}`, "error");
|
||||
alert("Failed to delete user! " + err.message);
|
||||
});
|
||||
}
|
||||
|
||||
// Authentication mixed with user management
|
||||
public login(email: string, password: string) {
|
||||
// Directly query with credentials
|
||||
this.db
|
||||
.query("SELECT * FROM users WHERE email = ? AND password_hash = ?", [
|
||||
email,
|
||||
this.hashPassword(password),
|
||||
])
|
||||
.then((result: any) => {
|
||||
if (result.rows.length === 0) {
|
||||
this.logger.log(`Failed login attempt: ${email}`, "warn");
|
||||
alert("Invalid email or password");
|
||||
return;
|
||||
}
|
||||
|
||||
const user = result.rows[0];
|
||||
if (user.status !== "active") {
|
||||
this.logger.log(
|
||||
`Login attempt from inactive account: ${email}`,
|
||||
"warn",
|
||||
);
|
||||
alert("Your account is not active");
|
||||
return;
|
||||
}
|
||||
|
||||
// Update global state
|
||||
currentUserID = user.id;
|
||||
loggedInUsers.push(user);
|
||||
this.lastOperation = "login";
|
||||
|
||||
// Store in localStorage
|
||||
localStorage.setItem("current_user", JSON.stringify(user));
|
||||
|
||||
// Redirect to dashboard
|
||||
window.location.href = "/dashboard.html";
|
||||
})
|
||||
.catch((err: any) => {
|
||||
this.logger.log(`Login error: ${err.message}`, "error");
|
||||
alert("Login failed! " + err.message);
|
||||
});
|
||||
}
|
||||
|
||||
// Utility function with security implications
|
||||
private hashPassword(password: string): string {
|
||||
// Not a real hash, just base64 encoding
|
||||
return btoa(password);
|
||||
}
|
||||
|
||||
// Cleanup that's never called
|
||||
public cleanup() {
|
||||
this.logger.log("Cleaning up resources", "debug");
|
||||
this.db.close();
|
||||
this.users = [];
|
||||
currentUserID = null;
|
||||
}
|
||||
}
|
||||
|
||||
// Instantiate globally
|
||||
const userManager = new UserManager();
|
||||
|
||||
// Event handlers directly in global scope
|
||||
function handleUserFormSubmit(event: Event) {
|
||||
event.preventDefault();
|
||||
const form = event.target as HTMLFormElement;
|
||||
|
||||
const userData = {
|
||||
firstName: (form.elements.namedItem("firstName") as HTMLInputElement).value,
|
||||
lastName: (form.elements.namedItem("lastName") as HTMLInputElement).value,
|
||||
email: (form.elements.namedItem("email") as HTMLInputElement).value,
|
||||
};
|
||||
|
||||
const userId = (form.elements.namedItem("userId") as HTMLInputElement).value;
|
||||
|
||||
if (userId) {
|
||||
// Should call an update method, but directly calls the database
|
||||
userManager.db
|
||||
.query(
|
||||
"UPDATE users SET firstName = ?, lastName = ?, email = ? WHERE id = ?",
|
||||
[userData.firstName, userData.lastName, userData.email, userId],
|
||||
)
|
||||
.then(() => {
|
||||
alert("User updated successfully!");
|
||||
userManager.renderUserList("user-container");
|
||||
form.reset();
|
||||
(form.elements.namedItem("userId") as HTMLInputElement).value = "";
|
||||
})
|
||||
.catch((err: any) => {
|
||||
alert("Failed to update user: " + err.message);
|
||||
});
|
||||
} else {
|
||||
userManager.createUser(userData);
|
||||
}
|
||||
}
|
||||
|
||||
// Global initialization
|
||||
window.onload = function () {
|
||||
console.log("Window loaded!");
|
||||
|
||||
// Set up event listeners
|
||||
const userForm = document.getElementById("user-form");
|
||||
if (userForm) {
|
||||
userForm.addEventListener("submit", handleUserFormSubmit);
|
||||
}
|
||||
|
||||
// Initialize user list
|
||||
userManager.renderUserList("user-container");
|
||||
|
||||
// Set up some global error handlers
|
||||
window.onerror = function (msg, url, line) {
|
||||
userManager.logger.log(`Global error: ${msg} at ${url}:${line}`, "error");
|
||||
return false;
|
||||
};
|
||||
};
|
||||
|
||||
// Global exports
|
||||
(window as any).userManager = userManager;
|
||||
(window as any).handleUserFormSubmit = handleUserFormSubmit;
|
||||
654
manual-testing-sandbox/next-edit/next-edit-9-5-sol.ts
Normal file
654
manual-testing-sandbox/next-edit/next-edit-9-5-sol.ts
Normal file
|
|
@ -0,0 +1,654 @@
|
|||
// Clean implementation of e-commerce product management system
|
||||
// Following SOLID principles
|
||||
|
||||
// Types and Interfaces
|
||||
type ProductStatus =
|
||||
| "active"
|
||||
| "inactive"
|
||||
| "discontinued"
|
||||
| "out_of_stock"
|
||||
| "backorder";
|
||||
type UserRole = "admin" | "manager" | "staff" | "customer";
|
||||
|
||||
interface Product {
|
||||
id: string;
|
||||
name: string;
|
||||
price: number;
|
||||
description: string;
|
||||
image: string;
|
||||
category: string;
|
||||
status: ProductStatus;
|
||||
created: Date;
|
||||
createdBy: string;
|
||||
stock: number;
|
||||
ratings: any[];
|
||||
tags: string[];
|
||||
lastModified: Date;
|
||||
lastModifiedBy?: string;
|
||||
}
|
||||
|
||||
interface User {
|
||||
id: string;
|
||||
username: string;
|
||||
role: UserRole;
|
||||
}
|
||||
|
||||
interface CartItem {
|
||||
productId: string;
|
||||
quantity: number;
|
||||
price: number;
|
||||
name: string;
|
||||
addedAt: Date;
|
||||
}
|
||||
|
||||
interface Notification {
|
||||
type: string;
|
||||
message: string;
|
||||
timestamp: Date;
|
||||
}
|
||||
|
||||
interface LogEntry {
|
||||
timestamp: string;
|
||||
action: string;
|
||||
data: any;
|
||||
user: string;
|
||||
}
|
||||
|
||||
interface SearchFilters {
|
||||
category?: string;
|
||||
minPrice?: number;
|
||||
maxPrice?: number;
|
||||
status?: ProductStatus;
|
||||
}
|
||||
|
||||
// Database abstraction - Single Responsibility for data persistence
|
||||
class Database {
|
||||
private products: Map<string, Product> = new Map();
|
||||
private users: Map<string, User> = new Map();
|
||||
private cart: Map<string, CartItem[]> = new Map();
|
||||
private orders: any[] = [];
|
||||
private logs: LogEntry[] = [];
|
||||
private sessions: Map<string, any> = new Map();
|
||||
private config = { taxRate: 0.08, discountThreshold: 1000 };
|
||||
|
||||
// Product repository methods
|
||||
getProduct(id: string): Product | undefined {
|
||||
return this.products.get(id);
|
||||
}
|
||||
|
||||
saveProduct(product: Product): void {
|
||||
this.products.set(product.id, product);
|
||||
}
|
||||
|
||||
removeProduct(id: string): boolean {
|
||||
return this.products.delete(id);
|
||||
}
|
||||
|
||||
getAllProducts(): Product[] {
|
||||
return Array.from(this.products.values());
|
||||
}
|
||||
|
||||
// Cart repository methods
|
||||
getCart(userId: string): CartItem[] {
|
||||
return this.cart.get(userId) || [];
|
||||
}
|
||||
|
||||
saveCart(userId: string, cart: CartItem[]): void {
|
||||
this.cart.set(userId, cart);
|
||||
}
|
||||
|
||||
// Logging method
|
||||
addLog(logEntry: LogEntry): void {
|
||||
this.logs.push(logEntry);
|
||||
}
|
||||
}
|
||||
|
||||
// Authentication service - Single Responsibility for user management
|
||||
class AuthService {
|
||||
private currentUser: User | null = null;
|
||||
|
||||
constructor(private database: Database) {}
|
||||
|
||||
getCurrentUser(): User | null {
|
||||
return this.currentUser;
|
||||
}
|
||||
|
||||
setCurrentUser(user: User): void {
|
||||
this.currentUser = user;
|
||||
}
|
||||
|
||||
logout(): void {
|
||||
this.currentUser = null;
|
||||
}
|
||||
|
||||
hasPermission(allowedRoles: UserRole[]): boolean {
|
||||
if (!this.currentUser) return false;
|
||||
return allowedRoles.includes(this.currentUser.role);
|
||||
}
|
||||
}
|
||||
|
||||
// Utility service - Single Responsibility for common functions
|
||||
class UtilityService {
|
||||
generateId(prefix: string): string {
|
||||
return `${prefix}_${Math.random().toString(36).substring(2, 9)}`;
|
||||
}
|
||||
}
|
||||
|
||||
// Logger service - Single Responsibility for logging
|
||||
class LoggingService {
|
||||
constructor(
|
||||
private database: Database,
|
||||
private authService: AuthService,
|
||||
) {}
|
||||
|
||||
log(action: string, data: any): void {
|
||||
const timestamp = new Date().toISOString();
|
||||
const logEntry: LogEntry = {
|
||||
timestamp,
|
||||
action,
|
||||
data,
|
||||
user: this.authService.getCurrentUser()?.username || "system",
|
||||
};
|
||||
|
||||
this.database.addLog(logEntry);
|
||||
console.log(`[${timestamp}] ${action}:`, data);
|
||||
}
|
||||
}
|
||||
|
||||
// Notification service - Single Responsibility for notifications
|
||||
class NotificationService {
|
||||
private notifications: Notification[] = [];
|
||||
|
||||
addNotification(type: string, message: string): void {
|
||||
this.notifications.push({
|
||||
type,
|
||||
message,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
getNotifications(): Notification[] {
|
||||
return [...this.notifications];
|
||||
}
|
||||
}
|
||||
|
||||
// Email service - Single Responsibility for email communication
|
||||
class EmailService {
|
||||
sendEmailToSubscribers(
|
||||
productName: string,
|
||||
subject: string,
|
||||
body: string,
|
||||
): void {
|
||||
console.log(`Sending email about ${productName} to subscribers`);
|
||||
// Actual email sending logic would go here
|
||||
}
|
||||
}
|
||||
|
||||
// Product validation - Single Responsibility for product validation
|
||||
class ProductValidator {
|
||||
validate(name: string, price: number): boolean {
|
||||
return name !== "" && price > 0;
|
||||
}
|
||||
}
|
||||
|
||||
// Auth middleware interface - Open/Closed Principle
|
||||
interface AuthorizationMiddleware {
|
||||
checkAuthorization(operation: string): boolean;
|
||||
}
|
||||
|
||||
// Product authorization - Single Responsibility for product auth
|
||||
class ProductAuthorizationMiddleware implements AuthorizationMiddleware {
|
||||
constructor(private authService: AuthService) {}
|
||||
|
||||
checkAuthorization(operation: string): boolean {
|
||||
const currentUser = this.authService.getCurrentUser();
|
||||
if (!currentUser) return false;
|
||||
|
||||
switch (operation) {
|
||||
case "create":
|
||||
case "update":
|
||||
return this.authService.hasPermission(["admin", "manager"]);
|
||||
case "delete":
|
||||
return this.authService.hasPermission(["admin"]);
|
||||
case "view":
|
||||
return true;
|
||||
default:
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Product service - Core business logic with proper separation of concerns
|
||||
class ProductService {
|
||||
constructor(
|
||||
private database: Database,
|
||||
private utilityService: UtilityService,
|
||||
private loggingService: LoggingService,
|
||||
private notificationService: NotificationService,
|
||||
private emailService: EmailService,
|
||||
private validator: ProductValidator,
|
||||
private authMiddleware: AuthorizationMiddleware,
|
||||
) {}
|
||||
|
||||
createProduct(
|
||||
name: string,
|
||||
price: number,
|
||||
description: string,
|
||||
image: string,
|
||||
category: string,
|
||||
initialStock: number = 100,
|
||||
): string {
|
||||
// Authorization check
|
||||
if (!this.authMiddleware.checkAuthorization("create")) {
|
||||
throw new Error("Unauthorized access");
|
||||
}
|
||||
|
||||
// Validation
|
||||
if (!this.validator.validate(name, price)) {
|
||||
throw new Error("Invalid product data");
|
||||
}
|
||||
|
||||
const currentUser = this.database.getUsers()[0]; // This is a placeholder - we'd use proper auth in a real app
|
||||
const id = this.utilityService.generateId("prod");
|
||||
const tags = category.split(",").map((t) => t.trim());
|
||||
|
||||
// Create product object
|
||||
const product: Product = {
|
||||
id,
|
||||
name,
|
||||
price,
|
||||
description,
|
||||
image,
|
||||
category,
|
||||
status: "active" as ProductStatus,
|
||||
created: new Date(),
|
||||
createdBy: currentUser.id,
|
||||
stock: initialStock,
|
||||
ratings: [],
|
||||
tags,
|
||||
lastModified: new Date(),
|
||||
};
|
||||
|
||||
// Save to database
|
||||
this.database.saveProduct(product);
|
||||
|
||||
// Logging
|
||||
this.loggingService.log("product_added", { id, name, price });
|
||||
|
||||
// Notification
|
||||
this.notificationService.addNotification(
|
||||
"product_added",
|
||||
`New product added: ${name}`,
|
||||
);
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
updateProduct(id: string, data: Partial<Product>): Product {
|
||||
// Authorization check
|
||||
if (!this.authMiddleware.checkAuthorization("update")) {
|
||||
throw new Error("Unauthorized access");
|
||||
}
|
||||
|
||||
const product = this.database.getProduct(id);
|
||||
if (!product) {
|
||||
throw new Error("Product not found");
|
||||
}
|
||||
|
||||
// Create updated product - preventing modification of protected fields
|
||||
const updatedProduct = { ...product };
|
||||
|
||||
Object.keys(data).forEach((key) => {
|
||||
if (key !== "id" && key !== "created" && key !== "createdBy") {
|
||||
updatedProduct[key as keyof Product] = data[
|
||||
key as keyof Product
|
||||
] as any;
|
||||
}
|
||||
});
|
||||
|
||||
const currentUser = this.database.getUsers()[0]; // Placeholder
|
||||
updatedProduct.lastModified = new Date();
|
||||
updatedProduct.lastModifiedBy = currentUser.id;
|
||||
|
||||
// Save to database
|
||||
this.database.saveProduct(updatedProduct);
|
||||
|
||||
// Logging
|
||||
this.loggingService.log("product_updated", { id, changes: data });
|
||||
|
||||
// Notification
|
||||
this.notificationService.addNotification(
|
||||
"product_updated",
|
||||
`Product updated: ${updatedProduct.name}`,
|
||||
);
|
||||
|
||||
// Handle special status changes
|
||||
if (data.status === "discontinued") {
|
||||
this.emailService.sendEmailToSubscribers(
|
||||
updatedProduct.name,
|
||||
"Product Discontinued",
|
||||
`The product ${updatedProduct.name} has been discontinued.`,
|
||||
);
|
||||
}
|
||||
|
||||
return updatedProduct;
|
||||
}
|
||||
|
||||
deleteProduct(id: string): boolean {
|
||||
// Authorization check
|
||||
if (!this.authMiddleware.checkAuthorization("delete")) {
|
||||
throw new Error("Unauthorized access");
|
||||
}
|
||||
|
||||
const product = this.database.getProduct(id);
|
||||
if (!product) {
|
||||
throw new Error("Product not found");
|
||||
}
|
||||
|
||||
// Business rule validation
|
||||
if (product.status === "active" && product.stock > 0) {
|
||||
throw new Error("Cannot delete active product with stock");
|
||||
}
|
||||
|
||||
// Delete from database
|
||||
const result = this.database.removeProduct(id);
|
||||
|
||||
// Logging
|
||||
this.loggingService.log("product_deleted", { id, name: product.name });
|
||||
|
||||
// Notification
|
||||
this.notificationService.addNotification(
|
||||
"product_deleted",
|
||||
`Product deleted: ${product.name}`,
|
||||
);
|
||||
|
||||
return result;
|
||||
}
|
||||
|
||||
searchProducts(query: string, filters: SearchFilters = {}): Product[] {
|
||||
const products = this.database.getAllProducts();
|
||||
const results = products.filter((product) => {
|
||||
// Match text search
|
||||
const matches =
|
||||
product.name.toLowerCase().includes(query.toLowerCase()) ||
|
||||
product.description.toLowerCase().includes(query.toLowerCase());
|
||||
|
||||
if (!matches) return false;
|
||||
|
||||
// Apply filters
|
||||
if (filters.category && product.category !== filters.category) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (filters.minPrice && product.price < filters.minPrice) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (filters.maxPrice && product.price > filters.maxPrice) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (filters.status && product.status !== filters.status) {
|
||||
return false;
|
||||
}
|
||||
|
||||
return true;
|
||||
});
|
||||
|
||||
// Log search results
|
||||
this.loggingService.log("product_search", {
|
||||
query,
|
||||
filters,
|
||||
resultCount: results.length,
|
||||
});
|
||||
|
||||
return results;
|
||||
}
|
||||
}
|
||||
|
||||
// Cart service - Single Responsibility for shopping cart functionality
|
||||
class CartService {
|
||||
constructor(
|
||||
private database: Database,
|
||||
private authService: AuthService,
|
||||
private loggingService: LoggingService,
|
||||
) {}
|
||||
|
||||
addToCart(productId: string, quantity: number = 1): CartItem[] {
|
||||
const currentUser = this.authService.getCurrentUser();
|
||||
if (!currentUser) {
|
||||
throw new Error("Must be logged in to add to cart");
|
||||
}
|
||||
|
||||
const product = this.database.getProduct(productId);
|
||||
if (!product) {
|
||||
throw new Error("Product not found");
|
||||
}
|
||||
|
||||
if (product.status !== "active") {
|
||||
throw new Error("Product is not available");
|
||||
}
|
||||
|
||||
if (product.stock < quantity) {
|
||||
throw new Error("Not enough stock");
|
||||
}
|
||||
|
||||
// Get current cart
|
||||
const cart = this.database.getCart(currentUser.id);
|
||||
|
||||
// Update or add item
|
||||
const existingItemIndex = cart.findIndex(
|
||||
(item) => item.productId === productId,
|
||||
);
|
||||
|
||||
if (existingItemIndex >= 0) {
|
||||
cart[existingItemIndex].quantity += quantity;
|
||||
} else {
|
||||
cart.push({
|
||||
productId,
|
||||
quantity,
|
||||
price: product.price,
|
||||
name: product.name,
|
||||
addedAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
// Update product stock
|
||||
product.stock -= quantity;
|
||||
this.database.saveProduct(product);
|
||||
|
||||
// Save cart
|
||||
this.database.saveCart(currentUser.id, cart);
|
||||
|
||||
// Log action
|
||||
this.loggingService.log("cart_add", {
|
||||
productId,
|
||||
quantity,
|
||||
userId: currentUser.id,
|
||||
});
|
||||
|
||||
return cart;
|
||||
}
|
||||
}
|
||||
|
||||
// Service Factory - Creates and wires up the services
|
||||
class ServiceFactory {
|
||||
static createProductService(): ProductService {
|
||||
const database = new Database();
|
||||
const authService = new AuthService(database);
|
||||
const utilityService = new UtilityService();
|
||||
const loggingService = new LoggingService(database, authService);
|
||||
const notificationService = new NotificationService();
|
||||
const emailService = new EmailService();
|
||||
const productValidator = new ProductValidator();
|
||||
const authMiddleware = new ProductAuthorizationMiddleware(authService);
|
||||
|
||||
return new ProductService(
|
||||
database,
|
||||
utilityService,
|
||||
loggingService,
|
||||
notificationService,
|
||||
emailService,
|
||||
productValidator,
|
||||
authMiddleware,
|
||||
);
|
||||
}
|
||||
|
||||
static createCartService(): CartService {
|
||||
const database = new Database();
|
||||
const authService = new AuthService(database);
|
||||
const loggingService = new LoggingService(database, authService);
|
||||
|
||||
return new CartService(database, authService, loggingService);
|
||||
}
|
||||
}
|
||||
|
||||
// Example usage:
|
||||
/*
|
||||
const productService = ServiceFactory.createProductService();
|
||||
const cartService = ServiceFactory.createCartService();
|
||||
|
||||
// Create a product
|
||||
const productId = productService.createProduct(
|
||||
'Gaming Laptop',
|
||||
1299.99,
|
||||
'High performance gaming laptop',
|
||||
'laptop.jpg',
|
||||
'Electronics,Computers',
|
||||
100
|
||||
);
|
||||
|
||||
// Add to cart
|
||||
cartService.addToCart(productId, 2);
|
||||
*/
|
||||
|
||||
/*
|
||||
Original Code Smells:
|
||||
|
||||
Violation of Single Responsibility Principle (SRP)
|
||||
|
||||
ProductManager class handles product management, cart operations, email sending, UI updates, and analytics
|
||||
Database operations, validation, logging, and notifications are all mixed together
|
||||
|
||||
|
||||
Violation of Open/Closed Principle (OCP)
|
||||
|
||||
Code is not structured to be easily extended without modification
|
||||
Hard-coded business rules and functionality
|
||||
|
||||
|
||||
Poor Encapsulation
|
||||
|
||||
Global variables (DATABASE, CURRENT_USER, NOTIFICATIONS)
|
||||
Direct manipulation of shared state
|
||||
|
||||
|
||||
Tight Coupling
|
||||
|
||||
Business logic directly depends on UI elements (document, window)
|
||||
Authentication checks embedded in business methods
|
||||
|
||||
|
||||
Singleton Anti-pattern Misuse
|
||||
|
||||
Incorrect implementation of the Singleton pattern
|
||||
|
||||
|
||||
Lack of Proper Interfaces and Abstraction
|
||||
|
||||
No clear contracts between components
|
||||
No separation between data access and business logic
|
||||
|
||||
|
||||
Code Duplication
|
||||
|
||||
Authentication checks duplicated across methods
|
||||
Notification and logging logic repeated
|
||||
|
||||
|
||||
Poor Error Handling
|
||||
|
||||
Inconsistent error handling
|
||||
Mixed validation with business operations
|
||||
|
||||
|
||||
UI Manipulation in Business Logic
|
||||
|
||||
Direct DOM manipulation in product methods
|
||||
|
||||
|
||||
Hard-coded Values
|
||||
|
||||
Default stock values
|
||||
Business rules embedded in methods
|
||||
|
||||
|
||||
Improvements Made:
|
||||
|
||||
Applied Single Responsibility Principle (SRP)
|
||||
|
||||
Created separate classes for distinct responsibilities:
|
||||
Database for data storage
|
||||
AuthService for authentication
|
||||
LoggingService for logging
|
||||
NotificationService for notifications
|
||||
EmailService for email communication
|
||||
ProductService for product business logic
|
||||
CartService for cart operations
|
||||
ProductValidator for validation
|
||||
UtilityService for utility functions
|
||||
|
||||
|
||||
Applied Open/Closed Principle (OCP)
|
||||
|
||||
Used interfaces for extensibility (e.g., AuthorizationMiddleware)
|
||||
Created classes that can be extended without modifying existing code
|
||||
|
||||
|
||||
Applied Interface Segregation Principle (ISP)
|
||||
|
||||
Created focused interfaces for different functionalities
|
||||
Ensured clients only depend on methods they use
|
||||
|
||||
|
||||
Applied Dependency Inversion Principle (DIP)
|
||||
|
||||
High-level modules depend on abstractions
|
||||
Used dependency injection to provide implementations
|
||||
|
||||
|
||||
Proper Encapsulation
|
||||
|
||||
Removed global variables
|
||||
Encapsulated state within appropriate classes
|
||||
|
||||
|
||||
Reduced Coupling
|
||||
|
||||
Removed direct UI manipulation from business logic
|
||||
Used dependency injection for loosely coupled components
|
||||
|
||||
|
||||
Implemented Factory Pattern
|
||||
|
||||
Added ServiceFactory to create and wire up services
|
||||
Simplified client code by hiding implementation details
|
||||
|
||||
|
||||
Added Type Safety
|
||||
|
||||
Created proper interfaces for data structures
|
||||
Used TypeScript types effectively
|
||||
|
||||
|
||||
Improved Error Handling
|
||||
|
||||
Consistent error checking across methods
|
||||
Validation separated from business logic
|
||||
|
||||
|
||||
Removed Code Duplication
|
||||
|
||||
Centralized authentication checks
|
||||
Reused code through proper abstraction
|
||||
*/
|
||||
302
manual-testing-sandbox/next-edit/next-edit-9-5.ts
Normal file
302
manual-testing-sandbox/next-edit/next-edit-9-5.ts
Normal file
|
|
@ -0,0 +1,302 @@
|
|||
// A messy e-commerce product management system with tangled responsibilities
|
||||
// Difficulty: 5/5
|
||||
|
||||
type ProductStatus =
|
||||
| "active"
|
||||
| "inactive"
|
||||
| "discontinued"
|
||||
| "out_of_stock"
|
||||
| "backorder";
|
||||
type UserRole = "admin" | "manager" | "staff" | "customer";
|
||||
let DATABASE: any = {
|
||||
products: new Map(),
|
||||
users: new Map(),
|
||||
cart: new Map(),
|
||||
orders: [],
|
||||
logs: [],
|
||||
sessions: new Map(),
|
||||
config: { taxRate: 0.08, discountThreshold: 1000 },
|
||||
};
|
||||
let CURRENT_USER: any = null;
|
||||
let NOTIFICATIONS: any[] = [];
|
||||
|
||||
// Global function to generate IDs (mixes concerns and not encapsulated)
|
||||
function generateId(prefix: string) {
|
||||
return `${prefix}_${Math.random().toString(36).substring(2, 9)}`;
|
||||
}
|
||||
|
||||
// Global function for logging (mixed with business logic)
|
||||
function log(action: string, data: any) {
|
||||
const timestamp = new Date().toISOString();
|
||||
DATABASE.logs.push({
|
||||
timestamp,
|
||||
action,
|
||||
data,
|
||||
user: CURRENT_USER?.username || "system",
|
||||
});
|
||||
console.log(`[${timestamp}] ${action}:`, data);
|
||||
}
|
||||
|
||||
class ProductManager {
|
||||
// This class does way too much - violates SRP
|
||||
static instance: ProductManager;
|
||||
private constructor() {}
|
||||
|
||||
// Singleton pattern used incorrectly
|
||||
static getInstance() {
|
||||
if (!ProductManager.instance) {
|
||||
ProductManager.instance = new ProductManager();
|
||||
}
|
||||
return ProductManager.instance;
|
||||
}
|
||||
|
||||
addProduct(
|
||||
name: string,
|
||||
price: number,
|
||||
desc: string,
|
||||
img: string,
|
||||
category: string,
|
||||
) {
|
||||
// Validation mixed with business logic
|
||||
if (!name || price <= 0) {
|
||||
throw new Error("Invalid product data");
|
||||
}
|
||||
|
||||
// Authentication check shouldn't be here
|
||||
if (
|
||||
!CURRENT_USER ||
|
||||
(CURRENT_USER.role !== "admin" && CURRENT_USER.role !== "manager")
|
||||
) {
|
||||
throw new Error("Unauthorized access");
|
||||
}
|
||||
|
||||
const id = generateId("prod");
|
||||
|
||||
// Direct database manipulation and notification logic mixed together
|
||||
DATABASE.products.set(id, {
|
||||
id,
|
||||
name,
|
||||
price,
|
||||
description: desc,
|
||||
image: img,
|
||||
category,
|
||||
status: "active",
|
||||
created: new Date(),
|
||||
createdBy: CURRENT_USER.id,
|
||||
stock: 100, // Default hardcoded
|
||||
ratings: [],
|
||||
tags: category.split(",").map((t: string) => t.trim()),
|
||||
lastModified: new Date(),
|
||||
});
|
||||
|
||||
// Notification logic should be separated
|
||||
NOTIFICATIONS.push({
|
||||
type: "product_added",
|
||||
message: `New product added: ${name}`,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// Logging should be a cross-cutting concern
|
||||
log("product_added", { id, name, price });
|
||||
|
||||
// UI manipulation mixed with business logic
|
||||
if (document) {
|
||||
const productList = document.getElementById("product-list");
|
||||
if (productList) {
|
||||
const productEl = document.createElement("div");
|
||||
productEl.innerHTML = `<div class="product">${name} - $${price}</div>`;
|
||||
productList.appendChild(productEl);
|
||||
}
|
||||
}
|
||||
|
||||
// Analytics tracking mixed in with product creation
|
||||
if (window) {
|
||||
try {
|
||||
(window as any).ga("send", "event", "Products", "Create", name);
|
||||
} catch (e) {
|
||||
console.error("Analytics error", e);
|
||||
}
|
||||
}
|
||||
|
||||
return id;
|
||||
}
|
||||
|
||||
updateProduct(id: string, data: any) {
|
||||
if (!DATABASE.products.has(id)) {
|
||||
throw new Error("Product not found");
|
||||
}
|
||||
|
||||
// Authentication check duplicated
|
||||
if (
|
||||
!CURRENT_USER ||
|
||||
(CURRENT_USER.role !== "admin" && CURRENT_USER.role !== "manager")
|
||||
) {
|
||||
throw new Error("Unauthorized access");
|
||||
}
|
||||
|
||||
const product = DATABASE.products.get(id);
|
||||
|
||||
// Updating with direct object manipulation
|
||||
Object.keys(data).forEach((key) => {
|
||||
if (key !== "id" && key !== "created" && key !== "createdBy") {
|
||||
product[key] = data[key];
|
||||
}
|
||||
});
|
||||
|
||||
product.lastModified = new Date();
|
||||
product.lastModifiedBy = CURRENT_USER.id;
|
||||
|
||||
DATABASE.products.set(id, product);
|
||||
|
||||
// More mixed responsibilities
|
||||
log("product_updated", { id, changes: data });
|
||||
|
||||
// Duplicated notification logic
|
||||
NOTIFICATIONS.push({
|
||||
type: "product_updated",
|
||||
message: `Product updated: ${product.name}`,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
// Email notification logic mixed in
|
||||
if (product.status === "discontinued") {
|
||||
this.sendEmailToSubscribers(
|
||||
product.id,
|
||||
"Product Discontinued",
|
||||
`The product ${product.name} has been discontinued.`,
|
||||
);
|
||||
}
|
||||
|
||||
return product;
|
||||
}
|
||||
|
||||
deleteProduct(id: string) {
|
||||
// More authentication mixed in business logic
|
||||
if (!CURRENT_USER || CURRENT_USER.role !== "admin") {
|
||||
throw new Error("Only admins can delete products");
|
||||
}
|
||||
|
||||
if (!DATABASE.products.has(id)) {
|
||||
throw new Error("Product not found");
|
||||
}
|
||||
|
||||
const product = DATABASE.products.get(id);
|
||||
|
||||
// Business rules mixed with deletion logic
|
||||
if (product.status === "active" && product.stock > 0) {
|
||||
throw new Error("Cannot delete active product with stock");
|
||||
}
|
||||
|
||||
// More mixed concerns
|
||||
log("product_deleted", { id, name: product.name });
|
||||
NOTIFICATIONS.push({
|
||||
type: "product_deleted",
|
||||
message: `Product deleted: ${product.name}`,
|
||||
timestamp: new Date(),
|
||||
});
|
||||
|
||||
DATABASE.products.delete(id);
|
||||
|
||||
// Cache clearing mixed with business logic
|
||||
if (window && (window as any).cache) {
|
||||
(window as any).cache.invalidate("products");
|
||||
}
|
||||
|
||||
return true;
|
||||
}
|
||||
|
||||
// Email functionality mixed in the product manager
|
||||
sendEmailToSubscribers(productId: string, subject: string, body: string) {
|
||||
const product = DATABASE.products.get(productId);
|
||||
if (!product) return;
|
||||
|
||||
// Email sending logic mixed with product management
|
||||
console.log(`Sending email about ${product.name} to subscribers`);
|
||||
// Imagine API call to email service here
|
||||
}
|
||||
|
||||
// Search functionality mixed in the same class
|
||||
searchProducts(query: string, filters: any = {}) {
|
||||
let results: any[] = [];
|
||||
|
||||
DATABASE.products.forEach((product: any) => {
|
||||
let matches =
|
||||
product.name.toLowerCase().includes(query.toLowerCase()) ||
|
||||
product.description.toLowerCase().includes(query.toLowerCase());
|
||||
|
||||
if (!matches) return;
|
||||
|
||||
// Filter logic mixed in search
|
||||
if (filters.category && product.category !== filters.category) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (filters.minPrice && product.price < filters.minPrice) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (filters.maxPrice && product.price > filters.maxPrice) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (filters.status && product.status !== filters.status) {
|
||||
return;
|
||||
}
|
||||
|
||||
results.push({ ...product });
|
||||
});
|
||||
|
||||
// Logging mixed with search functionality
|
||||
log("product_search", { query, filters, resultCount: results.length });
|
||||
|
||||
return results;
|
||||
}
|
||||
|
||||
// Cart functionality shouldn't be in product manager
|
||||
addToCart(productId: string, quantity: number = 1) {
|
||||
if (!CURRENT_USER) {
|
||||
throw new Error("Must be logged in to add to cart");
|
||||
}
|
||||
|
||||
const product = DATABASE.products.get(productId);
|
||||
if (!product) {
|
||||
throw new Error("Product not found");
|
||||
}
|
||||
|
||||
if (product.status !== "active") {
|
||||
throw new Error("Product is not available");
|
||||
}
|
||||
|
||||
if (product.stock < quantity) {
|
||||
throw new Error("Not enough stock");
|
||||
}
|
||||
|
||||
let cart = DATABASE.cart.get(CURRENT_USER.id) || [];
|
||||
const existingItem = cart.find((item: any) => item.productId === productId);
|
||||
|
||||
if (existingItem) {
|
||||
existingItem.quantity += quantity;
|
||||
} else {
|
||||
cart.push({
|
||||
productId,
|
||||
quantity,
|
||||
price: product.price,
|
||||
name: product.name,
|
||||
addedAt: new Date(),
|
||||
});
|
||||
}
|
||||
|
||||
DATABASE.cart.set(CURRENT_USER.id, cart);
|
||||
product.stock -= quantity;
|
||||
DATABASE.products.set(productId, product);
|
||||
|
||||
log("cart_add", { productId, quantity, userId: CURRENT_USER.id });
|
||||
|
||||
return cart;
|
||||
}
|
||||
}
|
||||
|
||||
// Usage would be something like:
|
||||
// const pm = ProductManager.getInstance();
|
||||
// pm.addProduct('Gaming Laptop', 1299.99, 'High performance gaming laptop', 'laptop.jpg', 'Electronics,Computers');
|
||||
// pm.addToCart('prod_1abc123', 2);
|
||||
465
package-lock.json
generated
465
package-lock.json
generated
|
|
@ -4,6 +4,9 @@
|
|||
"requires": true,
|
||||
"packages": {
|
||||
"": {
|
||||
"dependencies": {
|
||||
"jsdom": "^26.1.0"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@typescript-eslint/parser": "^7.8.0",
|
||||
"concurrently": "^9.1.2",
|
||||
|
|
@ -13,6 +16,129 @@
|
|||
"typescript": "^5.6.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@asamuzakjp/css-color": {
|
||||
"version": "3.2.0",
|
||||
"resolved": "https://registry.npmjs.org/@asamuzakjp/css-color/-/css-color-3.2.0.tgz",
|
||||
"integrity": "sha512-K1A6z8tS3XsmCMM86xoWdn7Fkdn9m6RSVtocUrJYIwZnFVkng/PvkEoWtOWmP+Scc6saYWHWZYbndEEXxl24jw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@csstools/css-calc": "^2.1.3",
|
||||
"@csstools/css-color-parser": "^3.0.9",
|
||||
"@csstools/css-parser-algorithms": "^3.0.4",
|
||||
"@csstools/css-tokenizer": "^3.0.3",
|
||||
"lru-cache": "^10.4.3"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/color-helpers": {
|
||||
"version": "5.0.2",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/color-helpers/-/color-helpers-5.0.2.tgz",
|
||||
"integrity": "sha512-JqWH1vsgdGcw2RR6VliXXdA0/59LttzlU8UlRT/iUUsEeWfYq8I+K0yhihEUTTHLRm1EXvpsCx3083EU15ecsA==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT-0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/css-calc": {
|
||||
"version": "2.1.4",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/css-calc/-/css-calc-2.1.4.tgz",
|
||||
"integrity": "sha512-3N8oaj+0juUw/1H3YwmDDJXCgTB1gKU6Hc/bB502u9zR0q2vd786XJH9QfrKIEgFlZmhZiq6epXl4rHqhzsIgQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@csstools/css-parser-algorithms": "^3.0.5",
|
||||
"@csstools/css-tokenizer": "^3.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/css-color-parser": {
|
||||
"version": "3.0.10",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/css-color-parser/-/css-color-parser-3.0.10.tgz",
|
||||
"integrity": "sha512-TiJ5Ajr6WRd1r8HSiwJvZBiJOqtH86aHpUjq5aEKWHiII2Qfjqd/HCWKPOW8EP4vcspXbHnXrwIDlu5savQipg==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@csstools/color-helpers": "^5.0.2",
|
||||
"@csstools/css-calc": "^2.1.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@csstools/css-parser-algorithms": "^3.0.5",
|
||||
"@csstools/css-tokenizer": "^3.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/css-parser-algorithms": {
|
||||
"version": "3.0.5",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/css-parser-algorithms/-/css-parser-algorithms-3.0.5.tgz",
|
||||
"integrity": "sha512-DaDeUkXZKjdGhgYaHNJTV9pV7Y9B3b644jCLs9Upc3VeNGg6LWARAT6O+Q+/COo+2gg/bM5rhpMAtf70WqfBdQ==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"@csstools/css-tokenizer": "^3.0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/@csstools/css-tokenizer": {
|
||||
"version": "3.0.4",
|
||||
"resolved": "https://registry.npmjs.org/@csstools/css-tokenizer/-/css-tokenizer-3.0.4.tgz",
|
||||
"integrity": "sha512-Vd/9EVDiu6PPJt9yAh6roZP6El1xHrdvIVGjyBsHR0RYwNHgL7FJPyIIW4fANJNG6FtyZfvlRPpFI4ZM/lubvw==",
|
||||
"funding": [
|
||||
{
|
||||
"type": "github",
|
||||
"url": "https://github.com/sponsors/csstools"
|
||||
},
|
||||
{
|
||||
"type": "opencollective",
|
||||
"url": "https://opencollective.com/csstools"
|
||||
}
|
||||
],
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/@eslint-community/eslint-utils": {
|
||||
"version": "4.7.0",
|
||||
"resolved": "https://registry.npmjs.org/@eslint-community/eslint-utils/-/eslint-utils-4.7.0.tgz",
|
||||
|
|
@ -366,6 +492,15 @@
|
|||
"acorn": "^6.0.0 || ^7.0.0 || ^8.0.0"
|
||||
}
|
||||
},
|
||||
"node_modules/agent-base": {
|
||||
"version": "7.1.3",
|
||||
"resolved": "https://registry.npmjs.org/agent-base/-/agent-base-7.1.3.tgz",
|
||||
"integrity": "sha512-jRR5wdylq8CkOe6hei19GGZnxM6rBGwFl3Bg0YItGDimvjGtAvdZk4Pu6Cl4u4Igsws4a1fd1Vq3ezrhn4KmFw==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/ajv": {
|
||||
"version": "6.12.6",
|
||||
"resolved": "https://registry.npmjs.org/ajv/-/ajv-6.12.6.tgz",
|
||||
|
|
@ -781,6 +916,32 @@
|
|||
"node": ">= 8"
|
||||
}
|
||||
},
|
||||
"node_modules/cssstyle": {
|
||||
"version": "4.4.0",
|
||||
"resolved": "https://registry.npmjs.org/cssstyle/-/cssstyle-4.4.0.tgz",
|
||||
"integrity": "sha512-W0Y2HOXlPkb2yaKrCVRjinYKciu/qSLEmK0K9mcfDei3zwlnHFEHAs/Du3cIRwPqY+J4JsiBzUjoHyc8RsJ03A==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"@asamuzakjp/css-color": "^3.2.0",
|
||||
"rrweb-cssom": "^0.8.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/data-urls": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/data-urls/-/data-urls-5.0.0.tgz",
|
||||
"integrity": "sha512-ZYP5VBHshaDAiVZxjbRVcFJpc+4xGgT0bK3vzy1HLN8jTO975HEbuYzZJcHoQEY5K1a0z8YayJkyVETa08eNTg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"whatwg-mimetype": "^4.0.0",
|
||||
"whatwg-url": "^14.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/data-view-buffer": {
|
||||
"version": "1.0.2",
|
||||
"resolved": "https://registry.npmjs.org/data-view-buffer/-/data-view-buffer-1.0.2.tgz",
|
||||
|
|
@ -839,7 +1000,6 @@
|
|||
"version": "4.4.1",
|
||||
"resolved": "https://registry.npmjs.org/debug/-/debug-4.4.1.tgz",
|
||||
"integrity": "sha512-KcKCqiftBJcZr++7ykoDIEwSa3XWowTfNPo92BYxjXiyYEVrUQh2aLyhxBCwww+heortUFxEJYcRzosstTEBYQ==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"ms": "^2.1.3"
|
||||
|
|
@ -853,6 +1013,12 @@
|
|||
}
|
||||
}
|
||||
},
|
||||
"node_modules/decimal.js": {
|
||||
"version": "10.5.0",
|
||||
"resolved": "https://registry.npmjs.org/decimal.js/-/decimal.js-10.5.0.tgz",
|
||||
"integrity": "sha512-8vDa8Qxvr/+d94hSh5P3IJwI5t8/c0KsMp+g8bNw9cY2icONa5aPfvKeieW1WlG0WQYwwhJ7mjui2xtiePQSXw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/deep-is": {
|
||||
"version": "0.1.4",
|
||||
"resolved": "https://registry.npmjs.org/deep-is/-/deep-is-0.1.4.tgz",
|
||||
|
|
@ -946,6 +1112,18 @@
|
|||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/entities": {
|
||||
"version": "6.0.1",
|
||||
"resolved": "https://registry.npmjs.org/entities/-/entities-6.0.1.tgz",
|
||||
"integrity": "sha512-aN97NXWF6AWBTahfVOIrB/NShkzi5H7F9r1s9mD3cDj4Ko5f2qhhVoYMibXF7GlLveb/D2ioWay8lxI97Ven3g==",
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=0.12"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/fb55/entities?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/es-abstract": {
|
||||
"version": "1.24.0",
|
||||
"resolved": "https://registry.npmjs.org/es-abstract/-/es-abstract-1.24.0.tgz",
|
||||
|
|
@ -1941,6 +2119,56 @@
|
|||
"node": ">= 0.4"
|
||||
}
|
||||
},
|
||||
"node_modules/html-encoding-sniffer": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/html-encoding-sniffer/-/html-encoding-sniffer-4.0.0.tgz",
|
||||
"integrity": "sha512-Y22oTqIU4uuPgEemfz7NDJz6OeKf12Lsu+QC+s3BVpda64lTiMYCyGwg5ki4vFxkMwQdeZDl2adZoqUgdFuTgQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"whatwg-encoding": "^3.1.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/http-proxy-agent": {
|
||||
"version": "7.0.2",
|
||||
"resolved": "https://registry.npmjs.org/http-proxy-agent/-/http-proxy-agent-7.0.2.tgz",
|
||||
"integrity": "sha512-T1gkAiYYDWYx3V5Bmyu7HcfcvL7mUrTWiM6yOfa3PIphViJ/gFPbvidQ+veqSOHci/PxBcDabeUNCzpOODJZig==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"agent-base": "^7.1.0",
|
||||
"debug": "^4.3.4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/https-proxy-agent": {
|
||||
"version": "7.0.6",
|
||||
"resolved": "https://registry.npmjs.org/https-proxy-agent/-/https-proxy-agent-7.0.6.tgz",
|
||||
"integrity": "sha512-vK9P5/iUfdl95AI+JVyUuIcVtd4ofvtrOr3HNtM2yxC9bnMbEdp3x01OhQNnjb8IJYi38VlTE3mBXwcfvywuSw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"agent-base": "^7.1.2",
|
||||
"debug": "4"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">= 14"
|
||||
}
|
||||
},
|
||||
"node_modules/iconv-lite": {
|
||||
"version": "0.6.3",
|
||||
"resolved": "https://registry.npmjs.org/iconv-lite/-/iconv-lite-0.6.3.tgz",
|
||||
"integrity": "sha512-4fCk79wshMdzMp2rH06qWrJE4iolqLhCUH+OiuIgU++RB0+94NlDL81atO7GX55uUKueo0txHNtvEyI6D7WdMw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"safer-buffer": ">= 2.1.2 < 3.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=0.10.0"
|
||||
}
|
||||
},
|
||||
"node_modules/ignore": {
|
||||
"version": "5.3.2",
|
||||
"resolved": "https://registry.npmjs.org/ignore/-/ignore-5.3.2.tgz",
|
||||
|
|
@ -2283,6 +2511,12 @@
|
|||
"node": ">=8"
|
||||
}
|
||||
},
|
||||
"node_modules/is-potential-custom-element-name": {
|
||||
"version": "1.0.1",
|
||||
"resolved": "https://registry.npmjs.org/is-potential-custom-element-name/-/is-potential-custom-element-name-1.0.1.tgz",
|
||||
"integrity": "sha512-bCYeRA2rVibKZd+s2625gGnGF/t7DSqDs4dP7CrLA1m7jKWz6pps0LpYLJN8Q64HtmPKJ1hrN3nzPNKFEKOUiQ==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/is-regex": {
|
||||
"version": "1.2.1",
|
||||
"resolved": "https://registry.npmjs.org/is-regex/-/is-regex-1.2.1.tgz",
|
||||
|
|
@ -2457,6 +2691,45 @@
|
|||
"js-yaml": "bin/js-yaml.js"
|
||||
}
|
||||
},
|
||||
"node_modules/jsdom": {
|
||||
"version": "26.1.0",
|
||||
"resolved": "https://registry.npmjs.org/jsdom/-/jsdom-26.1.0.tgz",
|
||||
"integrity": "sha512-Cvc9WUhxSMEo4McES3P7oK3QaXldCfNWp7pl2NNeiIFlCoLr3kfq9kb1fxftiwk1FLV7CvpvDfonxtzUDeSOPg==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"cssstyle": "^4.2.1",
|
||||
"data-urls": "^5.0.0",
|
||||
"decimal.js": "^10.5.0",
|
||||
"html-encoding-sniffer": "^4.0.0",
|
||||
"http-proxy-agent": "^7.0.2",
|
||||
"https-proxy-agent": "^7.0.6",
|
||||
"is-potential-custom-element-name": "^1.0.1",
|
||||
"nwsapi": "^2.2.16",
|
||||
"parse5": "^7.2.1",
|
||||
"rrweb-cssom": "^0.8.0",
|
||||
"saxes": "^6.0.0",
|
||||
"symbol-tree": "^3.2.4",
|
||||
"tough-cookie": "^5.1.1",
|
||||
"w3c-xmlserializer": "^5.0.0",
|
||||
"webidl-conversions": "^7.0.0",
|
||||
"whatwg-encoding": "^3.1.1",
|
||||
"whatwg-mimetype": "^4.0.0",
|
||||
"whatwg-url": "^14.1.1",
|
||||
"ws": "^8.18.0",
|
||||
"xml-name-validator": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"canvas": "^3.0.0"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"canvas": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/json-buffer": {
|
||||
"version": "3.0.1",
|
||||
"resolved": "https://registry.npmjs.org/json-buffer/-/json-buffer-3.0.1.tgz",
|
||||
|
|
@ -2552,6 +2825,12 @@
|
|||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/lru-cache": {
|
||||
"version": "10.4.3",
|
||||
"resolved": "https://registry.npmjs.org/lru-cache/-/lru-cache-10.4.3.tgz",
|
||||
"integrity": "sha512-JNAzZcXrCt42VGLuYz0zfAzDfAvJWW6AfYlDBQyDV5DClI2m5sAmK+OIO7s59XfsRsWHp02jAJrRadPRGTt6SQ==",
|
||||
"license": "ISC"
|
||||
},
|
||||
"node_modules/math-intrinsics": {
|
||||
"version": "1.1.0",
|
||||
"resolved": "https://registry.npmjs.org/math-intrinsics/-/math-intrinsics-1.1.0.tgz",
|
||||
|
|
@ -2616,7 +2895,6 @@
|
|||
"version": "2.1.3",
|
||||
"resolved": "https://registry.npmjs.org/ms/-/ms-2.1.3.tgz",
|
||||
"integrity": "sha512-6FlzubTLZG3J2a/NVCAleEhjzq5oxgHyaCU9yYXvcLsvoVaHJq/s5xXI6/XXP6tz7R9xAOtHnSO/tXtF3WRTlA==",
|
||||
"dev": true,
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/natural-compare": {
|
||||
|
|
@ -2627,6 +2905,12 @@
|
|||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/nwsapi": {
|
||||
"version": "2.2.20",
|
||||
"resolved": "https://registry.npmjs.org/nwsapi/-/nwsapi-2.2.20.tgz",
|
||||
"integrity": "sha512-/ieB+mDe4MrrKMT8z+mQL8klXydZWGR5Dowt4RAGKbJ3kIGEx3X4ljUo+6V73IXtUPWgfOlU5B9MlGxFO5T+cA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/object-inspect": {
|
||||
"version": "1.13.4",
|
||||
"resolved": "https://registry.npmjs.org/object-inspect/-/object-inspect-1.13.4.tgz",
|
||||
|
|
@ -2820,6 +3104,18 @@
|
|||
"node": ">=6"
|
||||
}
|
||||
},
|
||||
"node_modules/parse5": {
|
||||
"version": "7.3.0",
|
||||
"resolved": "https://registry.npmjs.org/parse5/-/parse5-7.3.0.tgz",
|
||||
"integrity": "sha512-IInvU7fabl34qmi9gY8XOVxhYyMyuH2xUNpb2q8/Y+7552KlejkRvqvD19nMoUW/uQGGbqNpA6Tufu5FL5BZgw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"entities": "^6.0.0"
|
||||
},
|
||||
"funding": {
|
||||
"url": "https://github.com/inikulin/parse5?sponsor=1"
|
||||
}
|
||||
},
|
||||
"node_modules/path-exists": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/path-exists/-/path-exists-4.0.0.tgz",
|
||||
|
|
@ -3003,9 +3299,7 @@
|
|||
"version": "2.3.1",
|
||||
"resolved": "https://registry.npmjs.org/punycode/-/punycode-2.3.1.tgz",
|
||||
"integrity": "sha512-vYt7UD1U9Wg6138shLtLOvdAu+8DsC/ilFtEVHcH+wydcSpNE20AfSOduf6MkRFahL5FY7X1oU7nKVZFtfq8Fg==",
|
||||
"dev": true,
|
||||
"license": "MIT",
|
||||
"peer": true,
|
||||
"engines": {
|
||||
"node": ">=6"
|
||||
}
|
||||
|
|
@ -3146,6 +3440,12 @@
|
|||
"url": "https://github.com/sponsors/isaacs"
|
||||
}
|
||||
},
|
||||
"node_modules/rrweb-cssom": {
|
||||
"version": "0.8.0",
|
||||
"resolved": "https://registry.npmjs.org/rrweb-cssom/-/rrweb-cssom-0.8.0.tgz",
|
||||
"integrity": "sha512-guoltQEx+9aMf2gDZ0s62EcV8lsXR+0w8915TC3ITdn2YueuNjdAYh/levpU9nFaoChh9RUS5ZdQMrKfVEN9tw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/run-parallel": {
|
||||
"version": "1.2.0",
|
||||
"resolved": "https://registry.npmjs.org/run-parallel/-/run-parallel-1.2.0.tgz",
|
||||
|
|
@ -3235,6 +3535,24 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/safer-buffer": {
|
||||
"version": "2.1.2",
|
||||
"resolved": "https://registry.npmjs.org/safer-buffer/-/safer-buffer-2.1.2.tgz",
|
||||
"integrity": "sha512-YZo3K82SD7Riyi0E1EQPojLz7kpepnSQI9IyPbHHg1XXXevb5dJI7tpyN2ADxGcQbHG7vcyRHk0cbwqcQriUtg==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/saxes": {
|
||||
"version": "6.0.0",
|
||||
"resolved": "https://registry.npmjs.org/saxes/-/saxes-6.0.0.tgz",
|
||||
"integrity": "sha512-xAg7SOnEhrm5zI3puOOKyy1OMcMlIJZYNJY7xLBwSze0UjhPLnWfj2GF2EpT0jmzaJKIWKHLsaSSajf35bcYnA==",
|
||||
"license": "ISC",
|
||||
"dependencies": {
|
||||
"xmlchars": "^2.2.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=v12.22.7"
|
||||
}
|
||||
},
|
||||
"node_modules/semver": {
|
||||
"version": "7.7.2",
|
||||
"resolved": "https://registry.npmjs.org/semver/-/semver-7.7.2.tgz",
|
||||
|
|
@ -3575,6 +3893,12 @@
|
|||
"url": "https://github.com/sponsors/ljharb"
|
||||
}
|
||||
},
|
||||
"node_modules/symbol-tree": {
|
||||
"version": "3.2.4",
|
||||
"resolved": "https://registry.npmjs.org/symbol-tree/-/symbol-tree-3.2.4.tgz",
|
||||
"integrity": "sha512-9QNk5KwDF+Bvz+PyObkmSYjI5ksVUYtjW7AU22r2NKcfLJcXp96hkDWU3+XndOsUb+AQ9QhfzfCT2O+CNWT5Tw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/text-table": {
|
||||
"version": "0.2.0",
|
||||
"resolved": "https://registry.npmjs.org/text-table/-/text-table-0.2.0.tgz",
|
||||
|
|
@ -3583,6 +3907,24 @@
|
|||
"license": "MIT",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/tldts": {
|
||||
"version": "6.1.86",
|
||||
"resolved": "https://registry.npmjs.org/tldts/-/tldts-6.1.86.tgz",
|
||||
"integrity": "sha512-WMi/OQ2axVTf/ykqCQgXiIct+mSQDFdH2fkwhPwgEwvJ1kSzZRiinb0zF2Xb8u4+OqPChmyI6MEu4EezNJz+FQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tldts-core": "^6.1.86"
|
||||
},
|
||||
"bin": {
|
||||
"tldts": "bin/cli.js"
|
||||
}
|
||||
},
|
||||
"node_modules/tldts-core": {
|
||||
"version": "6.1.86",
|
||||
"resolved": "https://registry.npmjs.org/tldts-core/-/tldts-core-6.1.86.tgz",
|
||||
"integrity": "sha512-Je6p7pkk+KMzMv2XXKmAE3McmolOQFdxkKw0R8EYNr7sELW46JqnNeTX8ybPiQgvg1ymCoF8LXs5fzFaZvJPTA==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/to-regex-range": {
|
||||
"version": "5.0.1",
|
||||
"resolved": "https://registry.npmjs.org/to-regex-range/-/to-regex-range-5.0.1.tgz",
|
||||
|
|
@ -3596,6 +3938,30 @@
|
|||
"node": ">=8.0"
|
||||
}
|
||||
},
|
||||
"node_modules/tough-cookie": {
|
||||
"version": "5.1.2",
|
||||
"resolved": "https://registry.npmjs.org/tough-cookie/-/tough-cookie-5.1.2.tgz",
|
||||
"integrity": "sha512-FVDYdxtnj0G6Qm/DhNPSb8Ju59ULcup3tuJxkFb5K8Bv2pUXILbf0xZWU8PX8Ov19OXljbUyveOFwRMwkXzO+A==",
|
||||
"license": "BSD-3-Clause",
|
||||
"dependencies": {
|
||||
"tldts": "^6.1.32"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=16"
|
||||
}
|
||||
},
|
||||
"node_modules/tr46": {
|
||||
"version": "5.1.1",
|
||||
"resolved": "https://registry.npmjs.org/tr46/-/tr46-5.1.1.tgz",
|
||||
"integrity": "sha512-hdF5ZgjTqgAntKkklYw0R03MG2x/bSzTtkxmIRw/sTNV8YXsCJ1tfLAX23lhxhHJlEf3CRCOCGGWw3vI3GaSPw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"punycode": "^2.3.1"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/tree-kill": {
|
||||
"version": "1.2.2",
|
||||
"resolved": "https://registry.npmjs.org/tree-kill/-/tree-kill-1.2.2.tgz",
|
||||
|
|
@ -3789,6 +4155,61 @@
|
|||
"punycode": "^2.1.0"
|
||||
}
|
||||
},
|
||||
"node_modules/w3c-xmlserializer": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/w3c-xmlserializer/-/w3c-xmlserializer-5.0.0.tgz",
|
||||
"integrity": "sha512-o8qghlI8NZHU1lLPrpi2+Uq7abh4GGPpYANlalzWxyWteJOCsr/P+oPBA49TOLu5FTZO4d3F9MnWJfiMo4BkmA==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"xml-name-validator": "^5.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/webidl-conversions": {
|
||||
"version": "7.0.0",
|
||||
"resolved": "https://registry.npmjs.org/webidl-conversions/-/webidl-conversions-7.0.0.tgz",
|
||||
"integrity": "sha512-VwddBukDzu71offAQR975unBIGqfKZpM+8ZX6ySk8nYhVoo5CYaZyzt3YBvYtRtO+aoGlqxPg/B87NGVZ/fu6g==",
|
||||
"license": "BSD-2-Clause",
|
||||
"engines": {
|
||||
"node": ">=12"
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-encoding": {
|
||||
"version": "3.1.1",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-encoding/-/whatwg-encoding-3.1.1.tgz",
|
||||
"integrity": "sha512-6qN4hJdMwfYBtE3YBTTHhoeuUrDBPZmbQaxWAqSALV/MeEnR5z1xd8UKud2RAkFoPkmB+hli1TZSnyi84xz1vQ==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"iconv-lite": "0.6.3"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-mimetype": {
|
||||
"version": "4.0.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-mimetype/-/whatwg-mimetype-4.0.0.tgz",
|
||||
"integrity": "sha512-QaKxh0eNIi2mE9p2vEdzfagOKHCcj1pJ56EEHGQOVxp8r9/iszLUUV7v89x9O1p/T+NlTM5W7jW6+cz4Fq1YVg==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/whatwg-url": {
|
||||
"version": "14.2.0",
|
||||
"resolved": "https://registry.npmjs.org/whatwg-url/-/whatwg-url-14.2.0.tgz",
|
||||
"integrity": "sha512-De72GdQZzNTUBBChsXueQUnPKDkg/5A5zp7pFDuQAj5UFoENpiACU0wlCvzpAGnTkj++ihpKwKyYewn/XNUbKw==",
|
||||
"license": "MIT",
|
||||
"dependencies": {
|
||||
"tr46": "^5.1.0",
|
||||
"webidl-conversions": "^7.0.0"
|
||||
},
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/which": {
|
||||
"version": "2.0.2",
|
||||
"resolved": "https://registry.npmjs.org/which/-/which-2.0.2.tgz",
|
||||
|
|
@ -3932,6 +4353,42 @@
|
|||
"license": "ISC",
|
||||
"peer": true
|
||||
},
|
||||
"node_modules/ws": {
|
||||
"version": "8.18.2",
|
||||
"resolved": "https://registry.npmjs.org/ws/-/ws-8.18.2.tgz",
|
||||
"integrity": "sha512-DMricUmwGZUVr++AEAe2uiVM7UoO9MAVZMDu05UQOaUII0lp+zOzLLU4Xqh/JvTqklB1T4uELaaPBKyjE1r4fQ==",
|
||||
"license": "MIT",
|
||||
"engines": {
|
||||
"node": ">=10.0.0"
|
||||
},
|
||||
"peerDependencies": {
|
||||
"bufferutil": "^4.0.1",
|
||||
"utf-8-validate": ">=5.0.2"
|
||||
},
|
||||
"peerDependenciesMeta": {
|
||||
"bufferutil": {
|
||||
"optional": true
|
||||
},
|
||||
"utf-8-validate": {
|
||||
"optional": true
|
||||
}
|
||||
}
|
||||
},
|
||||
"node_modules/xml-name-validator": {
|
||||
"version": "5.0.0",
|
||||
"resolved": "https://registry.npmjs.org/xml-name-validator/-/xml-name-validator-5.0.0.tgz",
|
||||
"integrity": "sha512-EvGK8EJ3DhaHfbRlETOWAS5pO9MZITeauHKJyb8wyajUfQUenkIg2MvLDTZ4T/TgIcm3HU0TFBgWWboAZ30UHg==",
|
||||
"license": "Apache-2.0",
|
||||
"engines": {
|
||||
"node": ">=18"
|
||||
}
|
||||
},
|
||||
"node_modules/xmlchars": {
|
||||
"version": "2.2.0",
|
||||
"resolved": "https://registry.npmjs.org/xmlchars/-/xmlchars-2.2.0.tgz",
|
||||
"integrity": "sha512-JZnDKK8B0RCDw84FNdDAIpZK+JuJw+s7Lz8nksI7SIuU3UXJJslUthsi+uWBUYOwPFwW7W7PRLRfUKpxjtjFCw==",
|
||||
"license": "MIT"
|
||||
},
|
||||
"node_modules/y18n": {
|
||||
"version": "5.0.8",
|
||||
"resolved": "https://registry.npmjs.org/y18n/-/y18n-5.0.8.tgz",
|
||||
|
|
|
|||
|
|
@ -15,5 +15,8 @@
|
|||
"prettier": "^3.3.3",
|
||||
"prettier-plugin-tailwindcss": "^0.6.8",
|
||||
"typescript": "^5.6.3"
|
||||
},
|
||||
"dependencies": {
|
||||
"jsdom": "^26.1.0"
|
||||
}
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,6 +1,6 @@
|
|||
{
|
||||
"name": "@continuedev/fetch",
|
||||
"version": "1.0.13",
|
||||
"version": "1.0.14",
|
||||
"description": "",
|
||||
"main": "dist/index.js",
|
||||
"types": "dist/index.d.ts",
|
||||
|
|
|
|||
187
packages/fetch/src/certs.test.ts
Normal file
187
packages/fetch/src/certs.test.ts
Normal file
|
|
@ -0,0 +1,187 @@
|
|||
import * as fs from "node:fs";
|
||||
import { beforeEach, expect, test, vi } from "vitest";
|
||||
import { CertsCache, getCertificateContent } from "./certs.js";
|
||||
|
||||
// Mock fs module
|
||||
vi.mock("node:fs", () => ({
|
||||
readFileSync: vi.fn(),
|
||||
}));
|
||||
|
||||
const mockReadFileSync = vi.mocked(fs.readFileSync);
|
||||
|
||||
beforeEach(() => {
|
||||
vi.clearAllMocks();
|
||||
});
|
||||
|
||||
test("getCertificateContent should decode base64 data URI correctly", () => {
|
||||
const testCert =
|
||||
"-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----";
|
||||
const base64Data = Buffer.from(testCert, "utf8").toString("base64");
|
||||
const dataUri = `data:application/x-pem-file;base64,${base64Data}`;
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
|
||||
expect(result).toBe(testCert);
|
||||
});
|
||||
|
||||
test("getCertificateContent should decode URL-encoded data URI correctly", () => {
|
||||
const testCert =
|
||||
"-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----";
|
||||
const encodedData = encodeURIComponent(testCert);
|
||||
const dataUri = `data:text/plain,${encodedData}`;
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
|
||||
expect(result).toBe(testCert);
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle plain text data URI correctly", () => {
|
||||
const testCert = "simple-cert-content";
|
||||
const dataUri = `data:text/plain,${testCert}`;
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
|
||||
expect(result).toBe(testCert);
|
||||
});
|
||||
|
||||
test("getCertificateContent should read file when input is a file path", () => {
|
||||
const filePath = "/path/to/cert.pem";
|
||||
const expectedContent =
|
||||
"-----BEGIN CERTIFICATE-----\nfile content\n-----END CERTIFICATE-----";
|
||||
|
||||
mockReadFileSync.mockReturnValue(expectedContent);
|
||||
|
||||
const result = getCertificateContent(filePath);
|
||||
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8");
|
||||
expect(result).toBe(expectedContent);
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle data URI with different media types", () => {
|
||||
const testData = "certificate-data";
|
||||
const base64Data = Buffer.from(testData, "utf8").toString("base64");
|
||||
const dataUri = `data:application/x-x509-ca-cert;base64,${base64Data}`;
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
|
||||
expect(result).toBe(testData);
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle data URI without media type", () => {
|
||||
const testData = "simple-data";
|
||||
const base64Data = Buffer.from(testData, "utf8").toString("base64");
|
||||
const dataUri = `data:;base64,${base64Data}`;
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
|
||||
expect(result).toBe(testData);
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle data URI without media type or encoding", () => {
|
||||
const testData = "simple-data";
|
||||
const base64Data = Buffer.from(testData, "utf8").toString("base64");
|
||||
const dataUri = `data:;base64,${base64Data}`;
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
|
||||
expect(result).toBe(testData);
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle relative file paths", () => {
|
||||
const filePath = "./certs/ca.pem";
|
||||
const expectedContent = "certificate from relative path";
|
||||
|
||||
mockReadFileSync.mockReturnValue(expectedContent);
|
||||
|
||||
const result = getCertificateContent(filePath);
|
||||
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8");
|
||||
expect(result).toBe(expectedContent);
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle data URI with special characters in URL encoding", () => {
|
||||
const testCert = "cert with spaces and special chars: !@#$%";
|
||||
const encodedData = encodeURIComponent(testCert);
|
||||
const dataUri = `data:text/plain,${encodedData}`;
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
|
||||
expect(result).toBe(testCert);
|
||||
});
|
||||
|
||||
test("CertsCache.getCachedCustomCert should cache and return certificate content", async () => {
|
||||
const certsCache = CertsCache.getInstance();
|
||||
const filePath = "/path/to/custom/cert.pem";
|
||||
const expectedContent = "custom cert content";
|
||||
|
||||
mockReadFileSync.mockReturnValue(expectedContent);
|
||||
|
||||
const cert1 = await certsCache.getCachedCustomCert(filePath);
|
||||
expect(cert1).toBe(expectedContent);
|
||||
expect(mockReadFileSync).toHaveBeenCalledTimes(1);
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8");
|
||||
|
||||
// Call again to check if it's cached
|
||||
const cert2 = await certsCache.getCachedCustomCert(filePath);
|
||||
expect(cert2).toBe(expectedContent);
|
||||
// readFileSync should not be called again
|
||||
expect(mockReadFileSync).toHaveBeenCalledTimes(1);
|
||||
});
|
||||
|
||||
test("CertsCache.getAllCachedCustomCerts should return all cached custom certs", async () => {
|
||||
const certsCache = CertsCache.getInstance();
|
||||
const filePaths = ["/path/to/cert1.pem", "/path/to/cert2.pem"];
|
||||
const expectedContent1 = "content of cert1";
|
||||
const expectedContent2 = "content of cert2";
|
||||
|
||||
mockReadFileSync.mockReturnValueOnce(expectedContent1);
|
||||
mockReadFileSync.mockReturnValueOnce(expectedContent2);
|
||||
|
||||
const certs = await certsCache.getAllCachedCustomCerts(filePaths);
|
||||
expect(certs).toEqual([expectedContent1, expectedContent2]);
|
||||
expect(mockReadFileSync).toHaveBeenCalledTimes(2);
|
||||
});
|
||||
|
||||
test("CertsCache.getCa should return combined CA when caBundlePath is provided", async () => {
|
||||
const certsCache = CertsCache.getInstance();
|
||||
const fixedCa = ["fixed CA cert"];
|
||||
const customCertPath = "/path/to/custom/cert.pem";
|
||||
const customCertContent = "custom cert content";
|
||||
|
||||
// Directly set _fixedCa to avoid initializing it with real data
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
certsCache._fixedCa = fixedCa;
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
certsCache._initialized = true;
|
||||
mockReadFileSync.mockReturnValue(customCertContent);
|
||||
|
||||
const ca = await certsCache.getCa(customCertPath);
|
||||
expect(ca).toEqual([...fixedCa, customCertContent]);
|
||||
});
|
||||
|
||||
test("CertsCache.clear should clear custom certs and reset initialized flag", () => {
|
||||
const certsCache = CertsCache.getInstance();
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
certsCache._customCerts.set("key", "value");
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
certsCache._initialized = true;
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
certsCache._fixedCa = ["test"];
|
||||
|
||||
certsCache.clear();
|
||||
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
expect(certsCache._customCerts.size).toBe(0);
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
expect(certsCache._initialized).toBe(false);
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore
|
||||
expect(certsCache._fixedCa).toEqual([]);
|
||||
});
|
||||
129
packages/fetch/src/certs.ts
Normal file
129
packages/fetch/src/certs.ts
Normal file
|
|
@ -0,0 +1,129 @@
|
|||
import { globalAgent } from "https";
|
||||
import * as fs from "node:fs";
|
||||
import tls from "node:tls";
|
||||
|
||||
/**
|
||||
* Extracts content from either a file path or data URI
|
||||
*/
|
||||
export function getCertificateContent(input: string): string {
|
||||
if (input.startsWith("data:")) {
|
||||
// Parse data URI: data:[<mediatype>][;base64],<data>
|
||||
const [header, data] = input.split(",");
|
||||
if (header.includes("base64")) {
|
||||
return Buffer.from(data, "base64").toString("utf8");
|
||||
} else {
|
||||
return decodeURIComponent(data);
|
||||
}
|
||||
} else {
|
||||
// Assume it's a file path
|
||||
return fs.readFileSync(input, "utf8");
|
||||
}
|
||||
}
|
||||
|
||||
export class CertsCache {
|
||||
private static instance: CertsCache;
|
||||
private _fixedCa: string[] = [];
|
||||
private _initialized: boolean = false;
|
||||
private _customCerts: Map<string, string> = new Map();
|
||||
|
||||
private constructor() {}
|
||||
|
||||
public static getInstance(): CertsCache {
|
||||
if (!CertsCache.instance) {
|
||||
CertsCache.instance = new CertsCache();
|
||||
}
|
||||
return CertsCache.instance;
|
||||
}
|
||||
|
||||
get fixedCa(): string[] {
|
||||
if (this._initialized) {
|
||||
return this._fixedCa;
|
||||
}
|
||||
|
||||
const globalCerts: string[] = [];
|
||||
if (Boolean(process.env.IS_BINARY)) {
|
||||
if (Array.isArray(globalAgent.options.ca)) {
|
||||
globalCerts.push(
|
||||
...globalAgent.options.ca.map((cert) => cert.toString()),
|
||||
);
|
||||
} else if (typeof globalAgent.options.ca !== "undefined") {
|
||||
globalCerts.push(globalAgent.options.ca.toString());
|
||||
}
|
||||
}
|
||||
|
||||
const extraCerts: string[] = [];
|
||||
if (process.env.NODE_EXTRA_CA_CERTS) {
|
||||
try {
|
||||
const content = fs.readFileSync(
|
||||
process.env.NODE_EXTRA_CA_CERTS,
|
||||
"utf8",
|
||||
);
|
||||
extraCerts.push(content);
|
||||
} catch (error) {
|
||||
if (process.env.VERBOSE_FETCH) {
|
||||
console.error(
|
||||
`Error reading NODE_EXTRA_CA_CERTS file: ${process.env.NODE_EXTRA_CA_CERTS}`,
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
this._fixedCa = Array.from(
|
||||
new Set([...tls.rootCertificates, ...globalCerts, ...extraCerts]),
|
||||
);
|
||||
this._initialized = true;
|
||||
return this._fixedCa;
|
||||
}
|
||||
|
||||
async getCachedCustomCert(path: string): Promise<string | undefined> {
|
||||
if (this._customCerts.has(path)) {
|
||||
return this._customCerts.get(path);
|
||||
}
|
||||
const certContent = getCertificateContent(path);
|
||||
this._customCerts.set(path, certContent);
|
||||
return certContent;
|
||||
}
|
||||
|
||||
async getAllCachedCustomCerts(
|
||||
caBundlePath: string[] | string,
|
||||
): Promise<string[]> {
|
||||
const paths = Array.isArray(caBundlePath) ? caBundlePath : [caBundlePath];
|
||||
const certs: string[] = [];
|
||||
await Promise.all(
|
||||
paths.map(async (path) => {
|
||||
try {
|
||||
const certContent = await this.getCachedCustomCert(path);
|
||||
if (certContent) {
|
||||
certs.push(certContent);
|
||||
} else if (process.env.VERBOSE_FETCH) {
|
||||
console.warn(`Empty certificate found at ${path}`);
|
||||
}
|
||||
} catch (error) {
|
||||
if (process.env.VERBOSE_FETCH) {
|
||||
console.error(
|
||||
`Error loading custom certificate from ${path}:`,
|
||||
error,
|
||||
);
|
||||
}
|
||||
}
|
||||
}),
|
||||
);
|
||||
return certs;
|
||||
}
|
||||
|
||||
async getCa(caBundlePath: undefined | string | string[]): Promise<string[]> {
|
||||
if (!caBundlePath) {
|
||||
return this.fixedCa;
|
||||
}
|
||||
|
||||
const customCerts = await this.getAllCachedCustomCerts(caBundlePath);
|
||||
return [...this.fixedCa, ...customCerts];
|
||||
}
|
||||
|
||||
async clear(): Promise<void> {
|
||||
this._customCerts.clear();
|
||||
this._initialized = false;
|
||||
this._fixedCa = [];
|
||||
}
|
||||
}
|
||||
|
|
@ -1,173 +0,0 @@
|
|||
import { globalAgent } from "https";
|
||||
import * as fs from "node:fs";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
import { getAgentOptions } from "./getAgentOptions.js";
|
||||
|
||||
// Store original env
|
||||
const originalEnv = process.env;
|
||||
const originalGlobalAgentOptions = { ...globalAgent.options };
|
||||
|
||||
// Temporary directory for test certificate files
|
||||
let tempDir: string;
|
||||
|
||||
beforeEach(() => {
|
||||
// Create a temporary directory for test files
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "fetch-test-"));
|
||||
|
||||
process.env = { ...originalEnv };
|
||||
|
||||
// Reset globalAgent for each test
|
||||
globalAgent.options = { ...originalGlobalAgentOptions };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv;
|
||||
globalAgent.options = originalGlobalAgentOptions;
|
||||
|
||||
// Clean up temporary directory
|
||||
try {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
console.error(`Failed to remove temp directory: ${error}`);
|
||||
}
|
||||
});
|
||||
|
||||
// Helper function to create test certificate files
|
||||
function createTestCertFile(filename: string, content: string): string {
|
||||
const filePath = path.join(tempDir, filename);
|
||||
fs.writeFileSync(filePath, content, "utf8");
|
||||
return filePath;
|
||||
}
|
||||
|
||||
test("getAgentOptions returns basic configuration with default values", () => {
|
||||
const options = getAgentOptions();
|
||||
|
||||
// Check default timeout (7200 seconds = 2 hours = 7,200,000 ms)
|
||||
expect(options.timeout).toBe(7200000);
|
||||
expect(options.sessionTimeout).toBe(7200000);
|
||||
expect(options.keepAliveMsecs).toBe(7200000);
|
||||
expect(options.keepAlive).toBe(true);
|
||||
|
||||
// Verify certificates array exists and contains items
|
||||
expect(options.ca).toBeInstanceOf(Array);
|
||||
expect(options.ca.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify at least one of the real TLS root certificates is included
|
||||
// This assumes there's at least one certificate with "CERTIFICATE" in it
|
||||
expect(options.ca.some((cert: any) => cert.includes("CERTIFICATE"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("getAgentOptions respects custom timeout", () => {
|
||||
const customTimeout = 300; // 5 minutes
|
||||
const options = getAgentOptions({ timeout: customTimeout });
|
||||
|
||||
// Check timeout values (300 seconds = 300,000 ms)
|
||||
expect(options.timeout).toBe(300000);
|
||||
expect(options.sessionTimeout).toBe(300000);
|
||||
expect(options.keepAliveMsecs).toBe(300000);
|
||||
});
|
||||
|
||||
test("getAgentOptions uses verifySsl setting", () => {
|
||||
// With verifySsl true
|
||||
let options = getAgentOptions({ verifySsl: true });
|
||||
expect(options.rejectUnauthorized).toBe(true);
|
||||
|
||||
// With verifySsl false
|
||||
options = getAgentOptions({ verifySsl: false });
|
||||
expect(options.rejectUnauthorized).toBe(false);
|
||||
});
|
||||
|
||||
test("getAgentOptions incorporates custom CA bundle paths", () => {
|
||||
// Create a test CA bundle file
|
||||
const caBundleContent =
|
||||
"-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIJAMcuSp7chAYdMA==\n-----END CERTIFICATE-----";
|
||||
const caBundlePath = createTestCertFile("ca-bundle.pem", caBundleContent);
|
||||
|
||||
// Single string path
|
||||
let options = getAgentOptions({ caBundlePath });
|
||||
|
||||
// Verify that our test certificate is included in the CA list
|
||||
expect(options.ca).toContain(caBundleContent);
|
||||
|
||||
// Create multiple test CA bundle files
|
||||
const caContent1 =
|
||||
"-----BEGIN CERTIFICATE-----\nABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n-----END CERTIFICATE-----";
|
||||
const caContent2 =
|
||||
"-----BEGIN CERTIFICATE-----\n0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n-----END CERTIFICATE-----";
|
||||
const caPath1 = createTestCertFile("ca1.pem", caContent1);
|
||||
const caPath2 = createTestCertFile("ca2.pem", caContent2);
|
||||
|
||||
// Array of paths
|
||||
options = getAgentOptions({
|
||||
caBundlePath: [caPath1, caPath2],
|
||||
});
|
||||
|
||||
// Verify that both test certificates are included in the CA list
|
||||
expect(options.ca).toContain(caContent1);
|
||||
expect(options.ca).toContain(caContent2);
|
||||
});
|
||||
|
||||
test("getAgentOptions includes global certs when running as binary", () => {
|
||||
// Set up test certs in globalAgent
|
||||
globalAgent.options.ca = ["global-cert-1", "global-cert-2"];
|
||||
|
||||
// Set IS_BINARY environment variable
|
||||
process.env.IS_BINARY = "true";
|
||||
|
||||
const options = getAgentOptions();
|
||||
|
||||
// Test for global certs
|
||||
expect(options.ca).toContain("global-cert-1");
|
||||
expect(options.ca).toContain("global-cert-2");
|
||||
});
|
||||
|
||||
test("getAgentOptions handles client certificate configuration", () => {
|
||||
// Create test certificate files
|
||||
const clientCertContent =
|
||||
"-----BEGIN CERTIFICATE-----\nCLIENTCERT\n-----END CERTIFICATE-----";
|
||||
const clientKeyContent =
|
||||
"-----BEGIN PRIVATE KEY-----\nCLIENTKEY\n-----END PRIVATE KEY-----";
|
||||
const certPath = createTestCertFile("client.cert", clientCertContent);
|
||||
const keyPath = createTestCertFile("client.key", clientKeyContent);
|
||||
|
||||
const clientCertOptions = {
|
||||
clientCertificate: {
|
||||
cert: certPath,
|
||||
key: keyPath,
|
||||
passphrase: "secret-passphrase",
|
||||
},
|
||||
};
|
||||
|
||||
const options = getAgentOptions(clientCertOptions);
|
||||
|
||||
expect(options.cert).toBe(clientCertContent);
|
||||
expect(options.key).toBe(clientKeyContent);
|
||||
expect(options.passphrase).toBe("secret-passphrase");
|
||||
});
|
||||
|
||||
test("getAgentOptions handles client certificate without passphrase", () => {
|
||||
// Create test certificate files
|
||||
const clientCertContent =
|
||||
"-----BEGIN CERTIFICATE-----\nCLIENTCERT2\n-----END CERTIFICATE-----";
|
||||
const clientKeyContent =
|
||||
"-----BEGIN PRIVATE KEY-----\nCLIENTKEY2\n-----END PRIVATE KEY-----";
|
||||
const certPath = createTestCertFile("client2.cert", clientCertContent);
|
||||
const keyPath = createTestCertFile("client2.key", clientKeyContent);
|
||||
|
||||
const clientCertOptions = {
|
||||
clientCertificate: {
|
||||
cert: certPath,
|
||||
key: keyPath,
|
||||
},
|
||||
};
|
||||
|
||||
const options = getAgentOptions(clientCertOptions);
|
||||
|
||||
expect(options.cert).toBe(clientCertContent);
|
||||
expect(options.key).toBe(clientKeyContent);
|
||||
expect(options.passphrase).toBeUndefined();
|
||||
});
|
||||
|
|
@ -5,7 +5,7 @@ import { HttpsProxyAgent } from "https-proxy-agent";
|
|||
import { BodyInit, RequestInit, Response } from "node-fetch";
|
||||
import { getAgentOptions } from "./getAgentOptions.js";
|
||||
import fetch from "./node-fetch-patch.js";
|
||||
import { getProxyFromEnv, shouldBypassProxy } from "./util.js";
|
||||
import { getProxy, shouldBypassProxy } from "./util.js";
|
||||
|
||||
const { http, https } = (followRedirects as any).default;
|
||||
|
||||
|
|
@ -89,18 +89,13 @@ export async function fetchwithRequestOptions(
|
|||
url.host = "127.0.0.1";
|
||||
}
|
||||
|
||||
const agentOptions = getAgentOptions(requestOptions);
|
||||
const agentOptions = await getAgentOptions(requestOptions);
|
||||
|
||||
// Get proxy from options or environment variables
|
||||
let proxy = requestOptions?.proxy;
|
||||
if (!proxy) {
|
||||
proxy = getProxyFromEnv(url.protocol);
|
||||
}
|
||||
const proxy = getProxy(url.protocol, requestOptions);
|
||||
|
||||
// Check if should bypass proxy based on requestOptions or NO_PROXY env var
|
||||
const shouldBypass =
|
||||
requestOptions?.noProxy?.includes(url.hostname) ||
|
||||
shouldBypassProxy(url.hostname);
|
||||
const shouldBypass = shouldBypassProxy(url.hostname, requestOptions);
|
||||
|
||||
// Create agent
|
||||
const protocol = url.protocol === "https:" ? https : http;
|
||||
|
|
|
|||
|
|
@ -1,122 +1,189 @@
|
|||
import { globalAgent } from "https";
|
||||
import * as fs from "node:fs";
|
||||
import { expect, test, vi } from "vitest";
|
||||
import * as os from "node:os";
|
||||
import * as path from "node:path";
|
||||
import { afterEach, beforeEach, expect, test } from "vitest";
|
||||
import { CertsCache } from "./certs.js";
|
||||
import { getAgentOptions } from "./getAgentOptions.js";
|
||||
|
||||
// Mock fs module
|
||||
vi.mock("node:fs", () => ({
|
||||
readFileSync: vi.fn(),
|
||||
}));
|
||||
// Store original env
|
||||
const originalEnv = process.env;
|
||||
const originalGlobalAgentOptions = { ...globalAgent.options };
|
||||
|
||||
const mockReadFileSync = vi.mocked(fs.readFileSync);
|
||||
// Temporary directory for test certificate files
|
||||
let tempDir: string;
|
||||
|
||||
// We need to access the private getCertificateContent function for testing
|
||||
// Since it's not exported, we'll test it indirectly through scenarios or mock the module
|
||||
const getCertificateContent = (input: string): string => {
|
||||
if (input.startsWith("data:")) {
|
||||
// Parse data URI: data:[<mediatype>][;base64],<data>
|
||||
const [header, data] = input.split(",");
|
||||
if (header.includes("base64")) {
|
||||
return Buffer.from(data, "base64").toString("utf8");
|
||||
} else {
|
||||
return decodeURIComponent(data);
|
||||
}
|
||||
} else {
|
||||
// Assume it's a file path
|
||||
return fs.readFileSync(input, "utf8");
|
||||
beforeEach(() => {
|
||||
// Create a temporary directory for test files
|
||||
tempDir = fs.mkdtempSync(path.join(os.tmpdir(), "fetch-test-"));
|
||||
|
||||
process.env = { ...originalEnv };
|
||||
|
||||
// Reset globalAgent for each test
|
||||
globalAgent.options = { ...originalGlobalAgentOptions };
|
||||
});
|
||||
|
||||
afterEach(() => {
|
||||
process.env = originalEnv;
|
||||
globalAgent.options = originalGlobalAgentOptions;
|
||||
|
||||
CertsCache.getInstance().clear();
|
||||
|
||||
// Clean up temporary directory
|
||||
try {
|
||||
fs.rmSync(tempDir, { recursive: true, force: true });
|
||||
} catch (error) {
|
||||
console.error(`Failed to remove temp directory: ${error}`);
|
||||
}
|
||||
};
|
||||
|
||||
test("getCertificateContent should decode base64 data URI correctly", () => {
|
||||
const testCert =
|
||||
"-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----";
|
||||
const base64Data = Buffer.from(testCert, "utf8").toString("base64");
|
||||
const dataUri = `data:application/x-pem-file;base64,${base64Data}`;
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
|
||||
expect(result).toBe(testCert);
|
||||
});
|
||||
|
||||
test("getCertificateContent should decode URL-encoded data URI correctly", () => {
|
||||
const testCert =
|
||||
"-----BEGIN CERTIFICATE-----\nMIIC...\n-----END CERTIFICATE-----";
|
||||
const encodedData = encodeURIComponent(testCert);
|
||||
const dataUri = `data:text/plain,${encodedData}`;
|
||||
// Helper function to create test certificate files
|
||||
function createTestCertFile(filename: string, content: string): string {
|
||||
const filePath = path.join(tempDir, filename);
|
||||
fs.writeFileSync(filePath, content, "utf8");
|
||||
return filePath;
|
||||
}
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
test("getAgentOptions returns basic configuration with default values", async () => {
|
||||
const options = await getAgentOptions();
|
||||
|
||||
expect(result).toBe(testCert);
|
||||
// Check default timeout (7200 seconds = 2 hours = 7,200,000 ms)
|
||||
expect(options.timeout).toBe(7200000);
|
||||
expect(options.sessionTimeout).toBe(7200000);
|
||||
expect(options.keepAliveMsecs).toBe(7200000);
|
||||
expect(options.keepAlive).toBe(true);
|
||||
|
||||
// Verify certificates array exists and contains items
|
||||
expect(options.ca).toBeInstanceOf(Array);
|
||||
expect(options.ca.length).toBeGreaterThan(0);
|
||||
|
||||
// Verify at least one of the real TLS root certificates is included
|
||||
// This assumes there's at least one certificate with "CERTIFICATE" in it
|
||||
expect(options.ca.some((cert: any) => cert.includes("CERTIFICATE"))).toBe(
|
||||
true,
|
||||
);
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle plain text data URI correctly", () => {
|
||||
const testCert = "simple-cert-content";
|
||||
const dataUri = `data:text/plain,${testCert}`;
|
||||
test("getAgentOptions respects custom timeout", async () => {
|
||||
const customTimeout = 300; // 5 minutes
|
||||
const options = await getAgentOptions({ timeout: customTimeout });
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
|
||||
expect(result).toBe(testCert);
|
||||
// Check timeout values (300 seconds = 300,000 ms)
|
||||
expect(options.timeout).toBe(300000);
|
||||
expect(options.sessionTimeout).toBe(300000);
|
||||
expect(options.keepAliveMsecs).toBe(300000);
|
||||
});
|
||||
|
||||
test("getCertificateContent should read file when input is a file path", () => {
|
||||
const filePath = "/path/to/cert.pem";
|
||||
const expectedContent =
|
||||
"-----BEGIN CERTIFICATE-----\nfile content\n-----END CERTIFICATE-----";
|
||||
test("getAgentOptions uses verifySsl setting", async () => {
|
||||
// With verifySsl true
|
||||
let options = await getAgentOptions({ verifySsl: true });
|
||||
expect(options.rejectUnauthorized).toBe(true);
|
||||
|
||||
mockReadFileSync.mockReturnValue(expectedContent);
|
||||
|
||||
const result = getCertificateContent(filePath);
|
||||
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8");
|
||||
expect(result).toBe(expectedContent);
|
||||
// With verifySsl false
|
||||
options = await getAgentOptions({ verifySsl: false });
|
||||
expect(options.rejectUnauthorized).toBe(false);
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle data URI with different media types", () => {
|
||||
const testData = "certificate-data";
|
||||
const base64Data = Buffer.from(testData, "utf8").toString("base64");
|
||||
const dataUri = `data:application/x-x509-ca-cert;base64,${base64Data}`;
|
||||
test("getAgentOptions incorporates custom CA bundle paths", async () => {
|
||||
// Create a test CA bundle file
|
||||
const caBundleContent =
|
||||
"-----BEGIN CERTIFICATE-----\nMIIDtTCCAp2gAwIBAgIJAMcuSp7chAYdMA==\n-----END CERTIFICATE-----";
|
||||
const caBundlePath = createTestCertFile("ca-bundle.pem", caBundleContent);
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
// Single string path
|
||||
let options = await getAgentOptions({ caBundlePath });
|
||||
|
||||
expect(result).toBe(testData);
|
||||
// Verify that our test certificate is included in the CA list
|
||||
expect(options.ca).toContain(caBundleContent);
|
||||
|
||||
// Create multiple test CA bundle files
|
||||
const caContent1 =
|
||||
"-----BEGIN CERTIFICATE-----\nABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789\n-----END CERTIFICATE-----";
|
||||
const caContent2 =
|
||||
"-----BEGIN CERTIFICATE-----\n0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ\n-----END CERTIFICATE-----";
|
||||
const caPath1 = createTestCertFile("ca1.pem", caContent1);
|
||||
const caPath2 = createTestCertFile("ca2.pem", caContent2);
|
||||
|
||||
// Array of paths
|
||||
options = await getAgentOptions({
|
||||
caBundlePath: [caPath1, caPath2],
|
||||
});
|
||||
|
||||
// Verify that both test certificates are included in the CA list
|
||||
expect(options.ca).toContain(caContent1);
|
||||
expect(options.ca).toContain(caContent2);
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle data URI without media type", () => {
|
||||
const testData = "simple-data";
|
||||
const base64Data = Buffer.from(testData, "utf8").toString("base64");
|
||||
const dataUri = `data:;base64,${base64Data}`;
|
||||
test("getAgentOptions includes global certs when running as binary", async () => {
|
||||
// Set up test certs in globalAgent
|
||||
globalAgent.options.ca = ["global-cert-1", "global-cert-2"];
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
// Set IS_BINARY environment variable
|
||||
process.env.IS_BINARY = "true";
|
||||
|
||||
expect(result).toBe(testData);
|
||||
const options = await getAgentOptions();
|
||||
|
||||
// Test for global certs
|
||||
expect(options.ca).toContain("global-cert-1");
|
||||
expect(options.ca).toContain("global-cert-2");
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle data URI without media type or encoding", () => {
|
||||
const testData = "simple-data";
|
||||
const base64Data = Buffer.from(testData, "utf8").toString("base64");
|
||||
const dataUri = `data:;base64,${base64Data}`;
|
||||
test("getAgentOptions handles client certificate configuration", async () => {
|
||||
// Create test certificate files
|
||||
const clientCertContent =
|
||||
"-----BEGIN CERTIFICATE-----\nCLIENTCERT\n-----END CERTIFICATE-----";
|
||||
const clientKeyContent =
|
||||
"-----BEGIN PRIVATE KEY-----\nCLIENTKEY\n-----END PRIVATE KEY-----";
|
||||
const certPath = createTestCertFile("client.cert", clientCertContent);
|
||||
const keyPath = createTestCertFile("client.key", clientKeyContent);
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
const clientCertOptions = {
|
||||
clientCertificate: {
|
||||
cert: certPath,
|
||||
key: keyPath,
|
||||
passphrase: "secret-passphrase",
|
||||
},
|
||||
};
|
||||
|
||||
expect(result).toBe(testData);
|
||||
const options = await getAgentOptions(clientCertOptions);
|
||||
|
||||
expect(options.cert).toBe(clientCertContent);
|
||||
expect(options.key).toBe(clientKeyContent);
|
||||
expect(options.passphrase).toBe("secret-passphrase");
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle relative file paths", () => {
|
||||
const filePath = "./certs/ca.pem";
|
||||
const expectedContent = "certificate from relative path";
|
||||
test("getAgentOptions handles client certificate without passphrase", async () => {
|
||||
// Create test certificate files
|
||||
const clientCertContent =
|
||||
"-----BEGIN CERTIFICATE-----\nCLIENTCERT2\n-----END CERTIFICATE-----";
|
||||
const clientKeyContent =
|
||||
"-----BEGIN PRIVATE KEY-----\nCLIENTKEY2\n-----END PRIVATE KEY-----";
|
||||
const certPath = createTestCertFile("client2.cert", clientCertContent);
|
||||
const keyPath = createTestCertFile("client2.key", clientKeyContent);
|
||||
|
||||
mockReadFileSync.mockReturnValue(expectedContent);
|
||||
const clientCertOptions = {
|
||||
clientCertificate: {
|
||||
cert: certPath,
|
||||
key: keyPath,
|
||||
},
|
||||
};
|
||||
|
||||
const result = getCertificateContent(filePath);
|
||||
const options = await getAgentOptions(clientCertOptions);
|
||||
|
||||
expect(mockReadFileSync).toHaveBeenCalledWith(filePath, "utf8");
|
||||
expect(result).toBe(expectedContent);
|
||||
expect(options.cert).toBe(clientCertContent);
|
||||
expect(options.key).toBe(clientKeyContent);
|
||||
expect(options.passphrase).toBeUndefined();
|
||||
});
|
||||
|
||||
test("getCertificateContent should handle data URI with special characters in URL encoding", () => {
|
||||
const testCert = "cert with spaces and special chars: !@#$%";
|
||||
const encodedData = encodeURIComponent(testCert);
|
||||
const dataUri = `data:text/plain,${encodedData}`;
|
||||
test("getAgentOptions reads NODE_EXTRA_CA_CERTS", async () => {
|
||||
const extraCertContent =
|
||||
"-----BEGIN CERTIFICATE-----\nEXTRA_CERT\n-----END CERTIFICATE-----";
|
||||
const certPath = createTestCertFile("extra-cert.cert", extraCertContent);
|
||||
|
||||
const result = getCertificateContent(dataUri);
|
||||
expect(CertsCache.getInstance().fixedCa).not.toContain(extraCertContent);
|
||||
|
||||
expect(result).toBe(testCert);
|
||||
CertsCache.getInstance().clear();
|
||||
|
||||
process.env.NODE_EXTRA_CA_CERTS = certPath;
|
||||
expect(CertsCache.getInstance().fixedCa).toContain(extraCertContent);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,56 +1,19 @@
|
|||
import { globalAgent } from "https";
|
||||
import * as fs from "node:fs";
|
||||
import tls from "node:tls";
|
||||
|
||||
import { RequestOptions } from "@continuedev/config-types";
|
||||
|
||||
/**
|
||||
* Extracts content from either a file path or data URI
|
||||
*/
|
||||
function getCertificateContent(input: string): string {
|
||||
if (input.startsWith("data:")) {
|
||||
// Parse data URI: data:[<mediatype>][;base64],<data>
|
||||
const [header, data] = input.split(",");
|
||||
if (header.includes("base64")) {
|
||||
return Buffer.from(data, "base64").toString("utf8");
|
||||
} else {
|
||||
return decodeURIComponent(data);
|
||||
}
|
||||
} else {
|
||||
// Assume it's a file path
|
||||
return fs.readFileSync(input, "utf8");
|
||||
}
|
||||
}
|
||||
import { CertsCache, getCertificateContent } from "./certs.js";
|
||||
|
||||
/**
|
||||
* Prepares agent options based on request options and certificates
|
||||
*/
|
||||
export function getAgentOptions(requestOptions?: RequestOptions): {
|
||||
export async function getAgentOptions(
|
||||
requestOptions?: RequestOptions,
|
||||
): Promise<{
|
||||
[key: string]: any;
|
||||
} {
|
||||
}> {
|
||||
const TIMEOUT = 7200; // 7200 seconds = 2 hours
|
||||
const timeout = (requestOptions?.timeout ?? TIMEOUT) * 1000; // measured in ms
|
||||
|
||||
// Get root certificates
|
||||
let globalCerts: string[] = [];
|
||||
if (process.env.IS_BINARY) {
|
||||
if (Array.isArray(globalAgent.options.ca)) {
|
||||
globalCerts = [...globalAgent.options.ca.map((cert) => cert.toString())];
|
||||
} else if (typeof globalAgent.options.ca !== "undefined") {
|
||||
globalCerts.push(globalAgent.options.ca.toString());
|
||||
}
|
||||
}
|
||||
|
||||
const ca = Array.from(new Set([...tls.rootCertificates, ...globalCerts]));
|
||||
const customCerts =
|
||||
typeof requestOptions?.caBundlePath === "string"
|
||||
? [requestOptions?.caBundlePath]
|
||||
: requestOptions?.caBundlePath;
|
||||
if (customCerts) {
|
||||
ca.push(
|
||||
...customCerts.map((customCert) => getCertificateContent(customCert)),
|
||||
);
|
||||
}
|
||||
const certsCache = CertsCache.getInstance();
|
||||
const ca = await certsCache.getCa(requestOptions?.caBundlePath);
|
||||
|
||||
const agentOptions: { [key: string]: any } = {
|
||||
ca,
|
||||
|
|
@ -73,5 +36,21 @@ export function getAgentOptions(requestOptions?: RequestOptions): {
|
|||
}
|
||||
}
|
||||
|
||||
if (process.env.VERBOSE_FETCH) {
|
||||
console.log(`Fetch agent options:`);
|
||||
console.log(
|
||||
`\tTimeout (sessionTimeout/keepAliveMsecs): ${agentOptions.timeout}`,
|
||||
);
|
||||
console.log(`\tTotal CA certs: ${ca.length}`);
|
||||
console.log(`\tGlobal/Root CA certs: ${certsCache.fixedCa.length}`);
|
||||
console.log(`\tCustom CA certs: ${ca.length - certsCache.fixedCa.length}`);
|
||||
console.log(
|
||||
`\tClient certificate: ${requestOptions?.clientCertificate ? "Yes" : "No"}`,
|
||||
);
|
||||
console.log(
|
||||
`\trejectUnauthorized/verifySsl: ${agentOptions.rejectUnauthorized ?? "not set (defaults to true)"}`,
|
||||
);
|
||||
}
|
||||
|
||||
return agentOptions;
|
||||
}
|
||||
|
|
|
|||
|
|
@ -1,5 +1,9 @@
|
|||
import { afterEach, expect, test, vi } from "vitest";
|
||||
import { getProxyFromEnv, shouldBypassProxy } from "./util.js";
|
||||
import {
|
||||
getProxyFromEnv,
|
||||
patternMatchesHostname,
|
||||
shouldBypassProxy,
|
||||
} from "./util.js";
|
||||
|
||||
// Reset environment variables after each test
|
||||
afterEach(() => {
|
||||
|
|
@ -52,51 +56,159 @@ test("getProxyFromEnv prefers HTTPS_PROXY over other env vars for https protocol
|
|||
expect(getProxyFromEnv("https:")).toBe("https://preferred.example.com");
|
||||
});
|
||||
|
||||
// Tests for patternMatchesHostname
|
||||
test("patternMatchesHostname with exact hostname match", () => {
|
||||
expect(patternMatchesHostname("example.com", "example.com")).toBe(true);
|
||||
expect(patternMatchesHostname("example.com", "different.com")).toBe(false);
|
||||
});
|
||||
|
||||
test("patternMatchesHostname with wildcard domains", () => {
|
||||
expect(patternMatchesHostname("sub.example.com", "*.example.com")).toBe(true);
|
||||
expect(patternMatchesHostname("sub.sub.example.com", "*.example.com")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(patternMatchesHostname("example.com", "*.example.com")).toBe(false);
|
||||
expect(patternMatchesHostname("sub.different.com", "*.example.com")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("patternMatchesHostname with domain suffix", () => {
|
||||
expect(patternMatchesHostname("sub.example.com", ".example.com")).toBe(true);
|
||||
expect(patternMatchesHostname("example.com", ".example.com")).toBe(true);
|
||||
expect(patternMatchesHostname("different.com", ".example.com")).toBe(false);
|
||||
});
|
||||
|
||||
test("patternMatchesHostname with case insensitivity", () => {
|
||||
expect(patternMatchesHostname("EXAMPLE.com", "example.COM")).toBe(true);
|
||||
expect(patternMatchesHostname("sub.EXAMPLE.com", "*.example.COM")).toBe(true);
|
||||
});
|
||||
|
||||
// Port handling tests
|
||||
test("patternMatchesHostname with exact port match", () => {
|
||||
expect(patternMatchesHostname("example.com:8080", "example.com:8080")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(patternMatchesHostname("example.com:8080", "example.com:9090")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("patternMatchesHostname with port in pattern but not in hostname", () => {
|
||||
expect(patternMatchesHostname("example.com", "example.com:8080")).toBe(false);
|
||||
});
|
||||
|
||||
test("patternMatchesHostname with port in hostname but not in pattern", () => {
|
||||
expect(patternMatchesHostname("example.com:8080", "example.com")).toBe(true);
|
||||
});
|
||||
|
||||
test("patternMatchesHostname with wildcard domains and ports", () => {
|
||||
expect(
|
||||
patternMatchesHostname("sub.example.com:8080", "*.example.com:8080"),
|
||||
).toBe(true);
|
||||
expect(
|
||||
patternMatchesHostname("sub.example.com:9090", "*.example.com:8080"),
|
||||
).toBe(false);
|
||||
expect(patternMatchesHostname("sub.example.com", "*.example.com:8080")).toBe(
|
||||
false,
|
||||
);
|
||||
});
|
||||
|
||||
test("patternMatchesHostname with domain suffix and ports", () => {
|
||||
expect(
|
||||
patternMatchesHostname("sub.example.com:8080", ".example.com:8080"),
|
||||
).toBe(true);
|
||||
expect(patternMatchesHostname("example.com:8080", ".example.com:8080")).toBe(
|
||||
true,
|
||||
);
|
||||
expect(
|
||||
patternMatchesHostname("sub.example.com:9090", ".example.com:8080"),
|
||||
).toBe(false);
|
||||
});
|
||||
|
||||
// Tests for shouldBypassProxy
|
||||
test("shouldBypassProxy returns false when NO_PROXY is not set", () => {
|
||||
expect(shouldBypassProxy("example.com")).toBe(false);
|
||||
expect(shouldBypassProxy("example.com", undefined)).toBe(false);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy returns true for exact hostname match", () => {
|
||||
process.env.NO_PROXY = "example.com,another.com";
|
||||
expect(shouldBypassProxy("example.com")).toBe(true);
|
||||
expect(shouldBypassProxy("example.com", undefined)).toBe(true);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy returns false when hostname doesn't match any NO_PROXY entry", () => {
|
||||
process.env.NO_PROXY = "example.com,another.com";
|
||||
expect(shouldBypassProxy("different.com")).toBe(false);
|
||||
expect(shouldBypassProxy("different.com", undefined)).toBe(false);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy handles lowercase no_proxy", () => {
|
||||
process.env.no_proxy = "example.com";
|
||||
expect(shouldBypassProxy("example.com")).toBe(true);
|
||||
expect(shouldBypassProxy("example.com", undefined)).toBe(true);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy works with wildcard domains", () => {
|
||||
process.env.NO_PROXY = "*.example.com";
|
||||
expect(shouldBypassProxy("sub.example.com")).toBe(true);
|
||||
expect(shouldBypassProxy("example.com")).toBe(false);
|
||||
expect(shouldBypassProxy("different.com")).toBe(false);
|
||||
expect(shouldBypassProxy("sub.example.com", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("example.com", undefined)).toBe(false);
|
||||
expect(shouldBypassProxy("different.com", undefined)).toBe(false);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy works with domain suffix", () => {
|
||||
process.env.NO_PROXY = ".example.com";
|
||||
expect(shouldBypassProxy("sub.example.com")).toBe(true);
|
||||
expect(shouldBypassProxy("example.com")).toBe(true);
|
||||
expect(shouldBypassProxy("different.com")).toBe(false);
|
||||
expect(shouldBypassProxy("sub.example.com", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("example.com", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("different.com", undefined)).toBe(false);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy handles multiple entries with different patterns", () => {
|
||||
process.env.NO_PROXY = "internal.local,*.example.com,.test.com";
|
||||
expect(shouldBypassProxy("internal.local")).toBe(true);
|
||||
expect(shouldBypassProxy("sub.example.com")).toBe(true);
|
||||
expect(shouldBypassProxy("sub.test.com")).toBe(true);
|
||||
expect(shouldBypassProxy("test.com")).toBe(true);
|
||||
expect(shouldBypassProxy("example.org")).toBe(false);
|
||||
expect(shouldBypassProxy("internal.local", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("sub.example.com", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("sub.test.com", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("test.com", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("example.org", undefined)).toBe(false);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy ignores whitespace in NO_PROXY", () => {
|
||||
process.env.NO_PROXY = " example.com , *.test.org ";
|
||||
expect(shouldBypassProxy("example.com")).toBe(true);
|
||||
expect(shouldBypassProxy("subdomain.test.org")).toBe(true);
|
||||
expect(shouldBypassProxy("example.com", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("subdomain.test.org", undefined)).toBe(true);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy with ports in NO_PROXY", () => {
|
||||
process.env.NO_PROXY = "example.com:8080,*.test.org:443,.internal.net:8443";
|
||||
expect(shouldBypassProxy("example.com:8080", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("example.com:9090", undefined)).toBe(false);
|
||||
expect(shouldBypassProxy("sub.test.org:443", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("sub.internal.net:8443", undefined)).toBe(true);
|
||||
expect(shouldBypassProxy("internal.net:8443", undefined)).toBe(true);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy accepts options with noProxy patterns", () => {
|
||||
const options = { noProxy: ["example.com:8080", "*.internal.net"] };
|
||||
expect(shouldBypassProxy("example.com:8080", options)).toBe(true);
|
||||
expect(shouldBypassProxy("example.com", options)).toBe(false);
|
||||
expect(shouldBypassProxy("server.internal.net", options)).toBe(true);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy combines environment and options noProxy patterns", () => {
|
||||
process.env.NO_PROXY = "example.org,*.test.com";
|
||||
const options = { noProxy: ["example.com:8080", "*.internal.net"] };
|
||||
expect(shouldBypassProxy("example.org", options)).toBe(true);
|
||||
expect(shouldBypassProxy("sub.test.com", options)).toBe(true);
|
||||
expect(shouldBypassProxy("example.com:8080", options)).toBe(true);
|
||||
expect(shouldBypassProxy("server.internal.net", options)).toBe(true);
|
||||
expect(shouldBypassProxy("other.domain", options)).toBe(false);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy handles empty noProxy array in options", () => {
|
||||
process.env.NO_PROXY = "example.org";
|
||||
const options = { noProxy: [] };
|
||||
expect(shouldBypassProxy("example.org", options)).toBe(true);
|
||||
expect(shouldBypassProxy("different.com", options)).toBe(false);
|
||||
});
|
||||
|
||||
test("shouldBypassProxy handles undefined options", () => {
|
||||
process.env.NO_PROXY = "example.org";
|
||||
expect(shouldBypassProxy("example.org", undefined)).toBe(true);
|
||||
});
|
||||
|
|
|
|||
|
|
@ -1,3 +1,5 @@
|
|||
import { RequestOptions } from "@continuedev/config-types";
|
||||
|
||||
/**
|
||||
* Gets the proxy settings from environment variables
|
||||
* @param protocol The URL protocol (http: or https:)
|
||||
|
|
@ -16,28 +18,91 @@ export function getProxyFromEnv(protocol: string): string | undefined {
|
|||
}
|
||||
}
|
||||
|
||||
// Note that request options proxy (per model) takes precedence over environment variables
|
||||
export function getProxy(
|
||||
protocol: string,
|
||||
requestOptions?: RequestOptions,
|
||||
): string | undefined {
|
||||
if (requestOptions?.proxy) {
|
||||
return requestOptions.proxy;
|
||||
}
|
||||
return getProxyFromEnv(protocol);
|
||||
}
|
||||
|
||||
export function getEnvNoProxyPatterns(): string[] {
|
||||
const envValue = process.env.NO_PROXY || process.env.no_proxy;
|
||||
if (envValue) {
|
||||
return envValue
|
||||
.split(",")
|
||||
.map((item) => item.trim().toLowerCase())
|
||||
.filter((i) => !!i);
|
||||
} else {
|
||||
return [];
|
||||
}
|
||||
}
|
||||
|
||||
export function getReqOptionsNoProxyPatterns(
|
||||
options: RequestOptions | undefined,
|
||||
): string[] {
|
||||
return (
|
||||
options?.noProxy?.map((i) => i.trim().toLowerCase()).filter((i) => !!i) ??
|
||||
[]
|
||||
);
|
||||
}
|
||||
|
||||
export function patternMatchesHostname(hostname: string, pattern: string) {
|
||||
// Split hostname and pattern to separate hostname and port
|
||||
const [hostnameWithoutPort, hostnamePort] = hostname.toLowerCase().split(":");
|
||||
const [patternWithoutPort, patternPort] = pattern.toLowerCase().split(":");
|
||||
|
||||
// If pattern specifies a port but hostname doesn't match it, no match
|
||||
if (patternPort && (!hostnamePort || hostnamePort !== patternPort)) {
|
||||
return false;
|
||||
}
|
||||
|
||||
// Now compare just the hostname parts
|
||||
|
||||
// exact match
|
||||
if (patternWithoutPort === hostnameWithoutPort) {
|
||||
return true;
|
||||
}
|
||||
// wildcard domain match (*.example.com)
|
||||
if (
|
||||
patternWithoutPort.startsWith("*.") &&
|
||||
hostnameWithoutPort.endsWith(patternWithoutPort.substring(1))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
// Domain suffix match (.example.com)
|
||||
if (
|
||||
patternWithoutPort.startsWith(".") &&
|
||||
hostnameWithoutPort.endsWith(patternWithoutPort.slice(1))
|
||||
) {
|
||||
return true;
|
||||
}
|
||||
|
||||
// TODO IP address ranges
|
||||
|
||||
// TODO CIDR notation
|
||||
|
||||
return false;
|
||||
}
|
||||
|
||||
/**
|
||||
* Checks if a hostname should bypass proxy based on NO_PROXY environment variable
|
||||
* @param hostname The hostname to check
|
||||
* @returns True if the hostname should bypass proxy
|
||||
*/
|
||||
export function shouldBypassProxy(hostname: string): boolean {
|
||||
const noProxy = process.env.NO_PROXY || process.env.no_proxy;
|
||||
if (!noProxy) return false;
|
||||
|
||||
const noProxyItems = noProxy.split(",").map((item) => item.trim());
|
||||
|
||||
return noProxyItems.some((item) => {
|
||||
// Exact match
|
||||
if (item === hostname) return true;
|
||||
|
||||
// Wildcard domain match (*.example.com)
|
||||
if (item.startsWith("*.") && hostname.endsWith(item.substring(1)))
|
||||
return true;
|
||||
|
||||
// Domain suffix match (.example.com)
|
||||
if (item.startsWith(".") && hostname.endsWith(item.slice(1))) return true;
|
||||
|
||||
return false;
|
||||
});
|
||||
export function shouldBypassProxy(
|
||||
hostname: string,
|
||||
requestOptions: RequestOptions | undefined,
|
||||
): boolean {
|
||||
const ignores = [
|
||||
...getEnvNoProxyPatterns(),
|
||||
...getReqOptionsNoProxyPatterns(requestOptions),
|
||||
];
|
||||
const hostLowerCase = hostname.toLowerCase();
|
||||
return ignores.some((ignore) =>
|
||||
patternMatchesHostname(hostLowerCase, ignore),
|
||||
);
|
||||
}
|
||||
|
|
|
|||
Loading…
Add table
Reference in a new issue