Skip to content

Commit

Permalink
chore: enable strict in tsconfig.json (#456)
Browse files Browse the repository at this point in the history
In the march towards full strictness, this enables `strict` in `tsconfig.json` and fixes the errors it pops up. A changeset is included because there are some subtle code changes, and we should leave a trail for them.
  • Loading branch information
threepointone authored Feb 15, 2022
1 parent 88a39c7 commit b5f42c5
Show file tree
Hide file tree
Showing 20 changed files with 132 additions and 65 deletions.
7 changes: 7 additions & 0 deletions .changeset/modern-owls-begin.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"wrangler": patch
---

chore: enable `strict` in `tsconfig.json`

In the march towards full strictness, this enables `strict` in `tsconfig.json` and fixes the errors it pops up. A changeset is included because there are some subtle code changes, and we should leave a trail for them.
6 changes: 6 additions & 0 deletions packages/wrangler/src/__tests__/helpers/command-exists.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module "command-exists" {
/**
* Detect whether a command exists on the system.
*/
export default function commandExists(cmd: string): Promise<void>;
}
6 changes: 6 additions & 0 deletions packages/wrangler/src/__tests__/helpers/faye-websocket.d.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
module "faye-websocket" {
/**
* Standards-compliant WebSocket client and server.
*/
export default WebSocket;
}
5 changes: 4 additions & 1 deletion packages/wrangler/src/__tests__/helpers/mock-bin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,10 @@ const nodeShebang = "#!/usr/bin/env node";
/**
* Create a binary file in a temp directory and make it available on the PATH.
*/
export async function mockBinary(binaryName: string, code: string) {
export async function mockBinary(
binaryName: string,
code: string
): Promise<() => void> {
// Ensure there is a directory to put the mock binary in.
const tmpDir = resolve(mkdtempSync(".mock-binary-"));

Expand Down
8 changes: 5 additions & 3 deletions packages/wrangler/src/__tests__/helpers/run-wrangler.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,10 @@ import { normalizeSlashes, stripTimings } from "./mock-console";
export async function runWrangler(cmd?: string) {
try {
await main(cmd?.split(" ") ?? []);
} catch (e) {
e.message = normalizeSlashes(stripTimings(e.message));
throw e;
} catch (err) {
if (err instanceof Error) {
err.message = normalizeSlashes(stripTimings(err.message));
}
throw err;
}
}
6 changes: 4 additions & 2 deletions packages/wrangler/src/__tests__/kv.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@ import { mockConsoleMethods } from "./helpers/mock-console";
import { mockKeyListRequest } from "./helpers/mock-kv";
import { runInTempDir } from "./helpers/run-in-tmp";
import { runWrangler } from "./helpers/run-wrangler";
import type { KVNamespaceInfo } from "../kv";
import type { KVNamespaceInfo, NamespaceKeyInfo } from "../kv";

describe("wrangler", () => {
mockAccountId();
Expand Down Expand Up @@ -839,7 +839,9 @@ describe("wrangler", () => {
"kv:key list --namespace-id some-namespace-id --limit 100"
);
expect(std.err).toMatchInlineSnapshot(`""`);
expect(JSON.parse(std.out).map((k) => k.name)).toEqual(keys);
expect(
JSON.parse(std.out).map((k: NamespaceKeyInfo) => k.name)
).toEqual(keys);
expect(requests.count).toEqual(6);
});
});
Expand Down
4 changes: 2 additions & 2 deletions packages/wrangler/src/__tests__/package-manager.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ describe("getPackageManager()", () => {
* Create a fake yarn binary
*/
function mockYarn(succeed: boolean): void {
let unMock;
let unMock: () => void;
beforeEach(async () => {
unMock = await mockBinary("yarn", `process.exit(${succeed ? 0 : 1})`);
});
Expand All @@ -162,7 +162,7 @@ function mockYarn(succeed: boolean): void {
* Create a fake npm binary
*/
function mockNpm(succeed: boolean): void {
let unMock;
let unMock: () => void;
beforeEach(async () => {
unMock = await mockBinary("npm", `process.exit(${succeed ? 0 : 1})`);
});
Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/src/__tests__/publish.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -321,7 +321,7 @@ export default{

expect(std.out).toMatchInlineSnapshot(`""`);
expect(std.err).toMatchInlineSnapshot(`
"A [site] definition requires a \`bucket\` field with a path to the site's public directory.
"AssertionError [ERR_ASSERTION]: A [site] definition requires a \`bucket\` field with a path to the site's public directory.
%s
If you think this is a bug then please create an issue at https://github.com/cloudflare/wrangler2/issues/new."
Expand Down
6 changes: 3 additions & 3 deletions packages/wrangler/src/__tests__/secret.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -54,7 +54,7 @@ describe("wrangler secret", () => {
try {
await runWrangler("secret put the-key");
} catch (e) {
error = e;
error = e as Error;
}
expect(std.out).toMatchInlineSnapshot(`""`);
expect(std.err).toMatchInlineSnapshot(`
Expand Down Expand Up @@ -120,7 +120,7 @@ describe("wrangler secret", () => {
try {
await runWrangler("secret delete the-key");
} catch (e) {
error = e;
error = e as Error;
}
expect(std.out).toMatchInlineSnapshot(`""`);
expect(std.err).toMatchInlineSnapshot(`
Expand Down Expand Up @@ -186,7 +186,7 @@ describe("wrangler secret", () => {
try {
await runWrangler("secret list");
} catch (e) {
error = e;
error = e as Error;
}
expect(std.out).toMatchInlineSnapshot(`""`);
expect(std.err).toMatchInlineSnapshot(`
Expand Down
5 changes: 4 additions & 1 deletion packages/wrangler/src/api/worker.ts
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ export interface CfDurableObjectMigrations {
new_tag: string;
steps: {
new_classes?: string[];
renamed_classes?: string[];
renamed_classes?: {
from: string;
to: string;
}[];
deleted_classes?: string[];
}[];
}
Expand Down
11 changes: 8 additions & 3 deletions packages/wrangler/src/cfetch/internal.ts
Original file line number Diff line number Diff line change
Expand Up @@ -42,7 +42,9 @@ export async function fetchInternal<ResponseType>(
}
}

function cloneHeaders(headers: HeadersInit | undefined): HeadersInit {
function cloneHeaders(
headers: HeadersInit | undefined
): Record<string, string> {
return { ...headers };
}

Expand All @@ -61,8 +63,11 @@ function requireApiToken(): string {
return apiToken;
}

function addAuthorizationHeader(headers: HeadersInit, apiToken: string): void {
if (headers["Authorization"]) {
function addAuthorizationHeader(
headers: Record<string, string>,
apiToken: string
): void {
if ("Authorization" in headers) {
throw new Error(
"The request already specifies an authorisation header - cannot add a new one."
);
Expand Down
12 changes: 9 additions & 3 deletions packages/wrangler/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -535,7 +535,13 @@ export function normaliseAndValidateEnvironmentsConfig(config: Config) {
);

// Fall back on "inherited fields" from the config, if not specified in the environment.
const inheritedFields = [

type InheritedField = keyof Omit<
Config,
"env" | "migrations" | "wasm_modules" | "site" | "dev"
>;

const inheritedFields: InheritedField[] = [
"name",
"account_id",
"workers_dev",
Expand All @@ -546,15 +552,15 @@ export function normaliseAndValidateEnvironmentsConfig(config: Config) {
"route",
"jsx_factory",
"jsx_fragment",
"site",
"triggers",
"usage_model",
];

for (const inheritedField of inheritedFields) {
if (config[inheritedField] !== undefined) {
if (environment[inheritedField] === undefined) {
environment[inheritedField] = config[inheritedField]; // TODO: - shallow or deep copy?
(environment[inheritedField] as typeof environment[InheritedField]) =
config[inheritedField]; // TODO: - shallow or deep copy?
}
}
}
Expand Down
14 changes: 8 additions & 6 deletions packages/wrangler/src/dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import type { CfModule, CfWorkerInit, CfScriptFormat } from "./api/worker";
import type { Entry } from "./bundle";
import type { AssetPaths } from "./sites";
import type { WatchMode } from "esbuild";
import type { ExecaChildProcess } from "execa";
import type { DirectoryResult } from "tmp-promise";

export type DevProps = {
Expand Down Expand Up @@ -454,7 +455,8 @@ function useCustomBuild(
const { command, cwd, watch_dir } = props;
useEffect(() => {
if (!command) return;
let cmd, interval;
let cmd: ExecaChildProcess<string> | undefined,
interval: NodeJS.Timeout | undefined;
console.log("running:", command);
cmd = execaCommand(command, {
...(cwd && { cwd }),
Expand All @@ -467,7 +469,7 @@ function useCustomBuild(
"all",
(_event, filePath) => {
console.log(`The file ${filePath} changed, restarting build...`);
cmd.kill();
cmd?.kill();
cmd = execaCommand(command, {
...(cwd && { cwd }),
shell: true,
Expand All @@ -494,7 +496,7 @@ function useCustomBuild(
}

if (fileExists === true) {
clearInterval(interval);
interval && clearInterval(interval);
setEntry(expectedEntry);
} else {
const elapsed = Date.now() - startedAt;
Expand All @@ -503,8 +505,8 @@ function useCustomBuild(
console.error(
`⎔ Build timed out, Could not resolve ${expectedEntry.file}`
);
clearInterval(interval);
cmd.kill();
interval && clearInterval(interval);
cmd?.kill();
}
}
}, 200);
Expand All @@ -514,7 +516,7 @@ function useCustomBuild(
cmd.kill();
cmd = undefined;
}
clearInterval(interval);
interval && clearInterval(interval);
interval = undefined;
};
}, [command, cwd, expectedEntry, watch_dir]);
Expand Down
18 changes: 12 additions & 6 deletions packages/wrangler/src/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -111,7 +111,7 @@ ${TOML.stringify({

if (configPath && "wasm_modules" in config) {
// rewrite wasm_module paths to be absolute
const modules = {};
const modules: Record<string, string> = {};
for (const [name, filePath] of Object.entries(config.wasm_modules || {})) {
modules[name] = path.relative(
process.cwd(),
Expand Down Expand Up @@ -332,7 +332,7 @@ export async function main(argv: string[]): Promise<void> {
// TODO: suggest next steps?
} catch (err) {
throw new Error(
`Failed to create wrangler.toml.\n${err.message ?? err}`
`Failed to create wrangler.toml.\n${(err as Error).message ?? err}`
);
}
}
Expand Down Expand Up @@ -1373,6 +1373,7 @@ export async function main(argv: string[]): Promise<void> {
try {
await submitSecret();
} catch (e) {
// @ts-expect-error non-standard property on Error
if (e.code === 10007) {
// upload a draft worker
await fetchResult(
Expand Down Expand Up @@ -1724,7 +1725,8 @@ export async function main(argv: string[]): Promise<void> {
id = getNamespaceId(args, config);
} catch (e) {
throw new CommandLineArgsError(
"Not able to delete namespace.\n" + e.message
"Not able to delete namespace.\n" +
((e as Error).message ?? e)
);
}

Expand Down Expand Up @@ -2140,7 +2142,9 @@ export async function main(argv: string[]): Promise<void> {
parsedContent = JSON.parse(content);
} catch (err) {
throw new Error(
`Could not parse json from ${filename}.\n${err.message ?? err}`
`Could not parse json from ${filename}.\n${
(err as Error).message ?? err
}`
);
}

Expand Down Expand Up @@ -2224,7 +2228,9 @@ export async function main(argv: string[]): Promise<void> {
parsedContent = JSON.parse(content);
} catch (err) {
throw new Error(
`Could not parse json from ${filename}.\n${err.message ?? err}`
`Could not parse json from ${filename}.\n${
(err as Error).message ?? err
}`
);
}

Expand Down Expand Up @@ -2431,7 +2437,7 @@ export async function main(argv: string[]): Promise<void> {
console.error(""); // Just adds a bit of space
console.error(e.message);
} else {
console.error(e.message);
console.error(e instanceof Error ? e.message : e);
console.error(""); // Just adds a bit of space
console.error(
`${fgGreenColor}%s${resetColor}`,
Expand Down
6 changes: 5 additions & 1 deletion packages/wrangler/src/inspect.ts
Original file line number Diff line number Diff line change
Expand Up @@ -367,7 +367,10 @@ export default function useInspector(props: InspectorProps) {
);
remoteWebSocket.send(event.data);
} catch (e) {
if (e.message !== "WebSocket is not open: readyState 0 (CONNECTING)") {
if (
(e as Error).message !==
"WebSocket is not open: readyState 0 (CONNECTING)"
) {
/**
* ^ this just means we haven't opened a websocket yet
* usually happens until there's at least one request
Expand Down Expand Up @@ -587,6 +590,7 @@ function logConsoleMessage(evt: Protocol.Runtime.ConsoleAPICalledEvent): void {
const method = mapConsoleAPIMessageTypeToConsoleMethod[evt.type];

if (method in console) {
// @ts-expect-error - we know this is a valid method
// eslint-disable-next-line prefer-spread
console[method].apply(console, args);
} else {
Expand Down
11 changes: 6 additions & 5 deletions packages/wrangler/src/pages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -795,8 +795,8 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {

let miniflareArgs: MiniflareOptions = {};

let scriptReadyResolve;
const scriptReadyPromise = new Promise(
let scriptReadyResolve: () => void;
const scriptReadyPromise = new Promise<void>(
(resolve) => (scriptReadyResolve = resolve)
);

Expand Down Expand Up @@ -830,7 +830,8 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
scriptPath,
};
} else {
scriptReadyResolve();
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
scriptReadyResolve!();

const scriptPath =
directory !== undefined
Expand Down Expand Up @@ -900,7 +901,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {

// env.ASSETS.fetch
serviceBindings: {
async ASSETS(request) {
async ASSETS(request: Request) {
if (proxyPort) {
try {
const url = new URL(request.url);
Expand Down Expand Up @@ -962,7 +963,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
miniflare.dispose().catch((err) => miniflare.log.error(err));
});
} catch (e) {
miniflare.log.error(e);
miniflare.log.error(e as Error);
EXIT("Could not start Miniflare.", 1);
}
}
Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/src/publish.ts
Original file line number Diff line number Diff line change
Expand Up @@ -222,7 +222,7 @@ export default async function publish(props: Props): Promise<void> {
type: bundleType,
},
bindings,
...(migrations && { migrations }),
migrations,
modules,
compatibility_date: config.compatibility_date,
compatibility_flags: config.compatibility_flags,
Expand Down
2 changes: 1 addition & 1 deletion packages/wrangler/src/sites.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -129,7 +129,7 @@ export async function syncAssets(
const result = await listNamespaceKeys(accountId, namespace);
const keys = new Set(result.map((x) => x.name));

const manifest = {};
const manifest: Record<string, string> = {};
const upload: {
key: string;
value: string;
Expand Down
Loading

0 comments on commit b5f42c5

Please sign in to comment.