Skip to content

Commit eea0862

Browse files
authored
Add env in common and internal
1 parent 3d687e2 commit eea0862

File tree

77 files changed

+320
-262
lines changed

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

77 files changed

+320
-262
lines changed

backend/src/__tests__/auto-topup.test.ts

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ describe('Auto Top-up System', () => {
3232
warn: () => {},
3333
}
3434

35-
beforeAll(() => {
35+
beforeAll(async () => {
3636
// Set up default mocks
3737
dbMock = mock(() =>
3838
Promise.resolve({
@@ -45,7 +45,7 @@ describe('Auto Top-up System', () => {
4545
)
4646

4747
// Mock the database
48-
mockModule('@codebuff/internal/db', () => ({
48+
await mockModule('@codebuff/internal/db', () => ({
4949
default: {
5050
query: {
5151
user: {
@@ -61,7 +61,7 @@ describe('Auto Top-up System', () => {
6161
}))
6262

6363
// Mock Stripe payment intent creation
64-
mockModule('@codebuff/internal/util/stripe', () => ({
64+
await mockModule('@codebuff/internal/util/stripe', () => ({
6565
stripeServer: {
6666
paymentIntents: {
6767
create: mock(() =>

backend/src/__tests__/usage-calculation.test.ts

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -17,9 +17,9 @@ describe('Usage Calculation System', () => {
1717
warn: () => {},
1818
}
1919

20-
beforeAll(() => {
20+
beforeAll(async () => {
2121
// Mock the database module before importing the function
22-
mockModule('@codebuff/internal/db', () => ({
22+
await mockModule('@codebuff/internal/db', () => ({
2323
default: {
2424
select: () => ({
2525
from: () => ({
@@ -61,7 +61,7 @@ describe('Usage Calculation System', () => {
6161
]
6262

6363
// Mock the database module with the test data
64-
mockModule('@codebuff/internal/db', () => ({
64+
await mockModule('@codebuff/internal/db', () => ({
6565
default: {
6666
select: () => ({
6767
from: () => ({
@@ -98,7 +98,7 @@ describe('Usage Calculation System', () => {
9898
]
9999

100100
// Mock the database module with the test data
101-
mockModule('@codebuff/internal/db', () => ({
101+
await mockModule('@codebuff/internal/db', () => ({
102102
default: {
103103
select: () => ({
104104
from: () => ({
@@ -145,7 +145,7 @@ describe('Usage Calculation System', () => {
145145
]
146146

147147
// Mock the database module with the test data
148-
mockModule('@codebuff/internal/db', () => ({
148+
await mockModule('@codebuff/internal/db', () => ({
149149
default: {
150150
select: () => ({
151151
from: () => ({
@@ -201,7 +201,7 @@ describe('Usage Calculation System', () => {
201201
]
202202

203203
// Mock the database module with the test data
204-
mockModule('@codebuff/internal/db', () => ({
204+
await mockModule('@codebuff/internal/db', () => ({
205205
default: {
206206
select: () => ({
207207
from: () => ({

backend/src/index.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import http from 'http'
22

33
import { setupBigQuery } from '@codebuff/bigquery'
44
import { flushAnalytics, initAnalytics } from '@codebuff/common/analytics'
5-
import { env } from '@codebuff/internal'
5+
import { env } from '@codebuff/internal/env'
66
import cors from 'cors'
77
import express from 'express'
88

backend/src/llm-apis/relace-api.ts

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { countTokens } from '@codebuff/agent-runtime/util/token-counter'
2-
import { env } from '@codebuff/internal'
2+
import { env } from '@codebuff/internal/env'
33

44
import { saveMessage } from '../llm-apis/message-cost-tracker'
55

backend/src/util/logger.ts

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@ import path from 'path'
33
import { format } from 'util'
44

55
import { splitData } from '@codebuff/common/util/split-data'
6-
import { env } from '@codebuff/internal'
6+
import { env } from '@codebuff/internal/env'
77
import pino from 'pino'
88

99
import {
@@ -28,7 +28,7 @@ export const withLoggerContext = <T>(
2828
const debugDir = path.join(__dirname, '../../../debug')
2929
if (
3030
env.NEXT_PUBLIC_CB_ENVIRONMENT === 'dev' &&
31-
process.env.CODEBUFF_GITHUB_ACTIONS !== 'true'
31+
process.env['CODEBUFF_GITHUB_ACTIONS'] !== 'true'
3232
) {
3333
try {
3434
mkdirSync(debugDir, { recursive: true })
@@ -52,7 +52,7 @@ const pinoLogger = pino(
5252
timestamp: () => `,"timestamp":"${new Date(Date.now()).toISOString()}"`,
5353
},
5454
env.NEXT_PUBLIC_CB_ENVIRONMENT === 'dev' &&
55-
process.env.CODEBUFF_GITHUB_ACTIONS !== 'true'
55+
process.env['CODEBUFF_GITHUB_ACTIONS'] !== 'true'
5656
? pino.transport({
5757
target: 'pino/file',
5858
options: {
@@ -95,7 +95,7 @@ function splitAndLog(
9595
}
9696

9797
export const logger: Record<LogLevel, pino.LogFn> =
98-
process.env.NEXT_PUBLIC_CB_ENVIRONMENT === 'dev'
98+
env.NEXT_PUBLIC_CB_ENVIRONMENT === 'dev'
9999
? pinoLogger
100100
: (Object.fromEntries(
101101
loggingLevels.map((level) => {

cli/src/__tests__/e2e/returning-user-auth.test.ts

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,8 @@
1+
import fs from 'fs'
2+
import os from 'os'
3+
import path from 'path'
4+
5+
import { API_KEY_ENV_VAR } from '@codebuff/common/old-constants'
16
import {
27
describe,
38
test,
@@ -7,19 +12,16 @@ import {
712
mock,
813
spyOn,
914
} from 'bun:test'
10-
import fs from 'fs'
11-
import os from 'os'
12-
import path from 'path'
1315

16+
import { validateApiKey } from '../../hooks/use-auth-query'
1417
import {
1518
getAuthTokenDetails,
1619
saveUserCredentials,
1720
type User,
1821
} from '../../utils/auth'
19-
import { validateApiKey } from '../../hooks/use-auth-query'
2022

21-
import type { Logger } from '@codebuff/common/types/contracts/logger'
2223
import type { GetUserInfoFromApiKeyFn } from '@codebuff/common/types/contracts/database'
24+
import type { Logger } from '@codebuff/common/types/contracts/logger'
2325

2426
const RETURNING_USER: User = {
2527
id: 'returning-user-456',
@@ -45,14 +47,14 @@ describe('Returning User Authentication helpers', () => {
4547
tempConfigDir = fs.mkdtempSync(
4648
path.join(os.tmpdir(), 'manicode-returning-'),
4749
)
48-
originalEnv.CODEBUFF_API_KEY = process.env.CODEBUFF_API_KEY
50+
originalEnv[API_KEY_ENV_VAR] = process.env[API_KEY_ENV_VAR]
4951
})
5052

5153
afterEach(() => {
5254
if (fs.existsSync(tempConfigDir)) {
5355
fs.rmSync(tempConfigDir, { recursive: true, force: true })
5456
}
55-
process.env.CODEBUFF_API_KEY = originalEnv.CODEBUFF_API_KEY
57+
process.env[API_KEY_ENV_VAR] = originalEnv[API_KEY_ENV_VAR]
5658
mock.restore()
5759
})
5860

@@ -81,7 +83,7 @@ describe('Returning User Authentication helpers', () => {
8183
path.join(tempConfigDir, 'credentials.json'),
8284
)
8385

84-
process.env.CODEBUFF_API_KEY = 'env-token-123'
86+
process.env[API_KEY_ENV_VAR] = 'env-token-123'
8587

8688
const details = getAuthTokenDetails()
8789
expect(details.source).toBe('environment')

cli/src/__tests__/integration/credentials-storage.test.ts

Lines changed: 38 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,11 @@
1+
import fs from 'fs'
2+
import os from 'os'
3+
import path from 'path'
4+
5+
import {
6+
clearMockedModules,
7+
mockModule,
8+
} from '@codebuff/common/testing/mock-modules'
19
import {
210
describe,
311
test,
@@ -7,16 +15,10 @@ import {
715
mock,
816
spyOn,
917
} from 'bun:test'
10-
import fs from 'fs'
11-
import path from 'path'
12-
import os from 'os'
1318

1419
import * as authModule from '../../utils/auth'
15-
import {
16-
saveUserCredentials,
17-
getUserCredentials,
18-
logoutUser,
19-
} from '../../utils/auth'
20+
import { saveUserCredentials, getUserCredentials } from '../../utils/auth'
21+
2022
import type { User } from '../../utils/auth'
2123

2224
/**
@@ -51,7 +53,6 @@ describe('Credentials Storage Integration', () => {
5153
beforeEach(() => {
5254
// Create temporary config directory for tests
5355
tempConfigDir = fs.mkdtempSync(path.join(os.tmpdir(), 'manicode-test-'))
54-
originalEnv = process.env.NEXT_PUBLIC_CB_ENVIRONMENT
5556

5657
// Mock getConfigDir to use temp directory
5758
spyOn(authModule, 'getConfigDir').mockReturnValue(tempConfigDir)
@@ -66,8 +67,8 @@ describe('Credentials Storage Integration', () => {
6667
fs.rmSync(tempConfigDir, { recursive: true, force: true })
6768
}
6869

69-
process.env.NEXT_PUBLIC_CB_ENVIRONMENT = originalEnv
7070
mock.restore()
71+
clearMockedModules()
7172
})
7273

7374
describe('P0: File System Operations', () => {
@@ -154,31 +155,48 @@ describe('Credentials Storage Integration', () => {
154155
expect(keys[0]).toBe('default')
155156
})
156157

157-
test('should use manicode-dev directory in development environment', () => {
158+
test('should use manicode-test directory in test environment', async () => {
158159
// Restore getConfigDir to use real implementation for this test
159160
mock.restore()
160161

161-
// Set environment to dev
162-
process.env.NEXT_PUBLIC_CB_ENVIRONMENT = 'dev'
162+
await mockModule('@codebuff/common/env', () => ({
163+
env: { NEXT_PUBLIC_CB_ENVIRONMENT: 'test' },
164+
}))
163165

164166
// Call real getConfigDir to verify it includes '-dev'
165167
const configDir = authModule.getConfigDir()
166-
expect(configDir).toContain('manicode-dev')
167-
expect(configDir).not.toContain('manicode/')
168-
expect(configDir).not.toBe(path.join(os.homedir(), '.config', 'manicode'))
168+
expect(configDir).toEqual(
169+
path.join(os.homedir(), '.config', 'manicode-test'),
170+
)
169171
})
170172

171-
test('should use manicode directory in production environment', () => {
173+
test('should use manicode-dev directory in development environment', async () => {
174+
// Restore getConfigDir to use real implementation for this test
175+
mock.restore()
176+
177+
await mockModule('@codebuff/common/env', () => ({
178+
env: { NEXT_PUBLIC_CB_ENVIRONMENT: 'dev' },
179+
}))
180+
181+
// Call real getConfigDir to verify it includes '-dev'
182+
const configDir = authModule.getConfigDir()
183+
expect(configDir).toEqual(
184+
path.join(os.homedir(), '.config', 'manicode-dev'),
185+
)
186+
})
187+
188+
test('should use manicode directory in production environment', async () => {
172189
// Restore getConfigDir to use real implementation
173190
mock.restore()
174191

175192
// Set environment to prod (or unset it)
176-
process.env.NEXT_PUBLIC_CB_ENVIRONMENT = 'prod'
193+
await mockModule('@codebuff/common/env', () => ({
194+
env: { NEXT_PUBLIC_CB_ENVIRONMENT: 'prod' },
195+
}))
177196

178197
// Call real getConfigDir to verify it doesn't include '-dev'
179198
const configDir = authModule.getConfigDir()
180-
expect(configDir).toBe(path.join(os.homedir(), '.config', 'manicode'))
181-
expect(configDir).not.toContain('manicode-dev')
199+
expect(configDir).toEqual(path.join(os.homedir(), '.config', 'manicode'))
182200
})
183201

184202
test('should allow credentials to persist across simulated CLI restarts', () => {
@@ -297,11 +315,6 @@ describe('Credentials Storage Integration', () => {
297315

298316
// File should be writable by user
299317
expect((mode & 0o200) !== 0).toBe(true)
300-
301-
// For security, ideally should not be world-readable, but we accept common permissions
302-
// Common acceptable permissions: 0644 (rw-r--r--) or 0600 (rw-------)
303-
const octalMode = (mode & 0o777).toString(8)
304-
expect(['644', '600', '640']).toContain(octalMode)
305318
} else {
306319
// On Windows, just verify file exists and is accessible
307320
expect(fs.existsSync(credentialsPath)).toBe(true)

cli/src/hooks/use-auth-query.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { API_KEY_ENV_VAR } from '@codebuff/common/old-constants'
12
import { getUserInfoFromApiKey as defaultGetUserInfoFromApiKey } from '@codebuff/sdk'
23
import { useQuery, useMutation, useQueryClient } from '@tanstack/react-query'
34

@@ -9,8 +10,8 @@ import {
910
} from '../utils/auth'
1011
import { logger as defaultLogger } from '../utils/logger'
1112

12-
import type { Logger } from '@codebuff/common/types/contracts/logger'
1313
import type { GetUserInfoFromApiKeyFn } from '@codebuff/common/types/contracts/database'
14+
import type { Logger } from '@codebuff/common/types/contracts/logger'
1415

1516
// Query keys for type-safe cache management
1617
export const authQueryKeys = {
@@ -95,7 +96,7 @@ export function useAuthQuery(deps: UseAuthQueryDeps = {}) {
9596

9697
const userCredentials = getUserCredentials()
9798
const apiKey =
98-
userCredentials?.authToken || process.env.CODEBUFF_API_KEY || ''
99+
userCredentials?.authToken || process.env[API_KEY_ENV_VAR] || ''
99100

100101
return useQuery({
101102
queryKey: authQueryKeys.validation(apiKey),

cli/src/index.tsx

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -2,14 +2,15 @@
22
import './polyfills/bun-strip-ansi'
33
import { createRequire } from 'module'
44

5+
import { API_KEY_ENV_VAR } from '@codebuff/common/old-constants'
56
import { render } from '@opentui/react'
67
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
78
import { Command } from 'commander'
89
import React from 'react'
910

1011
import { App } from './chat'
11-
import { getLoadedAgentsData } from './utils/local-agent-registry'
1212
import { getUserCredentials } from './utils/auth'
13+
import { getLoadedAgentsData } from './utils/local-agent-registry'
1314
import { clearLogFile } from './utils/logger'
1415

1516
const require = createRequire(import.meta.url)
@@ -101,7 +102,7 @@ const AppWithAsyncAuth = () => {
101102
// Check authentication asynchronously
102103
const userCredentials = getUserCredentials()
103104
const apiKey =
104-
userCredentials?.authToken || process.env.CODEBUFF_API_KEY || ''
105+
userCredentials?.authToken || process.env[API_KEY_ENV_VAR] || ''
105106

106107
if (!apiKey) {
107108
// No credentials, require auth

cli/src/login/constants.ts

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,7 @@
1+
import { env } from '@codebuff/common/env'
2+
13
// Get the website URL from environment or use default
2-
export const WEBSITE_URL =
3-
process.env.NEXT_PUBLIC_CODEBUFF_APP_URL || 'https://codebuff.com'
4+
export const WEBSITE_URL = env.NEXT_PUBLIC_CODEBUFF_APP_URL
45

56
// Codebuff ASCII Logo - compact version for 80-width terminals
67
export const LOGO = `

0 commit comments

Comments
 (0)