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

fix: don't crash when browser windows don't open #415

Merged
merged 1 commit into from
Feb 9, 2022
Merged
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
7 changes: 7 additions & 0 deletions .changeset/healthy-monkeys-count.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
"wrangler": patch
---

fix: don't crash when browser windows don't open

We open browser windows for a few things; during `wrangler dev`, and logging in. There are environments where this doesn't work as expected (like codespaces, stackblitz, etc). This fix simply logs an error instead of breaking the flow. This is the same fix as https://github.com/cloudflare/wrangler2/pull/263, now applied to the rest of wrangler.
12 changes: 7 additions & 5 deletions packages/wrangler/src/dev.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@ import commandExists from "command-exists";
import * as esbuild from "esbuild";
import { execaCommand } from "execa";
import { Box, Text, useApp, useInput } from "ink";
import open from "open";
import React, { useState, useEffect, useRef } from "react";
import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
import onExit from "signal-exit";
Expand All @@ -19,6 +18,7 @@ import { createWorker } from "./api/worker";
import guessWorkerFormat from "./guess-worker-format";
import useInspector from "./inspect";
import makeModuleCollector from "./module-collection";
import openInBrowser from "./open-in-brower";
import { usePreviewServer, waitForPortToBeAvailable } from "./proxy";
import { syncAssets } from "./sites";
import { getAPIToken } from "./user";
Expand Down Expand Up @@ -804,15 +804,17 @@ function useHotkeys(initial: useHotkeysInitialState, port: number) {
) => {
switch (input.toLowerCase()) {
// open browser
case "b":
await open(`http://localhost:${port}/`);
case "b": {
await openInBrowser(`http://localhost:${port}`);
break;
}
// toggle inspector
case "d":
await open(
case "d": {
await openInBrowser(
`https://built-devtools.pages.dev/js_app?experiments=true&v8only=true&ws=localhost:9229/ws`
);
break;
}
// toggle tunnel
case "s":
setToggles((previousToggles) => ({
Expand Down
13 changes: 13 additions & 0 deletions packages/wrangler/src/open-in-brower.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import open from "open";
/**
* An extremely simple wrapper around the open command.
* Specifically, it adds an 'error' event handler so that when this function
* is called in environments where we can't open the browser (e.g. github codespaces,
* stackblitz, remote servers), it doesn't just crash the process.
*/
export default async function openInBrowser(url: string): Promise<void> {
const childProcess = await open(url);
childProcess.on("error", () => {
console.warn(`Failed to open ${url} in a browser`);
});
}
6 changes: 2 additions & 4 deletions packages/wrangler/src/pages.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,10 @@ import { join } from "node:path";
import { URL } from "node:url";
import { watch } from "chokidar";
import { getType } from "mime";
import open from "open";
import { buildWorker } from "../pages/functions/buildWorker";
import { generateConfigFromFileTree } from "../pages/functions/filepath-routing";
import { writeRoutesModule } from "../pages/functions/routes";
import openInBrowser from "./open-in-brower";
import { toUrlPath } from "./paths";
import type { Config } from "../pages/functions/routes";
import type { Headers, Request, fetch } from "@miniflare/core";
Expand Down Expand Up @@ -945,9 +945,7 @@ export const pages: BuilderCallback<unknown, unknown> = (yargs) => {
console.log(`Serving at http://localhost:${port}/`);

if (process.env.BROWSER !== "none") {
const childProcess = await open(`http://localhost:${port}/`);
// fail silently if the open command doesn't work (e.g. in GitHub Codespaces)
childProcess.on("error", (_err) => {});
await openInBrowser(`http://localhost:${port}/`);
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@GregBrimble ^ I also replaced pages' usage of open(), fyi.

}

if (directory !== undefined && liveReload) {
Expand Down
12 changes: 6 additions & 6 deletions packages/wrangler/src/user.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -218,10 +218,10 @@ import TOML from "@iarna/toml";
import { render, Text } from "ink";
import SelectInput from "ink-select-input";
import Table from "ink-table";
import open from "open";
import React from "react";
import { fetch } from "undici";
import { CF_API_BASE_URL } from "./cfetch";
import openInBrowser from "./open-in-brower";
import type { ParsedUrlQuery } from "node:querystring";
import type { Response } from "undici";

Expand Down Expand Up @@ -804,18 +804,18 @@ export async function loginOrRefreshIfRequired(): Promise<boolean> {

export async function login(props?: LoginProps): Promise<boolean> {
const urlToOpen = await getAuthURL(props?.scopes);
await open(urlToOpen);
// TODO: log url only if on system where it's unreliable/unavailable
// console.log(`💁 Opened ${urlToOpen}`);
await openInBrowser(urlToOpen);
let server;
let loginTimeoutHandle;
const timerPromise = new Promise<boolean>((resolve) => {
loginTimeoutHandle = setTimeout(() => {
console.error("Timed out waiting for authorization code.");
console.error(
"Timed out waiting for authorization code, please try again."
);
server.close();
clearTimeout(loginTimeoutHandle);
resolve(false);
}, 60000); // wait for 30 seconds for the user to authorize
}, 60000); // wait for 60 seconds for the user to authorize
});

const loginPromise = new Promise<boolean>((resolve, reject) => {
Expand Down