Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ out/
coverage/
.nyc_output
*.lcov
.jest-cache/

# Logs
logs
Expand Down
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2025 xwartz

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
62 changes: 11 additions & 51 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
# Cursor API SDK
# Cursor API

[![npm version](https://badge.fury.io/js/cursor-api.svg)](https://badge.fury.io/js/cursor-api)
[![TypeScript](https://img.shields.io/badge/%3C%2F%3E-TypeScript-%230074c1.svg)](http://www.typescriptlang.org/)
Expand Down Expand Up @@ -36,7 +36,7 @@ const cursor = new Cursor({
})

const completion = await cursor.chat.completions.create({
model: 'gpt-4',
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Hello!' }],
})
```
Expand All @@ -45,7 +45,7 @@ const completion = await cursor.chat.completions.create({

```typescript
const stream = await cursor.chat.completions.create({
model: 'gpt-4',
model: 'gpt-4o',
messages: [{ role: 'user', content: 'Tell me a story' }],
stream: true,
})
Expand All @@ -56,6 +56,14 @@ for await (const chunk of stream) {
}
```

## Supported Models

| Model | Streaming | Description |
| ------------------------------------------------------- | --------- | ----------------------- |
| `claude-4-sonnet`, `claude-3.7-sonnet`, `claude-4-opus` | ✅ | Anthropic Claude models |
| `gpt-4.1`, `gpt-4o`, `gpt-4o-mini` | ✅ | OpenAI GPT models |
| `deepseek-r1`, `deepseek-v3` | ✅ | DeepSeek models |

## Documentation

- 📚 [Quick Start Guide](./docs/QUICK_START.md) - Get up and running in 5 minutes
Expand All @@ -66,54 +74,6 @@ for await (const chunk of stream) {
- 🧪 [Verification Guide](./docs/VERIFICATION.md) - Testing and debugging tools
- 👥 [Contributing](./CONTRIBUTING.md) - Development and contribution guidelines

## Supported Models

| Model | Streaming | Description |
| ------------------------------------------------------- | --------- | ----------------------- |
| `claude-4-sonnet`, `claude-3.7-sonnet`, `claude-4-opus` | ✅ | Anthropic Claude models |
| `gpt-4.1`, `gpt-4o`, `gpt-4o-mini` | ✅ | OpenAI GPT models |
| `deepseek-r1`, `deepseek-v3` | ✅ | DeepSeek models |

## Error Handling

```typescript
import { AuthenticationError, RateLimitError } from 'cursor-api';

try {
const completion = await cursor.chat.completions.create({
model: 'gpt-4',
messages: [{ role: 'user', content: 'Hello' }],
});
} catch (error) {
if (error instanceof AuthenticationError) {
console.error('Invalid credentials');
} else if (error instanceof RateLimitError) {
console.error('Rate limit exceeded');
}
}
```

## Development

```bash
git clone https://github.com/xwartz/cursor-api.git
cd cursor-api
npm install
npm run build
npm test
```

**Requirements:**
- Node.js 18+
- TypeScript 5.6+
- ESLint 9.0+ (flat config)

**Key Scripts:**
- `npm run build` - Build the project
- `npm run test` - Run tests
- `npm run lint` - Check code style
- `npm run format` - Format code with Prettier

## Contributing

We welcome contributions! See our [Contributing Guide](CONTRIBUTING.md) for details.
Expand Down
32 changes: 19 additions & 13 deletions e2e/jest.config.js
Original file line number Diff line number Diff line change
@@ -1,22 +1,25 @@
/** @type {import('jest').Config} */

const commonTsJestConfig = {
useESM: false,
tsconfig: {
module: 'commonjs',
target: 'es2020',
moduleResolution: 'node',
esModuleInterop: true,
allowSyntheticDefaultImports: true,
strict: false
}
};

module.exports = {
preset: 'ts-jest',
testEnvironment: 'node',
testTimeout: 120000,
displayName: 'e2e',
roots: ['<rootDir>'],
testMatch: ['**/*.e2e.test.ts'],
transform: {
'^.+\\.(ts|tsx)$': ['ts-jest', {
useESM: false,
tsconfig: {
module: 'commonjs',
target: 'es2020',
moduleResolution: 'node',
esModuleInterop: true,
allowSyntheticDefaultImports: true,
strict: false
}
}],
'^.+\\.(ts|tsx)$': ['ts-jest', commonTsJestConfig],
},
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/../src/$1',
Expand All @@ -26,4 +29,7 @@ module.exports = {
'/node_modules/',
'/temp-.*\\.(js|mjs|ts)$/'
],
}
maxWorkers: 1,
cache: true,
cacheDirectory: '<rootDir>/.jest-cache',
};
97 changes: 39 additions & 58 deletions jest.config.js
Original file line number Diff line number Diff line change
@@ -1,26 +1,37 @@
/** @type {import('jest').Config} */
module.exports = {

const commonTsJestConfig = {
useESM: false,
tsconfig: {
module: 'commonjs',
target: 'es2020',
moduleResolution: 'node',
esModuleInterop: true,
allowSyntheticDefaultImports: true,
strict: false
}
};

const baseConfig = {
preset: 'ts-jest',
testEnvironment: 'node',
testTimeout: 30000,
transform: {
'^.+\\.(ts|tsx)$': ['ts-jest', commonTsJestConfig],
},
setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
};

module.exports = {
...baseConfig,
forceExit: true,
roots: ['<rootDir>/src', '<rootDir>/tests'],
testMatch: [
'**/__tests__/**/*.+(ts|tsx|js)',
'**/*.(test|spec).+(ts|tsx|js)'
],
transform: {
'^.+\\.(ts|tsx)$': ['ts-jest', {
useESM: false,
tsconfig: {
module: 'commonjs',
target: 'es2020',
moduleResolution: 'node',
esModuleInterop: true,
allowSyntheticDefaultImports: true,
strict: false
}
}],
},
collectCoverageFrom: [
'src/**/*.{ts,tsx}',
'!src/**/*.d.ts',
Expand All @@ -34,57 +45,27 @@ module.exports = {
'lcov',
'html'
],
setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},

maxWorkers: '50%',
cache: true,
cacheDirectory: '<rootDir>/.jest-cache',
projects: [
{
...baseConfig,
displayName: 'unit',
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/tests/**/*.test.ts'],
transform: {
'^.+\\.(ts|tsx)$': ['ts-jest', {
useESM: false,
tsconfig: {
module: 'commonjs',
target: 'es2020',
moduleResolution: 'node',
esModuleInterop: true,
allowSyntheticDefaultImports: true,
strict: false
}
}],
},
setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
collectCoverageFrom: [
'src/**/*.{ts,tsx}',
'!src/**/*.d.ts',
'!src/**/*.test.{ts,tsx}',
'!src/**/*.spec.{ts,tsx}',
'!src/examples/**/*',
],
},
{
...baseConfig,
displayName: 'e2e',
preset: 'ts-jest',
testEnvironment: 'node',
testMatch: ['<rootDir>/e2e/**/*.e2e.test.ts'],
testTimeout: 120000,
transform: {
'^.+\\.(ts|tsx)$': ['ts-jest', {
useESM: false,
tsconfig: {
module: 'commonjs',
target: 'es2020',
moduleResolution: 'node',
esModuleInterop: true,
allowSyntheticDefaultImports: true,
strict: false
}
}],
},
setupFilesAfterEnv: ['<rootDir>/tests/setup.ts'],
moduleNameMapper: {
'^@/(.*)$': '<rootDir>/src/$1',
},
},
],
};
12 changes: 6 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -43,12 +43,12 @@
"verify": "tsx scripts/verify.ts",
"verify:build": "tsx scripts/verify-build.ts",
"debug": "tsx scripts/debug-auth.ts",
"test": "jest --selectProjects unit",
"test:watch": "jest --watch --selectProjects unit",
"test:coverage": "jest --coverage --selectProjects unit",
"test:e2e": "jest --selectProjects e2e",
"test:unit": "jest --selectProjects unit",
"test:all": "jest",
"test": "jest --detectOpenHandles --selectProjects unit",
"test:watch": "jest --watch --detectOpenHandles --selectProjects unit",
"test:coverage": "jest --coverage --detectOpenHandles --selectProjects unit",
"test:e2e": "jest --detectOpenHandles --selectProjects e2e",
"test:unit": "jest --detectOpenHandles --selectProjects unit",
"test:all": "npm run test:unit && npm run test:e2e",
"lint": "eslint src --ext .ts,.tsx",
"lint:fix": "eslint src --ext .ts,.tsx --fix",
"format": "prettier --write \"src/**/*.{ts,tsx,json}\"",
Expand Down
31 changes: 21 additions & 10 deletions src/core/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,13 +41,8 @@ export class APIClient {
* Create request headers
*/
private createHeaders(options?: RequestOptions): Record<string, string> {
// Handle URL-encoded keys
const cleanApiKey = this.apiKey.includes('%3A%3A')
? this.apiKey.split('%3A%3A')[1]
: this.apiKey

return {
authorization: `Bearer ${cleanApiKey}`,
authorization: `Bearer ${this.apiKey}`,
'x-cursor-checksum': this.checksum,
'Content-Type': 'application/connect+proto',
'connect-accept-encoding': 'gzip',
Expand Down Expand Up @@ -81,9 +76,11 @@ export class APIClient {
let lastError: Error | null = null

for (let attempt = 0; attempt <= this.maxRetries; attempt++) {
const controller = new AbortController()
let timeoutId: NodeJS.Timeout | undefined

try {
const controller = new AbortController()
const timeoutId = setTimeout(
timeoutId = setTimeout(
() => controller.abort(),
options.timeout ?? this.timeout
)
Expand All @@ -95,7 +92,11 @@ export class APIClient {
signal: options.signal ?? controller.signal,
})

clearTimeout(timeoutId)
// Clear timeout on successful response
if (timeoutId !== undefined) {
clearTimeout(timeoutId)
timeoutId = undefined
}

if (!response.ok) {
const errorText = await response.text().catch(() => 'Unknown error')
Expand All @@ -104,6 +105,12 @@ export class APIClient {

return response as T
} catch (error) {
// Ensure timeout is always cleared, even on error
if (timeoutId !== undefined) {
clearTimeout(timeoutId)
timeoutId = undefined
}

lastError = error as Error

// Don't retry on client errors (4xx) or if it's the last attempt
Expand Down Expand Up @@ -140,9 +147,13 @@ export class APIClient {
}

/**
* Utility function to sleep
* Utility function to sleep (can be bypassed in tests)
*/
private sleep(ms: number): Promise<void> {
// Allow bypassing sleep in test environment
if (process.env['NODE_ENV'] === 'test' || process.env['JEST_WORKER_ID']) {
return Promise.resolve()
}
return new Promise(resolve => setTimeout(resolve, ms))
}

Expand Down
Loading