From 2899c19ccb72ece7953ac2cc18463e659f3caf4d Mon Sep 17 00:00:00 2001 From: Pete Bacon Darwin Date: Sat, 15 Jan 2022 11:14:27 +0000 Subject: [PATCH] Refactor miscellaneous source files to pass strict-null checks --- packages/wrangler/src/__tests__/kv.test.ts | 12 ++++++++-- packages/wrangler/src/api/form_data.ts | 2 +- packages/wrangler/src/cfetch/internal.ts | 12 ++++------ packages/wrangler/src/kv.tsx | 27 ++++++++++++++-------- packages/wrangler/src/sites.tsx | 6 ++++- packages/wrangler/src/user.tsx | 18 ++++++++------- 6 files changed, 48 insertions(+), 29 deletions(-) diff --git a/packages/wrangler/src/__tests__/kv.test.ts b/packages/wrangler/src/__tests__/kv.test.ts index 88af107985f8..ea55f744a69b 100644 --- a/packages/wrangler/src/__tests__/kv.test.ts +++ b/packages/wrangler/src/__tests__/kv.test.ts @@ -335,8 +335,16 @@ describe("wrangler", () => { expect(namespaceId).toEqual(expectedNamespaceId); expect(key).toEqual(expectedKey); expect(body).toEqual(expectedValue); - expect(query.get("expiration")).toEqual(`${expiration}`); - expect(query.get("expiration_ttl")).toEqual(`${expirationTtl}`); + if (expiration !== undefined) { + expect(query.get("expiration")).toEqual(`${expiration}`); + } else { + expect(query.has("expiration")).toBe(false); + } + if (expirationTtl) { + expect(query.get("expiration_ttl")).toEqual(`${expirationTtl}`); + } else { + expect(query.has("expiration_ttl")).toBe(false); + } return null; } ); diff --git a/packages/wrangler/src/api/form_data.ts b/packages/wrangler/src/api/form_data.ts index 90a3fb4fad9b..51eebb282db6 100644 --- a/packages/wrangler/src/api/form_data.ts +++ b/packages/wrangler/src/api/form_data.ts @@ -23,7 +23,7 @@ export function toMimeType(type: CfModuleType): string { } } -function toModule(module: CfModule, entryType?: CfModuleType): Blob { +function toModule(module: CfModule, entryType: CfModuleType): Blob { const { type: moduleType, content } = module; const type = toMimeType(moduleType ?? entryType); diff --git a/packages/wrangler/src/cfetch/internal.ts b/packages/wrangler/src/cfetch/internal.ts index d77163e404c9..f7bdeae7d349 100644 --- a/packages/wrangler/src/cfetch/internal.ts +++ b/packages/wrangler/src/cfetch/internal.ts @@ -1,5 +1,5 @@ -import fetch from "node-fetch"; -import type { RequestInit, HeadersInit } from "node-fetch"; +import fetch, { Headers } from "node-fetch"; +import type { RequestInit } from "node-fetch"; import { getAPIToken, loginOrRefreshIfRequired } from "../user"; export const CF_API_BASE_URL = @@ -21,7 +21,7 @@ export async function fetchInternal( ): Promise { await requireLoggedIn(); const apiToken = requireApiToken(); - const headers = cloneHeaders(init.headers); + const headers = new Headers(init.headers); addAuthorizationHeader(headers, apiToken); const queryString = queryParams ? `?${queryParams.toString()}` : ""; @@ -55,11 +55,7 @@ function requireApiToken(): string { return apiToken; } -function cloneHeaders(headers: HeadersInit): HeadersInit { - return { ...headers }; -} - -function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void { +function addAuthorizationHeader(headers: Headers, apiToken: string): void { if (headers["Authorization"]) { throw new Error( "The request already specifies an authorisation header - cannot add a new one." diff --git a/packages/wrangler/src/kv.tsx b/packages/wrangler/src/kv.tsx index 8b84033baf58..edd28be1ef5d 100644 --- a/packages/wrangler/src/kv.tsx +++ b/packages/wrangler/src/kv.tsx @@ -82,7 +82,7 @@ export interface NamespaceKeyInfo { export async function listNamespaceKeys( accountId: string, namespaceId: string, - prefix?: string + prefix = "" ) { return await fetchListResult( `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys`, @@ -98,15 +98,20 @@ export async function putKeyValue( value: string, args?: { expiration?: number; expiration_ttl?: number } ) { + let searchParams: URLSearchParams | undefined; + if (args) { + searchParams = new URLSearchParams(); + if (args.expiration) { + searchParams.set("expiration", `${args.expiration}`); + } + if (args.expiration_ttl) { + searchParams.set("expiration_ttl", `${args.expiration_ttl}`); + } + } return await fetchResult( `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`, { method: "PUT", body: value }, - args - ? new URLSearchParams({ - expiration: args.expiration?.toString(), - expiration_ttl: args.expiration_ttl?.toString(), - }) - : undefined + searchParams ); } @@ -262,6 +267,10 @@ export function getNamespaceId({ /** * KV namespace binding names must be valid JS identifiers. */ -export function isValidNamespaceBinding(binding: string): boolean { - return /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(binding); +export function isValidNamespaceBinding( + binding: string | undefined +): binding is string { + return ( + typeof binding === "string" && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(binding) + ); } diff --git a/packages/wrangler/src/sites.tsx b/packages/wrangler/src/sites.tsx index 1d9a00d48771..5580f3b401dc 100644 --- a/packages/wrangler/src/sites.tsx +++ b/packages/wrangler/src/sites.tsx @@ -89,7 +89,11 @@ export async function syncAssets( ); const manifest = {}; - const upload = []; + const upload: { + key: string; + value: string; + base64: boolean; + }[] = []; // TODO: this can be more efficient by parallelising for await (const file of getFilesInFolder(dirPath)) { // TODO: "exclude:" config diff --git a/packages/wrangler/src/user.tsx b/packages/wrangler/src/user.tsx index 39b471b14fc8..98b1ccecd772 100644 --- a/packages/wrangler/src/user.tsx +++ b/packages/wrangler/src/user.tsx @@ -298,9 +298,9 @@ let initialised = false; // we do this because we have some async stuff // TODO: this should just happen in the top level -// abd we should fiure out how to do top level await +// and we should figure out how to do top level await export async function initialise(): Promise { - // get refreshtoken/accesstoken from fs if exists + // get refreshToken/accessToken from fs if exists try { // if CF_API_TOKEN available, use that if (process.env.CF_API_TOKEN) { @@ -350,7 +350,9 @@ export function getAPIToken(): string { } throwIfNotInitialised(); - return LocalState.accessToken?.value; + // `throwIfNotInitialised()` ensures that the accessToken is guaranteed to be defined. + // eslint-disable-next-line @typescript-eslint/no-non-null-assertion + return LocalState.accessToken!.value; } interface AccessContext { @@ -971,14 +973,14 @@ export async function getAccountId() { }); } catch (err) { // probably offline + return; } - if (!response) return; - let accountId: string; - // @ts-expect-error need to type this response - const responseJSON: { + + let accountId: string | undefined; + const responseJSON = (await response.json()) as { success: boolean; result: { id: string; account: { id: string; name: string } }[]; - } = await response.json(); + }; if (responseJSON.success === true) { if (responseJSON.result.length === 1) {