Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Remove some @ts-ignore #2167

Open
wants to merge 4 commits into
base: master
Choose a base branch
from
Open
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
6 changes: 3 additions & 3 deletions src/Error.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
/* eslint-disable camelcase */

import {HttpClientResponseError} from './RequestSender.js';
import {RawErrorType, StripeRawError} from './Types.js';

export const generate = (rawStripeError: StripeRawError): StripeError => {
Expand Down Expand Up @@ -38,7 +39,7 @@ export class StripeError extends Error {
readonly code?: string;
readonly doc_url?: string;
readonly param?: string;
readonly detail?: string | Error;
readonly detail?: string | Error | HttpClientResponseError;
readonly statusCode?: number;
readonly charge?: string;
readonly decline_code?: string;
Expand All @@ -62,8 +63,7 @@ export class StripeError extends Error {
this.headers = raw.headers;
this.requestId = raw.requestId;
this.statusCode = raw.statusCode;
// @ts-ignore
this.message = raw.message;
this.message = raw.message ?? '';

this.charge = raw.charge;
this.decline_code = raw.decline_code;
Expand Down
11 changes: 5 additions & 6 deletions src/RequestSender.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ import {
import {
emitWarning,
normalizeHeaders,
parseHttpHeaderAsNumber,
parseHttpHeaderAsString,
removeNullish,
stringifyRequestData,
} from './utils.js';
Expand Down Expand Up @@ -480,11 +482,10 @@ export class RequestSender {

const requestStartTime = Date.now();

// @ts-ignore
const requestEvent: RequestEvent = removeNullish({
api_version: apiVersion,
account: headers['Stripe-Account'],
idempotency_key: headers['Idempotency-Key'],
account: parseHttpHeaderAsString(headers['Stripe-Account']),
idempotency_key: parseHttpHeaderAsString(headers['Idempotency-Key']),
method,
path,
request_start_time: requestStartTime,
Expand All @@ -503,8 +504,7 @@ export class RequestSender {
apiVersion,
headers,
requestRetries,
// @ts-ignore
res.getHeaders()['retry-after']
parseHttpHeaderAsNumber(res.getHeaders()['retry-after'])
);
} else if (options.streaming && res.getStatusCode() < 400) {
return this._streamingResponseHandler(
Expand Down Expand Up @@ -542,7 +542,6 @@ export class RequestSender {
: RequestSender._generateConnectionErrorMessage(
requestRetries
),
// @ts-ignore
detail: error,
})
);
Expand Down
5 changes: 3 additions & 2 deletions src/Types.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import {
HttpClientResponseInterface,
} from './net/HttpClient.js';
import {PlatformFunctions} from './platform/PlatformFunctions.js';
import {HttpClientResponseError} from './RequestSender.js';

export type AppInfo = {name?: string} & Record<string, unknown>;
export type BufferedFile = {
Expand Down Expand Up @@ -50,7 +51,7 @@ export type RequestEvent = {
method?: string;
path?: string;
request_start_time: number;
usage: Array<string>;
usage?: Array<string>;
};
export type RequestHeaders = Record<string, string | number | string[]>;
export type RequestOptions = {
Expand Down Expand Up @@ -173,7 +174,7 @@ export type StripeRawError = {
doc_url?: string;
decline_code?: string;
param?: string;
detail?: string | Error;
detail?: string | Error | HttpClientResponseError;
charge?: string;
payment_method_type?: string;
payment_intent?: any;
Expand Down
8 changes: 3 additions & 5 deletions src/Webhooks.ts
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ type WebhookSignatureObject = {
};
export type WebhookObject = {
DEFAULT_TOLERANCE: number;
signature: WebhookSignatureObject;
signature: WebhookSignatureObject | null;
constructEvent: (
payload: WebhookPayload,
header: WebhookHeader,
Expand Down Expand Up @@ -75,7 +75,6 @@ export function createWebhooks(
): WebhookObject {
const Webhook: WebhookObject = {
DEFAULT_TOLERANCE: 300, // 5 minutes
// @ts-ignore
signature: null,
constructEvent(
payload: WebhookPayload,
Expand All @@ -86,7 +85,7 @@ export function createWebhooks(
receivedAt: number
): WebhookEvent {
try {
this.signature.verifyHeader(
this.signature?.verifyHeader(
payload,
header,
secret,
Expand Down Expand Up @@ -117,7 +116,7 @@ export function createWebhooks(
cryptoProvider: CryptoProvider,
receivedAt: number
): Promise<WebhookEvent> {
await this.signature.verifyHeaderAsync(
await this.signature?.verifyHeaderAsync(
payload,
header,
secret,
Expand Down Expand Up @@ -394,7 +393,6 @@ export function createWebhooks(
) - details.timestamp;

if (tolerance > 0 && timestampAge > tolerance) {
// @ts-ignore
throw new StripeSignatureVerificationError(header, payload, {
message: 'Timestamp outside the tolerance zone',
});
Expand Down
7 changes: 3 additions & 4 deletions src/net/FetchHttpClient.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import {RequestHeaders, RequestData, ResponseHeaders} from '../Types.js';
import {parseHeadersForFetch} from '../utils.js';
import {
HttpClient,
HttpClientInterface,
Expand Down Expand Up @@ -139,10 +140,8 @@ export class FetchHttpClient extends HttpClient implements HttpClientInterface {
url.toString(),
{
method,
// @ts-ignore
headers,
// @ts-ignore
body,
headers: parseHeadersForFetch(headers),
body: typeof body === 'object' ? JSON.stringify(body) : body,
},
timeout
);
Expand Down
3 changes: 1 addition & 2 deletions src/stripe.core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -242,8 +242,7 @@ export function createStripe(

return accum;
},
// @ts-ignore
undefined
{}
);
},

Expand Down
40 changes: 36 additions & 4 deletions src/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,14 +73,22 @@ export const makeURLInterpolator = ((): ((s: string) => UrlInterpolator) => {
return (str: string): UrlInterpolator => {
const cleanString = str.replace(/["\n\r\u2028\u2029]/g, ($0) => rc[$0]);
return (outputs: Record<string, unknown>): string => {
return cleanString.replace(/\{([\s\S]+?)\}/g, ($0, $1) =>
// @ts-ignore
encodeURIComponent(outputs[$1] || '')
);
return cleanString.replace(/\{([\s\S]+?)\}/g, ($0, $1) => {
const output = outputs[$1];
if (isValidEncodeUriComponentType(output))
return encodeURIComponent(output);
return '';
});
};
};
})();

function isValidEncodeUriComponentType(
value: unknown
): value is number | string | boolean {
return ['number', 'string', 'boolean'].includes(typeof value);
}

export function extractUrlParams(path: string): Array<string> {
const params = path.match(/\{\w+\}/g);
if (!params) {
Expand Down Expand Up @@ -376,3 +384,27 @@ export function concat(arrays: Array<Uint8Array>): Uint8Array {

return merged;
}

export function parseHttpHeaderAsString<K extends keyof RequestHeaders>(
header: RequestHeaders[K]
): string {
if (Array.isArray(header)) {
return header.join(', ');
}
return String(header);
}

export function parseHttpHeaderAsNumber<K extends keyof RequestHeaders>(
header: RequestHeaders[K]
): number {
const number = Array.isArray(header) ? header[0] : header;
return Number(number);
}

export function parseHeadersForFetch(
headers: RequestHeaders
): [string, string][] {
return Object.entries(headers).map(([key, value]) => {
return [key, parseHttpHeaderAsString(value)];
});
}
2 changes: 2 additions & 0 deletions test/utils.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,8 @@ describe('utils', () => {

expect(template({foo: '', baz: ''})).to.equal('/some/url//?ok=1');

expect(template({foo: 0, baz: 't'})).to.equal('/some/url/0/t?ok=1');

expect(
// Test encoding:
template({foo: 'FOO', baz: '__::baz::__'})
Expand Down