Skip to content

Commit

Permalink
fix: use default base url if BASE_URL env var is blank (#250)
Browse files Browse the repository at this point in the history
Previously, a blank BASE_URL environment variable would cause an invalid URL error. Now it uses the default.
  • Loading branch information
stainless-bot committed Jan 10, 2024
1 parent 8797990 commit e38f32f
Show file tree
Hide file tree
Showing 3 changed files with 18 additions and 4 deletions.
6 changes: 4 additions & 2 deletions src/core.ts
Expand Up @@ -961,14 +961,16 @@ export const ensurePresent = <T>(value: T | null | undefined): T => {
/**
* Read an environment variable.
*
* Trims beginning and trailing whitespace.
*
* Will return undefined if the environment variable doesn't exist or cannot be accessed.
*/
export const readEnv = (env: string): string | undefined => {
if (typeof process !== 'undefined') {
return process.env?.[env] ?? undefined;
return process.env?.[env]?.trim() ?? undefined;
}
if (typeof Deno !== 'undefined') {
return Deno.env?.get?.(env);
return Deno.env?.get?.(env)?.trim();
}
return undefined;
};
Expand Down
2 changes: 1 addition & 1 deletion src/index.ts
Expand Up @@ -104,7 +104,7 @@ export class Anthropic extends Core.APIClient {
apiKey,
authToken,
...opts,
baseURL: baseURL ?? `https://api.anthropic.com`,
baseURL: baseURL || `https://api.anthropic.com`,
};

super({
Expand Down
14 changes: 13 additions & 1 deletion tests/index.test.ts
Expand Up @@ -140,7 +140,7 @@ describe('instantiate client', () => {
});

afterEach(() => {
process.env['SINK_BASE_URL'] = undefined;
process.env['ANTHROPIC_BASE_URL'] = undefined;
});

test('explicit option', () => {
Expand All @@ -153,6 +153,18 @@ describe('instantiate client', () => {
const client = new Anthropic({ apiKey: 'my-anthropic-api-key' });
expect(client.baseURL).toEqual('https://example.com/from_env');
});

test('empty env variable', () => {
process.env['ANTHROPIC_BASE_URL'] = ''; // empty
const client = new Anthropic({ apiKey: 'my-anthropic-api-key' });
expect(client.baseURL).toEqual('https://api.anthropic.com');
});

test('blank env variable', () => {
process.env['ANTHROPIC_BASE_URL'] = ' '; // blank
const client = new Anthropic({ apiKey: 'my-anthropic-api-key' });
expect(client.baseURL).toEqual('https://api.anthropic.com');
});
});

test('maxRetries option is correctly set', () => {
Expand Down

0 comments on commit e38f32f

Please sign in to comment.