Skip to content

Commit

Permalink
tmp
Browse files Browse the repository at this point in the history
  • Loading branch information
yjp20 committed Oct 23, 2024
1 parent ebfcc69 commit 0d836ee
Show file tree
Hide file tree
Showing 205 changed files with 4,644 additions and 1,932 deletions.
2 changes: 0 additions & 2 deletions .github/workflows/publish-jsr.yml
Original file line number Diff line number Diff line change
Expand Up @@ -28,5 +28,3 @@ jobs:
- name: Publish to JSR
run: |
bash ./bin/publish-jsr
env:
JSR_TOKEN: ${{ secrets.SINK_JSR_TOKEN || secrets.JSR_TOKEN }}
41 changes: 21 additions & 20 deletions src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -41,16 +41,16 @@ async function defaultParseResponse<T>(props: APIResponseProps): Promise<T> {
const { response } = props;
if (props.options.stream) {
debug('response', response.status, response.url, response.headers, response.body);

// Note: there is an invariant here that isn't represented in the type system
// that if you set `stream: true` the response type must also be `Stream<T>`

if (props.options.__streamClass) {
return props.options.__streamClass.fromSSEResponse(response, props.controller) as any;
}

return Stream.fromSSEResponse(response, props.controller) as any;
};
}

// fetch refuses to read the body when the status code is 204.
if (response.status === 204) {
Expand Down Expand Up @@ -368,9 +368,11 @@ export abstract class APIClient {
// Don't set the retry count header if it was already set or removed through default headers or by the
// caller. We check `defaultHeaders` and `headers`, which can contain nulls, instead of `reqHeaders` to
// account for the removal case.
if (getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&
getHeader(headers, 'x-stainless-retry-count') === undefined) {
reqHeaders['x-stainless-retry-count'] = String(retryCount)
if (
getHeader(defaultHeaders, 'x-stainless-retry-count') === undefined &&
getHeader(headers, 'x-stainless-retry-count') === undefined
) {
reqHeaders['x-stainless-retry-count'] = String(retryCount);
}

this.validateHeaders(reqHeaders, headers);
Expand Down Expand Up @@ -781,14 +783,14 @@ export type RequestOptions<
signal?: AbortSignal | undefined | null;
idempotencyKey?: string;

stringOpt?: string | undefined;
booleanOpt?: boolean | undefined;
integerOpt?: number | undefined;
numberOpt?: number | undefined;
stringOpt?: string | undefined;
booleanOpt?: boolean | undefined;
integerOpt?: number | undefined;
numberOpt?: number | undefined;

__binaryRequest?: boolean | undefined;
__binaryResponse?: boolean | undefined;
__streamClass?: typeof Stream
__streamClass?: typeof Stream;
};

// This is required so that we can determine if a given object matches the RequestOptions
Expand All @@ -808,14 +810,14 @@ const requestOptionsKeys: KeysEnum<RequestOptions> = {
signal: true,
idempotencyKey: true,

stringOpt: true,
booleanOpt: true,
integerOpt: true,
numberOpt: true,
stringOpt: true,
booleanOpt: true,
integerOpt: true,
numberOpt: true,

__binaryRequest: true,
__binaryResponse: true,
__streamClass: true
__streamClass: true,
};

export const isRequestOptions = (obj: unknown): obj is RequestOptions => {
Expand Down Expand Up @@ -1029,8 +1031,7 @@ export const castToError = (err: any): Error => {
};

export const ensurePresent = <T>(value: T | null | undefined): T => {
if (value == null)
throw new SinkError(`Expected a value to be given but received ${value} instead.`);
if (value == null) throw new SinkError(`Expected a value to be given but received ${value} instead.`);
return value;
};

Expand Down Expand Up @@ -1169,7 +1170,7 @@ export const getRequiredHeader = (headers: HeadersLike | Headers, header: string
throw new Error(`Could not find ${header} header`);
}
return foundHeader;
}
};

export const getHeader = (headers: HeadersLike | Headers, header: string): string | undefined => {
const lowerCasedHeader = header.toLowerCase();
Expand Down
24 changes: 16 additions & 8 deletions src/error.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,18 +2,21 @@

import { castToError, Headers } from './core';

export class SinkError extends Error {
}
export class SinkError extends Error {}

export class APIError extends SinkError {
readonly status: number | undefined;
readonly headers: Headers | undefined;
readonly error: Object | undefined;


readonly requestId: string | null | undefined;

constructor(status: number | undefined, error: Object | undefined, message: string | undefined, headers: Headers | undefined) {
constructor(
status: number | undefined,
error: Object | undefined,
message: string | undefined,
headers: Headers | undefined,
) {
super(`${APIError.makeMessage(status, error, message)}`);
this.status = status;
this.headers = headers;
Expand All @@ -24,7 +27,8 @@ export class APIError extends SinkError {
private static makeMessage(status: number | undefined, error: any, message: string | undefined) {
const msg =
error?.message ?
typeof error.message === 'string' ? error.message
typeof error.message === 'string' ?
error.message
: JSON.stringify(error.message)
: error ? JSON.stringify(error)
: message;
Expand All @@ -41,7 +45,12 @@ export class APIError extends SinkError {
return '(no status code or body)';
}

static generate(status: number | undefined, errorResponse: Object | undefined, message: string | undefined, headers: Headers | undefined) {
static generate(
status: number | undefined,
errorResponse: Object | undefined,
message: string | undefined,
headers: Headers | undefined,
) {
if (!status) {
return new APIConnectionError({ message, cause: castToError(errorResponse) });
}
Expand Down Expand Up @@ -137,5 +146,4 @@ export class RateLimitError extends APIError {
override readonly status: 429 = 429;
}

export class InternalServerError extends APIError {
}
export class InternalServerError extends APIError {}
62 changes: 38 additions & 24 deletions src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,7 @@

import * as Errors from './error';
import * as Uploads from './uploads';
import { isRequestOptions } from './core';
import { type Agent, type RequestInit } from './_shims/index';
import { type Agent } from './_shims/index';
import * as qs from './internal/qs';
import * as Core from './core';
import * as Pagination from './pagination';
Expand Down Expand Up @@ -123,7 +122,7 @@ export interface ClientOptions {
* Specify a custom `fetch` function implementation.
*
* If not provided, we use `node-fetch` on Node.js and otherwise expect that `fetch` is
* defined globally.
* defined globally.
*/
fetch?: Core.Fetch | undefined;

Expand Down Expand Up @@ -159,7 +158,7 @@ export interface ClientOptions {
}

/**
* API Client for interfacing with the Sink API.
* API Client for interfacing with the Sink API.
*/
export class Sink extends Core.APIClient {
userToken: string | null;
Expand Down Expand Up @@ -238,22 +237,22 @@ export class Sink extends Core.APIClient {
}: ClientOptions) {
if (username === undefined) {
throw new Errors.SinkError(
'The SINK_USER environment variable is missing or empty; either provide it, or instantiate the Sink client with an username option, like new Sink({ username: \'Robert\' }).'
"The SINK_USER environment variable is missing or empty; either provide it, or instantiate the Sink client with an username option, like new Sink({ username: 'Robert' }).",
);
}
if (someNumberArgRequiredNoDefault === undefined) {
throw new Errors.SinkError(
'The SINK_SOME_NUMBER_ARG environment variable is missing or empty; either provide it, or instantiate the Sink client with an someNumberArgRequiredNoDefault option, like new Sink({ someNumberArgRequiredNoDefault: \'my someNumberArgRequiredNoDefault\' }).'
"The SINK_SOME_NUMBER_ARG environment variable is missing or empty; either provide it, or instantiate the Sink client with an someNumberArgRequiredNoDefault option, like new Sink({ someNumberArgRequiredNoDefault: 'my someNumberArgRequiredNoDefault' }).",
);
}
if (someNumberArgRequiredNoDefaultNoEnv === undefined) {
throw new Errors.SinkError(
'Missing required client option someNumberArgRequiredNoDefaultNoEnv; you need to instantiate the Sink client with an someNumberArgRequiredNoDefaultNoEnv option, like new Sink({ someNumberArgRequiredNoDefaultNoEnv: \'my someNumberArgRequiredNoDefaultNoEnv\' }).'
"Missing required client option someNumberArgRequiredNoDefaultNoEnv; you need to instantiate the Sink client with an someNumberArgRequiredNoDefaultNoEnv option, like new Sink({ someNumberArgRequiredNoDefaultNoEnv: 'my someNumberArgRequiredNoDefaultNoEnv' }).",
);
}
if (requiredArgNoEnv === undefined) {
throw new Errors.SinkError(
'Missing required client option requiredArgNoEnv; you need to instantiate the Sink client with an requiredArgNoEnv option, like new Sink({ requiredArgNoEnv: \'<example>\' }).'
"Missing required client option requiredArgNoEnv; you need to instantiate the Sink client with an requiredArgNoEnv option, like new Sink({ requiredArgNoEnv: '<example>' }).",
);
}

Expand Down Expand Up @@ -282,13 +281,15 @@ export class Sink extends Core.APIClient {
};

if (!options.dangerouslyAllowBrowser && Core.isRunningInBrowser()) {
throw new Errors.SinkError('This is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Sink({ dangerouslyAllowBrowser: true })')
throw new Errors.SinkError(
'This is disabled by default, as it risks exposing your secret API credentials to attackers.\nIf you understand the risks and have appropriate mitigations in place,\nyou can set the `dangerouslyAllowBrowser` option to `true`, e.g.,\n\nnew Sink({ dangerouslyAllowBrowser: true })',
);
}

if (baseURL && opts.environment) {
throw new Errors.SinkError(
'Ambiguous URL; The `baseURL` option (or SINK_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null'
)
'Ambiguous URL; The `baseURL` option (or SINK_BASE_URL env var) and the `environment` option are given. If you want to use the environment you must pass baseURL: null',
);
}

super({
Expand All @@ -300,7 +301,7 @@ export class Sink extends Core.APIClient {
});

this._options = options;
this.idempotencyHeader = 'Idempotency-Key'
this.idempotencyHeader = 'Idempotency-Key';

this.userToken = userToken;
this.apiKeyHeader = apiKeyHeader;
Expand Down Expand Up @@ -372,7 +373,8 @@ export class Sink extends Core.APIClient {
version1_30Names: API.Version1_30Names = new API.Version1_30Names(this);
recursion: API.Recursion = new API.Recursion(this);
sharedQueryParams: API.SharedQueryParams = new API.SharedQueryParams(this);
modelReferencedInParentAndChild: API.ModelReferencedInParentAndChildResource = new API.ModelReferencedInParentAndChildResource(this);
modelReferencedInParentAndChild: API.ModelReferencedInParentAndChildResource =
new API.ModelReferencedInParentAndChildResource(this);

/**
* API status check
Expand All @@ -381,7 +383,7 @@ export class Sink extends Core.APIClient {
return this.get('/status', options);
}

apiStatusAlias = this.apiStatus
apiStatusAlias = this.apiStatus;

/**
* Endpoint returning no response
Expand All @@ -400,7 +402,7 @@ export class Sink extends Core.APIClient {
protected override defaultHeaders(opts: Core.FinalRequestOptions): Core.Headers {
return {
...super.defaultHeaders(opts),
...(this._options.dangerouslyAllowBrowser ? {'my-header-only-set-if-browser': 'true'} : undefined),
...(this._options.dangerouslyAllowBrowser ? { 'my-header-only-set-if-browser': 'true' } : undefined),
'My-Api-Version': '11',
'X-Enable-Metrics': '1',
'X-Client-UserName': this.username,
Expand All @@ -411,8 +413,8 @@ export class Sink extends Core.APIClient {
}

protected override authHeaders(opts: Core.FinalRequestOptions): Core.Headers {
const bearerAuth = this.bearerAuth(opts)
const apiKeyAuth = this.apiKeyAuth(opts)
const bearerAuth = this.bearerAuth(opts);
const apiKeyAuth = this.apiKeyAuth(opts);

if (bearerAuth != null && !Core.isEmptyObj(bearerAuth)) {
return bearerAuth;
Expand All @@ -439,12 +441,12 @@ export class Sink extends Core.APIClient {
}

protected override stringifyQuery(query: Record<string, unknown>): string {
return qs.stringify(query, { arrayFormat: 'comma' })
return qs.stringify(query, { arrayFormat: 'comma' });
}

static Sink = this;
static CONSTANT_WITH_NEWLINES = "\n\nHuman:"
static DEFAULT_TIMEOUT = 60000 // 1 minute
static CONSTANT_WITH_NEWLINES = '\n\nHuman:';
static DEFAULT_TIMEOUT = 60000; // 1 minute

static SinkError = Errors.SinkError;
static APIError = Errors.APIError;
Expand All @@ -464,11 +466,23 @@ export class Sink extends Core.APIClient {
static fileFromPath = Uploads.fileFromPath;
}

export const {
CONSTANT_WITH_NEWLINES
} = Sink
export const { CONSTANT_WITH_NEWLINES } = Sink;

export const { SinkError, APIError, APIConnectionError, APIConnectionTimeoutError, APIUserAbortError, NotFoundError, ConflictError, RateLimitError, BadRequestError, AuthenticationError, InternalServerError, PermissionDeniedError, UnprocessableEntityError } = Errors
export const {
SinkError,
APIError,
APIConnectionError,
APIConnectionTimeoutError,
APIUserAbortError,
NotFoundError,
ConflictError,
RateLimitError,
BadRequestError,
AuthenticationError,
InternalServerError,
PermissionDeniedError,
UnprocessableEntityError,
} = Errors;

export import toFile = Uploads.toFile;
export import fileFromPath = Uploads.fileFromPath;
Expand Down
Loading

0 comments on commit 0d836ee

Please sign in to comment.