wrangler 0.0.0-e95bea2 → 0.0.0-e95e5a0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (93) hide show
  1. package/README.md +25 -14
  2. package/bin/wrangler.js +13 -1
  3. package/miniflare-dist/index.mjs +4886 -0
  4. package/package.json +33 -25
  5. package/pages/functions/buildPlugin.ts +92 -0
  6. package/pages/functions/buildWorker.ts +80 -4
  7. package/pages/functions/filepath-routing.test.ts +136 -25
  8. package/pages/functions/filepath-routing.ts +14 -3
  9. package/pages/functions/routes.ts +6 -1
  10. package/pages/functions/template-plugin.ts +146 -0
  11. package/pages/functions/template-worker.ts +21 -8
  12. package/src/__tests__/config-cache.test.ts +36 -0
  13. package/src/__tests__/configuration.test.ts +1179 -271
  14. package/src/__tests__/dev.test.tsx +382 -25
  15. package/src/__tests__/guess-worker-format.test.ts +28 -1
  16. package/src/__tests__/helpers/mock-account-id.ts +4 -0
  17. package/src/__tests__/helpers/mock-cfetch.ts +5 -1
  18. package/src/__tests__/helpers/mock-console.ts +20 -3
  19. package/src/__tests__/helpers/mock-dialogs.ts +26 -1
  20. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  21. package/src/__tests__/helpers/mock-istty.ts +27 -0
  22. package/src/__tests__/helpers/mock-kv.ts +9 -16
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  24. package/src/__tests__/helpers/run-in-tmp.ts +10 -0
  25. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  26. package/src/__tests__/https-options.test.ts +5 -2
  27. package/src/__tests__/index.test.ts +27 -769
  28. package/src/__tests__/init.test.ts +1516 -0
  29. package/src/__tests__/jest.setup.ts +4 -4
  30. package/src/__tests__/kv.test.ts +172 -126
  31. package/src/__tests__/logger.test.ts +115 -0
  32. package/src/__tests__/pages.test.ts +311 -26
  33. package/src/__tests__/publish.test.ts +2946 -524
  34. package/src/__tests__/r2.test.ts +26 -10
  35. package/src/__tests__/route.test.ts +4 -4
  36. package/src/__tests__/secret.test.ts +55 -34
  37. package/src/__tests__/tail.test.ts +146 -20
  38. package/src/__tests__/user.test.ts +131 -0
  39. package/src/__tests__/whoami.test.tsx +26 -7
  40. package/src/bundle.ts +30 -3
  41. package/src/cfetch/internal.ts +9 -7
  42. package/src/cli.ts +5 -11
  43. package/src/config/README.md +7 -7
  44. package/src/config/config.ts +33 -78
  45. package/src/config/environment.ts +93 -4
  46. package/src/config/index.ts +15 -4
  47. package/src/config/validation-helpers.ts +202 -15
  48. package/src/config/validation.ts +530 -133
  49. package/src/config-cache.ts +45 -0
  50. package/src/create-worker-preview.ts +22 -13
  51. package/src/create-worker-upload-form.ts +32 -9
  52. package/src/dev/dev-vars.ts +36 -0
  53. package/src/dev/dev.tsx +136 -75
  54. package/src/dev/local.tsx +196 -125
  55. package/src/dev/remote.tsx +25 -13
  56. package/src/dev/use-esbuild.ts +23 -5
  57. package/src/dialogs.tsx +16 -6
  58. package/src/entry.ts +119 -11
  59. package/src/environment-variables.ts +3 -1
  60. package/src/errors.ts +11 -0
  61. package/src/https-options.ts +3 -2
  62. package/src/index.tsx +739 -400
  63. package/src/inspect.ts +17 -11
  64. package/src/intl-polyfill.d.ts +139 -0
  65. package/src/{kv/index.tsx → kv.ts} +8 -28
  66. package/src/logger.ts +66 -0
  67. package/src/miniflare-cli/README.md +30 -0
  68. package/src/miniflare-cli/enum-keys.ts +17 -0
  69. package/src/miniflare-cli/index.ts +41 -0
  70. package/src/miniflare-cli/request-context.ts +40 -0
  71. package/src/module-collection.ts +63 -58
  72. package/src/open-in-browser.ts +5 -4
  73. package/src/package-manager.ts +9 -8
  74. package/src/pages.tsx +883 -62
  75. package/src/parse.ts +1 -1
  76. package/src/proxy.ts +32 -21
  77. package/src/publish.ts +276 -161
  78. package/src/sites.tsx +88 -33
  79. package/src/tail/index.ts +2 -2
  80. package/src/tail/printing.ts +13 -8
  81. package/src/update-check.ts +19 -0
  82. package/src/user.tsx +231 -103
  83. package/src/whoami.tsx +2 -1
  84. package/src/worker.ts +15 -6
  85. package/templates/gitignore +171 -0
  86. package/templates/static-asset-facade.js +1 -1
  87. package/wrangler-dist/cli.js +22087 -49340
  88. package/src/__tests__/dev2.test.tsx +0 -152
  89. package/src/__tests__/helpers/mock-user.ts +0 -27
  90. package/src/__tests__/logout.test.ts +0 -50
  91. package/src/__tests__/sentry.test.ts +0 -146
  92. package/src/reporting.ts +0 -131
  93. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,45 @@
1
+ import { mkdirSync, readFileSync, rmSync, writeFileSync } from "fs";
2
+ import { dirname, join } from "path";
3
+
4
+ let cacheMessageShown = false;
5
+
6
+ const cacheFolder = "node_modules/.cache/wrangler";
7
+
8
+ const showCacheMessage = () => {
9
+ if (!cacheMessageShown) {
10
+ console.log(
11
+ `Using cached values in '${cacheFolder}'. This is used as a temporary store to improve the developer experience for some commands. It may be purged at any time. It doesn't contain any sensitive information, but it should not be commited into source control.`
12
+ );
13
+ cacheMessageShown = true;
14
+ }
15
+ };
16
+
17
+ export const getConfigCache = <T>(fileName: string): Partial<T> => {
18
+ try {
19
+ const configCacheLocation = join(cacheFolder, fileName);
20
+ const configCache = JSON.parse(readFileSync(configCacheLocation, "utf-8"));
21
+ showCacheMessage();
22
+ return configCache;
23
+ } catch {
24
+ return {};
25
+ }
26
+ };
27
+
28
+ export const saveToConfigCache = <T>(
29
+ fileName: string,
30
+ newValues: Partial<T>
31
+ ) => {
32
+ const configCacheLocation = join(cacheFolder, fileName);
33
+ const existingValues = getConfigCache(fileName);
34
+
35
+ mkdirSync(dirname(configCacheLocation), { recursive: true });
36
+ writeFileSync(
37
+ configCacheLocation,
38
+ JSON.stringify({ ...existingValues, ...newValues }, null, 2)
39
+ );
40
+ showCacheMessage();
41
+ };
42
+
43
+ export const purgeConfigCaches = () => {
44
+ rmSync(cacheFolder, { recursive: true, force: true });
45
+ };
@@ -2,6 +2,7 @@ import { URL } from "node:url";
2
2
  import { fetch } from "undici";
3
3
  import { fetchResult } from "./cfetch";
4
4
  import { createWorkerUploadForm } from "./create-worker-upload-form";
5
+ import { logger } from "./logger";
5
6
  import type { CfAccount, CfWorkerContext, CfWorkerInit } from "./worker";
6
7
 
7
8
  /**
@@ -57,7 +58,8 @@ export interface CfPreviewToken {
57
58
  */
58
59
  async function sessionToken(
59
60
  account: CfAccount,
60
- ctx: CfWorkerContext
61
+ ctx: CfWorkerContext,
62
+ abortSignal: AbortSignal
61
63
  ): Promise<CfPreviewToken> {
62
64
  const { accountId } = account;
63
65
  const initUrl = ctx.zone
@@ -65,9 +67,9 @@ async function sessionToken(
65
67
  : `/accounts/${accountId}/workers/subdomain/edge-preview`;
66
68
 
67
69
  const { exchange_url } = await fetchResult<{ exchange_url: string }>(initUrl);
68
- const { inspector_websocket, token } = (await (
69
- await fetch(exchange_url)
70
- ).json()) as { inspector_websocket: string; token: string };
70
+ const { inspector_websocket, prewarm, token } = (await (
71
+ await fetch(exchange_url, { signal: abortSignal })
72
+ ).json()) as { inspector_websocket: string; token: string; prewarm: string };
71
73
  const { host } = new URL(inspector_websocket);
72
74
  const query = `cf_workers_preview_token=${token}`;
73
75
 
@@ -75,9 +77,7 @@ async function sessionToken(
75
77
  value: token,
76
78
  host,
77
79
  inspectorUrl: new URL(`${inspector_websocket}?${query}`),
78
- prewarmUrl: new URL(
79
- `https://${host}/cdn-cgi/workers/preview/prewarm?${query}`
80
- ),
80
+ prewarmUrl: new URL(prewarm),
81
81
  };
82
82
  }
83
83
 
@@ -96,11 +96,13 @@ function randomId(): string {
96
96
  async function createPreviewToken(
97
97
  account: CfAccount,
98
98
  worker: CfWorkerInit,
99
- ctx: CfWorkerContext
99
+ ctx: CfWorkerContext,
100
+ abortSignal: AbortSignal
100
101
  ): Promise<CfPreviewToken> {
101
102
  const { value, host, inspectorUrl, prewarmUrl } = await sessionToken(
102
103
  account,
103
- ctx
104
+ ctx,
105
+ abortSignal
104
106
  );
105
107
 
106
108
  const { accountId } = account;
@@ -155,12 +157,19 @@ async function createPreviewToken(
155
157
  export async function createWorkerPreview(
156
158
  init: CfWorkerInit,
157
159
  account: CfAccount,
158
- ctx: CfWorkerContext
160
+ ctx: CfWorkerContext,
161
+ abortSignal: AbortSignal
159
162
  ): Promise<CfPreviewToken> {
160
- const token = await createPreviewToken(account, init, ctx);
161
- const response = await fetch(token.prewarmUrl.href, { method: "POST" });
163
+ const token = await createPreviewToken(account, init, ctx, abortSignal);
164
+ const response = await fetch(token.prewarmUrl.href, {
165
+ method: "POST",
166
+ signal: abortSignal,
167
+ headers: {
168
+ "cf-workers-preview-token": token.value,
169
+ },
170
+ });
162
171
  if (!response.ok) {
163
- // console.error("worker failed to prewarm: ", response.statusText);
172
+ logger.warn("worker failed to prewarm: ", response.statusText);
164
173
  }
165
174
  return token;
166
175
  }
@@ -26,7 +26,7 @@ export function toMimeType(type: CfModuleType): string {
26
26
  export interface WorkerMetadata {
27
27
  /** The name of the entry point module. Only exists when the worker is in the ES module format */
28
28
  main_module?: string;
29
- /** The name of the entry point module. Only exists when the worker is in the Service Worker format */
29
+ /** The name of the entry point module. Only exists when the worker is in the service-worker format */
30
30
  body_part?: string;
31
31
  compatibility_date?: string;
32
32
  compatibility_flags?: string[];
@@ -38,6 +38,7 @@ export interface WorkerMetadata {
38
38
  | { type: "json"; name: string; json: unknown }
39
39
  | { type: "wasm_module"; name: string; part: string }
40
40
  | { type: "text_blob"; name: string; part: string }
41
+ | { type: "data_blob"; name: string; part: string }
41
42
  | {
42
43
  type: "durable_object_namespace";
43
44
  name: string;
@@ -133,6 +134,21 @@ export function createWorkerUploadForm(worker: CfWorkerInit): FormData {
133
134
  }
134
135
  }
135
136
 
137
+ for (const [name, filePath] of Object.entries(bindings.data_blobs || {})) {
138
+ metadataBindings.push({
139
+ name,
140
+ type: "data_blob",
141
+ part: name,
142
+ });
143
+
144
+ formData.set(
145
+ name,
146
+ new File([readFileSync(filePath)], filePath, {
147
+ type: "application/octet-stream",
148
+ })
149
+ );
150
+ }
151
+
136
152
  if (main.type === "commonjs") {
137
153
  // This is a service-worker format worker.
138
154
  for (const module of Object.values([...(modules || [])])) {
@@ -146,8 +162,12 @@ export function createWorkerUploadForm(worker: CfWorkerInit): FormData {
146
162
  );
147
163
  // And then remove it from the modules collection
148
164
  modules = modules?.filter((m) => m !== module);
149
- } else if (module.type === "compiled-wasm" || module.type === "text") {
150
- // Convert all wasm/text modules into `wasm_module`/`text_blob` bindings.
165
+ } else if (
166
+ module.type === "compiled-wasm" ||
167
+ module.type === "text" ||
168
+ module.type === "buffer"
169
+ ) {
170
+ // Convert all wasm/text/data modules into `wasm_module`/`text_blob`/`data_blob` bindings.
151
171
  // The "name" of the module is a file path. We use it
152
172
  // to instead be a "part" of the body, and a reference
153
173
  // that we can use inside our source. This identifier has to be a valid
@@ -156,7 +176,12 @@ export function createWorkerUploadForm(worker: CfWorkerInit): FormData {
156
176
  const name = module.name.replace(/[^a-zA-Z0-9_$]/g, "_");
157
177
  metadataBindings.push({
158
178
  name,
159
- type: module.type === "compiled-wasm" ? "wasm_module" : "text_blob",
179
+ type:
180
+ module.type === "compiled-wasm"
181
+ ? "wasm_module"
182
+ : module.type === "text"
183
+ ? "text_blob"
184
+ : "data_blob",
160
185
  part: name,
161
186
  });
162
187
 
@@ -167,15 +192,13 @@ export function createWorkerUploadForm(worker: CfWorkerInit): FormData {
167
192
  type:
168
193
  module.type === "compiled-wasm"
169
194
  ? "application/wasm"
170
- : "text/plain",
195
+ : module.type === "text"
196
+ ? "text/plain"
197
+ : "application/octet-stream",
171
198
  })
172
199
  );
173
200
  // And then remove it from the modules collection
174
201
  modules = modules?.filter((m) => m !== module);
175
- } else if (module.type === "buffer") {
176
- throw new Error(
177
- 'The "buffer" module type is not yet supported in service worker format workers'
178
- );
179
202
  }
180
203
  }
181
204
  }
@@ -0,0 +1,36 @@
1
+ import * as fs from "node:fs";
2
+ import * as path from "node:path";
3
+ import dotenv from "dotenv";
4
+ import { logger } from "../logger";
5
+ import type { Config } from "../config";
6
+
7
+ /**
8
+ * Get the Worker `vars` bindings for a `wrangler dev` instance of a Worker.
9
+ *
10
+ * The `vars` bindings can be specified in the `wrangler.toml` configuration file.
11
+ * But "secret" `vars` are usually only provided at the server -
12
+ * either by creating them in the Dashboard UI, or using the `wrangler secret` command.
13
+ *
14
+ * It is useful during development, to provide these types of variable locally.
15
+ * When running `wrangler dev` we will look for a file called `.dev.vars`, situated
16
+ * next to the `wrangler.toml` file (or in the current working directory if there is no
17
+ * `wrangler.toml`).
18
+ *
19
+ * Any values in this file, formatted like a `dotenv` file, will add to or override `vars`
20
+ * bindings provided in the `wrangler.toml`.
21
+ */
22
+ export function getVarsForDev(config: Config): Config["vars"] {
23
+ const configDir = path.resolve(path.dirname(config.configPath ?? "."));
24
+ const devVarsPath = path.resolve(configDir, ".dev.vars");
25
+ if (fs.existsSync(devVarsPath)) {
26
+ const devVarsRelativePath = path.relative(process.cwd(), devVarsPath);
27
+ logger.log(`Using vars defined in ${devVarsRelativePath}`);
28
+ const devVars = dotenv.parse(fs.readFileSync(devVarsPath, "utf8"));
29
+ return {
30
+ ...config.vars,
31
+ ...devVars,
32
+ };
33
+ } else {
34
+ return config.vars;
35
+ }
36
+ }
package/src/dev/dev.tsx CHANGED
@@ -2,15 +2,15 @@ import { spawn } from "node:child_process";
2
2
  import { watch } from "chokidar";
3
3
  import clipboardy from "clipboardy";
4
4
  import commandExists from "command-exists";
5
- import { Box, Text, useApp, useInput } from "ink";
5
+ import { Box, Text, useApp, useInput, useStdin } from "ink";
6
6
  import React, { useState, useEffect, useRef } from "react";
7
7
  import { withErrorBoundary, useErrorHandler } from "react-error-boundary";
8
8
  import onExit from "signal-exit";
9
9
  import tmp from "tmp-promise";
10
10
  import { fetch } from "undici";
11
11
  import { runCustomBuild } from "../entry";
12
+ import { logger } from "../logger";
12
13
  import openInBrowser from "../open-in-browser";
13
- import { reportError } from "../reporting";
14
14
  import { getAPIToken } from "../user";
15
15
  import { Local } from "./local";
16
16
  import { Remote } from "./remote";
@@ -19,30 +19,36 @@ import type { Config } from "../config";
19
19
  import type { Entry } from "../entry";
20
20
  import type { AssetPaths } from "../sites";
21
21
  import type { CfWorkerInit } from "../worker";
22
+ import type { EsbuildBundle } from "./use-esbuild";
22
23
 
23
24
  export type DevProps = {
24
25
  name?: string;
25
26
  entry: Entry;
26
- port?: number;
27
+ port: number;
28
+ ip: string;
27
29
  inspectorPort: number;
28
30
  rules: Config["rules"];
29
- accountId: undefined | string;
31
+ accountId: string | undefined;
30
32
  initialMode: "local" | "remote";
31
- jsxFactory: undefined | string;
32
- jsxFragment: undefined | string;
33
+ jsxFactory: string | undefined;
34
+ jsxFragment: string | undefined;
35
+ tsconfig: string | undefined;
33
36
  upstreamProtocol: "https" | "http";
34
37
  localProtocol: "https" | "http";
35
38
  enableLocalPersistence: boolean;
36
39
  bindings: CfWorkerInit["bindings"];
37
- public: undefined | string;
38
- assetPaths: undefined | AssetPaths;
39
- compatibilityDate: undefined | string;
40
- compatibilityFlags: undefined | string[];
41
- usageModel: undefined | "bundled" | "unbound";
42
- buildCommand: {
43
- command?: undefined | string;
44
- cwd?: undefined | string;
45
- watch_dir?: undefined | string;
40
+ crons: Config["triggers"]["crons"];
41
+ public: string | undefined;
42
+ assetPaths: AssetPaths | undefined;
43
+ compatibilityDate: string;
44
+ compatibilityFlags: string[] | undefined;
45
+ usageModel: "bundled" | "unbound" | undefined;
46
+ minify: boolean | undefined;
47
+ nodeCompat: boolean | undefined;
48
+ build: {
49
+ command?: string | undefined;
50
+ cwd?: string | undefined;
51
+ watch_dir?: string | undefined;
46
52
  };
47
53
  env: string | undefined;
48
54
  legacyEnv: boolean;
@@ -55,15 +61,14 @@ export type DevProps = {
55
61
  };
56
62
 
57
63
  export function DevImplementation(props: DevProps): JSX.Element {
58
- const port = props.port ?? 8787;
59
64
  const apiToken = props.initialMode === "remote" ? getAPIToken() : undefined;
60
65
  const directory = useTmpDir();
61
66
 
62
- useCustomBuild(props.entry, props.buildCommand);
67
+ useCustomBuild(props.entry, props.build);
63
68
 
64
69
  if (props.public && props.entry.format === "service-worker") {
65
70
  throw new Error(
66
- "You cannot use the service worker format with a `public` directory."
71
+ "You cannot use the service-worker format with a `public` directory."
67
72
  );
68
73
  }
69
74
 
@@ -75,7 +80,13 @@ export function DevImplementation(props: DevProps): JSX.Element {
75
80
 
76
81
  if (props.bindings.text_blobs && props.entry.format === "modules") {
77
82
  throw new Error(
78
- "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[build.upload.rules]` in your wrangler.toml"
83
+ "You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
84
+ );
85
+ }
86
+
87
+ if (props.bindings.data_blobs && props.entry.format === "modules") {
88
+ throw new Error(
89
+ "You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
79
90
  );
80
91
  }
81
92
 
@@ -87,14 +98,38 @@ export function DevImplementation(props: DevProps): JSX.Element {
87
98
  rules: props.rules,
88
99
  jsxFragment: props.jsxFragment,
89
100
  serveAssetsFromWorker: !!props.public,
101
+ tsconfig: props.tsconfig,
102
+ minify: props.minify,
103
+ nodeCompat: props.nodeCompat,
90
104
  });
91
105
 
106
+ // only load the UI if we're running in a supported environment
107
+ const { isRawModeSupported } = useStdin();
108
+ return isRawModeSupported ? (
109
+ <InteractiveDevSession {...props} bundle={bundle} apiToken={apiToken} />
110
+ ) : (
111
+ <DevSession
112
+ {...props}
113
+ bundle={bundle}
114
+ apiToken={apiToken}
115
+ local={props.initialMode === "local"}
116
+ />
117
+ );
118
+ }
119
+
120
+ type InteractiveDevSessionProps = DevProps & {
121
+ apiToken: string | undefined;
122
+ bundle: EsbuildBundle | undefined;
123
+ };
124
+
125
+ function InteractiveDevSession(props: InteractiveDevSessionProps) {
92
126
  const toggles = useHotkeys(
93
127
  {
94
128
  local: props.initialMode === "local",
95
129
  tunnel: false,
96
130
  },
97
- port,
131
+ props.port,
132
+ props.ip,
98
133
  props.inspectorPort,
99
134
  props.localProtocol
100
135
  );
@@ -103,51 +138,67 @@ export function DevImplementation(props: DevProps): JSX.Element {
103
138
 
104
139
  return (
105
140
  <>
106
- {toggles.local ? (
107
- <Local
108
- name={props.name}
109
- bundle={bundle}
110
- format={props.entry.format}
111
- bindings={props.bindings}
112
- assetPaths={props.assetPaths}
113
- public={props.public}
114
- port={port}
115
- rules={props.rules}
116
- inspectorPort={props.inspectorPort}
117
- enableLocalPersistence={props.enableLocalPersistence}
118
- />
119
- ) : (
120
- <Remote
121
- name={props.name}
122
- bundle={bundle}
123
- format={props.entry.format}
124
- accountId={props.accountId}
125
- apiToken={apiToken}
126
- bindings={props.bindings}
127
- assetPaths={props.assetPaths}
128
- public={props.public}
129
- port={port}
130
- localProtocol={props.localProtocol}
131
- inspectorPort={props.inspectorPort}
132
- compatibilityDate={props.compatibilityDate}
133
- compatibilityFlags={props.compatibilityFlags}
134
- usageModel={props.usageModel}
135
- env={props.env}
136
- legacyEnv={props.legacyEnv}
137
- zone={props.zone}
138
- />
139
- )}
141
+ <DevSession {...props} local={toggles.local} />
140
142
  <Box borderStyle="round" paddingLeft={1} paddingRight={1}>
141
- <Text>
142
- {`B to open a browser, D to open Devtools, L to ${
143
- toggles.local ? "turn off" : "turn on"
144
- } local mode, X to exit`}
145
- </Text>
143
+ <Text bold={true}>[b]</Text>
144
+ <Text> open a browser, </Text>
145
+ <Text bold={true}>[d]</Text>
146
+ <Text> open Devtools, </Text>
147
+ <Text bold={true}>[l]</Text>
148
+ <Text> {toggles.local ? "turn off" : "turn on"} local mode, </Text>
149
+ <Text bold={true}>[c]</Text>
150
+ <Text> clear console, </Text>
151
+ <Text bold={true}>[x]</Text>
152
+ <Text> to exit</Text>
146
153
  </Box>
147
154
  </>
148
155
  );
149
156
  }
150
157
 
158
+ type DevSessionProps = InteractiveDevSessionProps & { local: boolean };
159
+
160
+ function DevSession(props: DevSessionProps) {
161
+ return props.local ? (
162
+ <Local
163
+ name={props.name}
164
+ bundle={props.bundle}
165
+ format={props.entry.format}
166
+ compatibilityDate={props.compatibilityDate}
167
+ compatibilityFlags={props.compatibilityFlags}
168
+ bindings={props.bindings}
169
+ assetPaths={props.assetPaths}
170
+ public={props.public}
171
+ port={props.port}
172
+ ip={props.ip}
173
+ rules={props.rules}
174
+ inspectorPort={props.inspectorPort}
175
+ enableLocalPersistence={props.enableLocalPersistence}
176
+ crons={props.crons}
177
+ />
178
+ ) : (
179
+ <Remote
180
+ name={props.name}
181
+ bundle={props.bundle}
182
+ format={props.entry.format}
183
+ accountId={props.accountId}
184
+ apiToken={props.apiToken}
185
+ bindings={props.bindings}
186
+ assetPaths={props.assetPaths}
187
+ public={props.public}
188
+ port={props.port}
189
+ ip={props.ip}
190
+ localProtocol={props.localProtocol}
191
+ inspectorPort={props.inspectorPort}
192
+ compatibilityDate={props.compatibilityDate}
193
+ compatibilityFlags={props.compatibilityFlags}
194
+ usageModel={props.usageModel}
195
+ env={props.env}
196
+ legacyEnv={props.legacyEnv}
197
+ zone={props.zone}
198
+ />
199
+ );
200
+ }
201
+
151
202
  export interface DirectorySyncResult {
152
203
  name: string;
153
204
  removeCallback: () => void;
@@ -163,7 +214,9 @@ function useTmpDir(): string | undefined {
163
214
  setDirectory(dir);
164
215
  return;
165
216
  } catch (err) {
166
- console.error("failed to create tmp dir");
217
+ logger.error(
218
+ "Failed to create temporary directory to store built files."
219
+ );
167
220
  handleError(err);
168
221
  }
169
222
  return () => {
@@ -176,9 +229,9 @@ function useTmpDir(): string | undefined {
176
229
  function useCustomBuild(
177
230
  expectedEntry: Entry,
178
231
  build: {
179
- command?: undefined | string;
180
- cwd?: undefined | string;
181
- watch_dir?: undefined | string;
232
+ command?: string | undefined;
233
+ cwd?: string | undefined;
234
+ watch_dir?: string | undefined;
182
235
  }
183
236
  ): void {
184
237
  useEffect(() => {
@@ -190,9 +243,9 @@ function useCustomBuild(
190
243
  ignoreInitial: true,
191
244
  }).on("all", (_event, filePath) => {
192
245
  //TODO: we should buffer requests to the proxy until this completes
193
- console.log(`The file ${filePath} changed, restarting build...`);
246
+ logger.log(`The file ${filePath} changed, restarting build...`);
194
247
  runCustomBuild(expectedEntry.file, build).catch((err) => {
195
- console.error("Custom build failed:", err);
248
+ logger.error("Custom build failed:", err);
196
249
  });
197
250
  });
198
251
  }
@@ -239,12 +292,12 @@ function useTunnel(toggle: boolean) {
239
292
  try {
240
293
  await commandExists("cloudflared");
241
294
  } catch (e) {
242
- console.error(
295
+ logger.warn(
243
296
  "To share your worker on the Internet, please install `cloudflared` from https://developers.cloudflare.com/cloudflare-one/connections/connect-apps/install-and-setup/installation"
244
297
  );
245
298
  return;
246
299
  }
247
- console.log("⎔ Starting a tunnel...");
300
+ logger.log("⎔ Starting a tunnel...");
248
301
  tunnel.current = spawn("cloudflared", [
249
302
  "tunnel",
250
303
  "--url",
@@ -255,30 +308,29 @@ function useTunnel(toggle: boolean) {
255
308
 
256
309
  tunnel.current.on("close", (code) => {
257
310
  if (code) {
258
- console.log(`Tunnel process exited with code ${code}`);
311
+ logger.log(`Tunnel process exited with code ${code}`);
259
312
  }
260
313
  });
261
314
 
262
315
  removeSignalExitListener.current = onExit((_code, _signal) => {
263
- console.log("⎔ Shutting down local tunnel.");
316
+ logger.log("⎔ Shutting down local tunnel.");
264
317
  tunnel.current?.kill();
265
318
  tunnel.current = undefined;
266
319
  });
267
320
 
268
321
  const hostName = await findTunnelHostname();
269
322
  await clipboardy.write(hostName);
270
- console.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
323
+ logger.log(`⬣ Sharing at ${hostName}, copied to clipboard.`);
271
324
  }
272
325
  }
273
326
 
274
327
  startTunnel().catch(async (err) => {
275
- console.error("tunnel:", err);
276
- await reportError(err);
328
+ logger.error("tunnel:", err);
277
329
  });
278
330
 
279
331
  return () => {
280
332
  if (tunnel.current) {
281
- console.log("⎔ Shutting down tunnel.");
333
+ logger.log("⎔ Shutting down tunnel.");
282
334
  tunnel.current?.kill();
283
335
  tunnel.current = undefined;
284
336
  removeSignalExitListener.current && removeSignalExitListener.current();
@@ -295,11 +347,13 @@ type useHotkeysInitialState = {
295
347
  function useHotkeys(
296
348
  initial: useHotkeysInitialState,
297
349
  port: number,
350
+ ip: string,
298
351
  inspectorPort: number,
299
352
  localProtocol: "http" | "https"
300
353
  ) {
301
354
  // UGH, we should put port in context instead
302
355
  const [toggles, setToggles] = useState(initial);
356
+ const { exit } = useApp();
303
357
  useInput(
304
358
  async (
305
359
  input,
@@ -307,9 +361,16 @@ function useHotkeys(
307
361
  key
308
362
  ) => {
309
363
  switch (input.toLowerCase()) {
364
+ // clear console
365
+ case "c":
366
+ console.clear();
367
+ // This console.log causes Ink to re-render the `DevSession` component.
368
+ // Couldn't find a better way to tell it to do so...
369
+ console.log();
370
+ break;
310
371
  // open browser
311
372
  case "b": {
312
- await openInBrowser(`${localProtocol}://localhost:${port}`);
373
+ await openInBrowser(`${localProtocol}://${ip}:${port}`);
313
374
  break;
314
375
  }
315
376
  // toggle inspector
@@ -330,7 +391,7 @@ function useHotkeys(
330
391
  // shut down
331
392
  case "q":
332
393
  case "x":
333
- process.exit(0);
394
+ exit();
334
395
  break;
335
396
  default:
336
397
  // nothing?