wrangler 2.0.12 → 2.0.16

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 (149) hide show
  1. package/README.md +7 -1
  2. package/bin/wrangler.js +111 -57
  3. package/miniflare-dist/index.mjs +9 -2
  4. package/package.json +156 -154
  5. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  6. package/src/__tests__/config-cache.test.ts +30 -24
  7. package/src/__tests__/configuration.test.ts +3935 -3476
  8. package/src/__tests__/dev.test.tsx +1128 -979
  9. package/src/__tests__/guess-worker-format.test.ts +68 -68
  10. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  11. package/src/__tests__/helpers/faye-websocket.d.ts +4 -4
  12. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  13. package/src/__tests__/helpers/mock-bin.ts +20 -20
  14. package/src/__tests__/helpers/mock-cfetch.ts +92 -92
  15. package/src/__tests__/helpers/mock-console.ts +49 -39
  16. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  17. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  18. package/src/__tests__/helpers/mock-istty.ts +65 -18
  19. package/src/__tests__/helpers/mock-kv.ts +26 -26
  20. package/src/__tests__/helpers/mock-oauth-flow.ts +223 -228
  21. package/src/__tests__/helpers/mock-process.ts +39 -0
  22. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  23. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  24. package/src/__tests__/helpers/run-in-tmp.ts +27 -27
  25. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  26. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  27. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  28. package/src/__tests__/https-options.test.ts +104 -104
  29. package/src/__tests__/index.test.ts +239 -234
  30. package/src/__tests__/init.test.ts +1605 -1250
  31. package/src/__tests__/jest.setup.ts +63 -33
  32. package/src/__tests__/kv.test.ts +1128 -1011
  33. package/src/__tests__/logger.test.ts +100 -74
  34. package/src/__tests__/package-manager.test.ts +303 -303
  35. package/src/__tests__/pages.test.ts +1152 -652
  36. package/src/__tests__/parse.test.ts +252 -252
  37. package/src/__tests__/publish.test.ts +6371 -5622
  38. package/src/__tests__/pubsub.test.ts +367 -0
  39. package/src/__tests__/r2.test.ts +133 -133
  40. package/src/__tests__/route.test.ts +18 -18
  41. package/src/__tests__/secret.test.ts +382 -377
  42. package/src/__tests__/tail.test.ts +530 -530
  43. package/src/__tests__/user.test.ts +123 -111
  44. package/src/__tests__/whoami.test.tsx +198 -117
  45. package/src/__tests__/worker-namespace.test.ts +327 -0
  46. package/src/abort.d.ts +1 -1
  47. package/src/api/dev.ts +49 -0
  48. package/src/api/index.ts +1 -0
  49. package/src/bundle-reporter.tsx +29 -0
  50. package/src/bundle.ts +157 -149
  51. package/src/cfetch/index.ts +80 -80
  52. package/src/cfetch/internal.ts +90 -83
  53. package/src/cli.ts +21 -7
  54. package/src/config/config.ts +204 -195
  55. package/src/config/diagnostics.ts +61 -61
  56. package/src/config/environment.ts +390 -357
  57. package/src/config/index.ts +206 -193
  58. package/src/config/validation-helpers.ts +366 -366
  59. package/src/config/validation.ts +1573 -1376
  60. package/src/config-cache.ts +79 -41
  61. package/src/create-worker-preview.ts +206 -136
  62. package/src/create-worker-upload-form.ts +247 -238
  63. package/src/dev/dev-vars.ts +13 -13
  64. package/src/dev/dev.tsx +329 -307
  65. package/src/dev/local.tsx +304 -275
  66. package/src/dev/remote.tsx +366 -224
  67. package/src/dev/use-esbuild.ts +126 -91
  68. package/src/dev.tsx +538 -0
  69. package/src/dialogs.tsx +97 -97
  70. package/src/durable.ts +87 -87
  71. package/src/entry.ts +234 -228
  72. package/src/environment-variables.ts +23 -23
  73. package/src/errors.ts +6 -6
  74. package/src/generate.ts +33 -0
  75. package/src/git-client.ts +42 -0
  76. package/src/https-options.ts +79 -79
  77. package/src/index.tsx +1775 -2763
  78. package/src/init.ts +549 -0
  79. package/src/inspect.ts +593 -593
  80. package/src/intl-polyfill.d.ts +123 -123
  81. package/src/is-interactive.ts +12 -0
  82. package/src/kv.ts +277 -277
  83. package/src/logger.ts +46 -39
  84. package/src/miniflare-cli/enum-keys.ts +8 -8
  85. package/src/miniflare-cli/index.ts +42 -31
  86. package/src/miniflare-cli/request-context.ts +18 -18
  87. package/src/module-collection.ts +212 -212
  88. package/src/open-in-browser.ts +4 -6
  89. package/src/package-manager.ts +123 -123
  90. package/src/pages/build.tsx +202 -0
  91. package/src/pages/constants.ts +7 -0
  92. package/src/pages/deployments.tsx +101 -0
  93. package/src/pages/dev.tsx +964 -0
  94. package/src/pages/functions/buildPlugin.ts +105 -0
  95. package/src/pages/functions/buildWorker.ts +151 -0
  96. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  97. package/src/pages/functions/filepath-routing.ts +189 -0
  98. package/src/pages/functions/identifiers.ts +78 -0
  99. package/src/pages/functions/routes.ts +151 -0
  100. package/src/pages/index.tsx +84 -0
  101. package/src/pages/projects.tsx +157 -0
  102. package/src/pages/publish.tsx +335 -0
  103. package/src/pages/types.ts +40 -0
  104. package/src/pages/upload.tsx +384 -0
  105. package/src/pages/utils.ts +12 -0
  106. package/src/parse.ts +202 -138
  107. package/src/paths.ts +6 -6
  108. package/src/preview.ts +31 -0
  109. package/src/proxy.ts +400 -402
  110. package/src/publish.ts +667 -621
  111. package/src/pubsub/index.ts +286 -0
  112. package/src/pubsub/pubsub-commands.tsx +577 -0
  113. package/src/r2.ts +19 -19
  114. package/src/selfsigned.d.ts +23 -23
  115. package/src/sites.tsx +271 -225
  116. package/src/tail/filters.ts +108 -108
  117. package/src/tail/index.ts +217 -217
  118. package/src/tail/printing.ts +45 -45
  119. package/src/update-check.ts +11 -11
  120. package/src/user/choose-account.tsx +60 -0
  121. package/src/user/env-vars.ts +46 -0
  122. package/src/user/generate-auth-url.ts +33 -0
  123. package/src/user/generate-random-state.ts +16 -0
  124. package/src/user/index.ts +3 -0
  125. package/src/user/user.tsx +1161 -0
  126. package/src/whoami.tsx +61 -42
  127. package/src/worker-namespace.ts +190 -0
  128. package/src/worker.ts +110 -100
  129. package/src/zones.ts +39 -36
  130. package/templates/checked-fetch.js +17 -0
  131. package/templates/new-worker-scheduled.js +3 -3
  132. package/templates/new-worker-scheduled.ts +15 -15
  133. package/templates/new-worker.js +3 -3
  134. package/templates/new-worker.ts +15 -15
  135. package/templates/no-op-worker.js +10 -0
  136. package/templates/pages-template-plugin.ts +155 -0
  137. package/templates/pages-template-worker.ts +161 -0
  138. package/templates/static-asset-facade.js +31 -31
  139. package/templates/tsconfig.json +95 -95
  140. package/wrangler-dist/cli.js +55383 -54138
  141. package/pages/functions/buildPlugin.ts +0 -105
  142. package/pages/functions/buildWorker.ts +0 -151
  143. package/pages/functions/filepath-routing.ts +0 -189
  144. package/pages/functions/identifiers.ts +0 -78
  145. package/pages/functions/routes.ts +0 -156
  146. package/pages/functions/template-plugin.ts +0 -147
  147. package/pages/functions/template-worker.ts +0 -143
  148. package/src/pages.tsx +0 -2093
  149. package/src/user.tsx +0 -1214
@@ -1,240 +1,382 @@
1
1
  import { readFile } from "node:fs/promises";
2
2
  import path from "node:path";
3
- import { useState, useEffect, useRef } from "react";
4
- import { createWorkerPreview } from "../create-worker-preview";
3
+ import React, { useState, useEffect, useRef } from "react";
4
+ import { useErrorHandler } from "react-error-boundary";
5
+ import { printBundleSize } from "../bundle-reporter";
6
+ import {
7
+ createPreviewSession,
8
+ createWorkerPreview,
9
+ } from "../create-worker-preview";
5
10
  import useInspector from "../inspect";
6
11
  import { logger } from "../logger";
7
12
  import { usePreviewServer } from "../proxy";
8
13
  import { syncAssets } from "../sites";
9
- import { requireApiToken, requireAuth } from "../user";
10
- import type { CfPreviewToken } from "../create-worker-preview";
14
+ import {
15
+ ChooseAccount,
16
+ getAccountChoices,
17
+ requireApiToken,
18
+ saveAccountToCache,
19
+ } from "../user";
20
+ import type { Route } from "../config/environment";
21
+ import type {
22
+ CfPreviewToken,
23
+ CfPreviewSession,
24
+ } from "../create-worker-preview";
11
25
  import type { AssetPaths } from "../sites";
12
- import type { CfModule, CfWorkerInit, CfScriptFormat } from "../worker";
26
+ import type { ChooseAccountItem } from "../user";
27
+ import type {
28
+ CfModule,
29
+ CfWorkerInit,
30
+ CfScriptFormat,
31
+ CfAccount,
32
+ CfWorkerContext,
33
+ } from "../worker";
13
34
  import type { EsbuildBundle } from "./use-esbuild";
14
35
 
15
36
  export function Remote(props: {
16
- name: string | undefined;
17
- bundle: EsbuildBundle | undefined;
18
- format: CfScriptFormat | undefined;
19
- public: string | undefined;
20
- assetPaths: AssetPaths | undefined;
21
- port: number;
22
- ip: string;
23
- localProtocol: "https" | "http";
24
- inspectorPort: number;
25
- accountId: string | undefined;
26
- bindings: CfWorkerInit["bindings"];
27
- compatibilityDate: string;
28
- compatibilityFlags: string[] | undefined;
29
- usageModel: "bundled" | "unbound" | undefined;
30
- env: string | undefined;
31
- legacyEnv: boolean | undefined;
32
- zone: string | undefined;
33
- host: string | undefined;
37
+ name: string | undefined;
38
+ bundle: EsbuildBundle | undefined;
39
+ format: CfScriptFormat | undefined;
40
+ isWorkersSite: boolean;
41
+ assetPaths: AssetPaths | undefined;
42
+ port: number;
43
+ ip: string;
44
+ localProtocol: "https" | "http";
45
+ inspectorPort: number;
46
+ accountId: string | undefined;
47
+ bindings: CfWorkerInit["bindings"];
48
+ compatibilityDate: string;
49
+ compatibilityFlags: string[] | undefined;
50
+ usageModel: "bundled" | "unbound" | undefined;
51
+ env: string | undefined;
52
+ legacyEnv: boolean | undefined;
53
+ zone: string | undefined;
54
+ host: string | undefined;
55
+ routes: Route[] | undefined;
56
+ onReady?: () => void;
34
57
  }) {
35
- const previewToken = useWorker({
36
- name: props.name,
37
- bundle: props.bundle,
38
- format: props.format,
39
- modules: props.bundle ? props.bundle.modules : [],
40
- accountId: props.accountId,
41
- bindings: props.bindings,
42
- assetPaths: props.assetPaths,
43
- public: props.public,
44
- port: props.port,
45
- compatibilityDate: props.compatibilityDate,
46
- compatibilityFlags: props.compatibilityFlags,
47
- usageModel: props.usageModel,
48
- env: props.env,
49
- legacyEnv: props.legacyEnv,
50
- zone: props.zone,
51
- host: props.host,
52
- });
53
-
54
- usePreviewServer({
55
- previewToken,
56
- publicRoot: props.public,
57
- localProtocol: props.localProtocol,
58
- localPort: props.port,
59
- ip: props.ip,
60
- });
61
-
62
- useInspector({
63
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
64
- port: props.inspectorPort,
65
- logToTerminal: true,
66
- });
67
- return null;
58
+ const [accountId, setAccountId] = useState(props.accountId);
59
+ const accountChoicesRef = useRef<Promise<ChooseAccountItem[]>>();
60
+ const [accountChoices, setAccountChoices] = useState<ChooseAccountItem[]>();
61
+
62
+ const previewToken = useWorker({
63
+ name: props.name,
64
+ bundle: props.bundle,
65
+ format: props.format,
66
+ modules: props.bundle ? props.bundle.modules : [],
67
+ accountId,
68
+ bindings: props.bindings,
69
+ assetPaths: props.assetPaths,
70
+ isWorkersSite: props.isWorkersSite,
71
+ port: props.port,
72
+ compatibilityDate: props.compatibilityDate,
73
+ compatibilityFlags: props.compatibilityFlags,
74
+ usageModel: props.usageModel,
75
+ env: props.env,
76
+ legacyEnv: props.legacyEnv,
77
+ zone: props.zone,
78
+ host: props.host,
79
+ routes: props.routes,
80
+ onReady: props.onReady,
81
+ });
82
+
83
+ usePreviewServer({
84
+ previewToken,
85
+ assetDirectory: props.isWorkersSite
86
+ ? undefined
87
+ : props.assetPaths?.assetDirectory,
88
+ localProtocol: props.localProtocol,
89
+ localPort: props.port,
90
+ ip: props.ip,
91
+ });
92
+
93
+ useInspector({
94
+ inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
95
+ port: props.inspectorPort,
96
+ logToTerminal: true,
97
+ });
98
+
99
+ const errorHandler = useErrorHandler();
100
+
101
+ // This effect handles the async step of fetching the available accounts for the current user.
102
+ // If only one account is available then it is just used by calling `setAccountId()`.
103
+ useEffect(() => {
104
+ if (
105
+ accountChoicesRef.current !== undefined ||
106
+ props.accountId !== undefined
107
+ ) {
108
+ return;
109
+ }
110
+ accountChoicesRef.current = getAccountChoices();
111
+ accountChoicesRef.current.then(
112
+ (accounts) => {
113
+ if (accounts.length === 1) {
114
+ saveAccountToCache({
115
+ id: accounts[0].id,
116
+ name: accounts[0].name,
117
+ });
118
+ setAccountId(accounts[0].id);
119
+ } else {
120
+ setAccountChoices(accounts);
121
+ }
122
+ },
123
+ (err) => {
124
+ errorHandler(err);
125
+ }
126
+ );
127
+ });
128
+
129
+ // If we have not already chosen an account and there are multiple accounts available
130
+ // allow the users to select one.
131
+ return accountId === undefined && accountChoices !== undefined ? (
132
+ <ChooseAccount
133
+ accounts={accountChoices}
134
+ onSelect={(selectedAccount) => {
135
+ saveAccountToCache(selectedAccount);
136
+ setAccountId(selectedAccount.id);
137
+ }}
138
+ onError={(err) => errorHandler(err)}
139
+ ></ChooseAccount>
140
+ ) : null;
68
141
  }
69
142
 
70
143
  export function useWorker(props: {
71
- name: string | undefined;
72
- bundle: EsbuildBundle | undefined;
73
- format: CfScriptFormat | undefined;
74
- modules: CfModule[];
75
- accountId: string | undefined;
76
- bindings: CfWorkerInit["bindings"];
77
- assetPaths: AssetPaths | undefined;
78
- public: string | undefined;
79
- port: number;
80
- compatibilityDate: string | undefined;
81
- compatibilityFlags: string[] | undefined;
82
- usageModel: "bundled" | "unbound" | undefined;
83
- env: string | undefined;
84
- legacyEnv: boolean | undefined;
85
- zone: string | undefined;
86
- host: string | undefined;
144
+ name: string | undefined;
145
+ bundle: EsbuildBundle | undefined;
146
+ format: CfScriptFormat | undefined;
147
+ modules: CfModule[];
148
+ accountId: string | undefined;
149
+ bindings: CfWorkerInit["bindings"];
150
+ assetPaths: AssetPaths | undefined;
151
+ isWorkersSite: boolean;
152
+ port: number;
153
+ compatibilityDate: string | undefined;
154
+ compatibilityFlags: string[] | undefined;
155
+ usageModel: "bundled" | "unbound" | undefined;
156
+ env: string | undefined;
157
+ legacyEnv: boolean | undefined;
158
+ zone: string | undefined;
159
+ host: string | undefined;
160
+ routes: Route[] | undefined;
161
+ onReady?: () => void;
87
162
  }): CfPreviewToken | undefined {
88
- const {
89
- name,
90
- bundle,
91
- format,
92
- modules,
93
- accountId,
94
- bindings,
95
- assetPaths,
96
- compatibilityDate,
97
- compatibilityFlags,
98
- usageModel,
99
- port,
100
- } = props;
101
- const [token, setToken] = useState<CfPreviewToken | undefined>();
102
-
103
- // This is the most reliable way to detect whether
104
- // something's "happened" in our system; We make a ref and
105
- // mark it once we log our initial message. Refs are vars!
106
- const startedRef = useRef(false);
107
- // This ref holds the actual accountId being used, the `accountId` prop could be undefined
108
- // as it is only what is retrieved from the wrangler.toml config.
109
- const accountIdRef = useRef(accountId);
110
-
111
- useEffect(() => {
112
- const abortController = new AbortController();
113
- async function start() {
114
- setToken(undefined); // reset token in case we're re-running
115
-
116
- if (!bundle || !format) return;
117
-
118
- if (!startedRef.current) {
119
- startedRef.current = true;
120
- } else {
121
- logger.log("⎔ Detected changes, restarted server.");
122
- }
123
-
124
- // Ensure we have an account id, even if it means logging in here.
125
- accountIdRef.current = await requireAuth({
126
- account_id: accountIdRef.current,
127
- });
128
-
129
- const assets = await syncAssets(
130
- accountIdRef.current,
131
- // When we're using the newer service environments, we wouldn't
132
- // have added the env name on to the script name. However, we must
133
- // include it in the kv namespace name regardless (since there's no
134
- // concept of service environments for kv namespaces yet).
135
- name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
136
- props.public ? undefined : assetPaths,
137
- true,
138
- false
139
- ); // TODO: cancellable?
140
-
141
- const content = await readFile(bundle.path, "utf-8");
142
-
143
- const init: CfWorkerInit = {
144
- name,
145
- main: {
146
- name: path.basename(bundle.path),
147
- type: format === "modules" ? "esm" : "commonjs",
148
- content,
149
- },
150
- modules: modules.concat(
151
- assets.manifest
152
- ? {
153
- name: "__STATIC_CONTENT_MANIFEST",
154
- content: JSON.stringify(assets.manifest),
155
- type: "text",
156
- }
157
- : []
158
- ),
159
- bindings: {
160
- ...bindings,
161
- kv_namespaces: (bindings.kv_namespaces || []).concat(
162
- assets.namespace
163
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
164
- : []
165
- ),
166
- text_blobs: {
167
- ...bindings.text_blobs,
168
- ...(assets.manifest &&
169
- format === "service-worker" && {
170
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
171
- }),
172
- },
173
- },
174
- migrations: undefined, // no migrations in dev
175
- compatibility_date: compatibilityDate,
176
- compatibility_flags: compatibilityFlags,
177
- usage_model: usageModel,
178
- };
179
- setToken(
180
- await createWorkerPreview(
181
- init,
182
- {
183
- accountId: accountIdRef.current,
184
- apiToken: requireApiToken(),
185
- },
186
- {
187
- env: props.env,
188
- legacyEnv: props.legacyEnv,
189
- zone: props.zone,
190
- host: props.host,
191
- },
192
- abortController.signal
193
- )
194
- );
195
- }
196
- start().catch((err) => {
197
- // we want to log the error, but not end the process
198
- // since it could recover after the developer fixes whatever's wrong
199
- if ((err as { code: string }).code !== "ABORT_ERR") {
200
- // instead of logging the raw API error to the user,
201
- // give them friendly instructions
202
- // for error 10063 (workers.dev subdomain required)
203
- if (err.code === 10063) {
204
- const errorMessage =
205
- "Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
206
- const solutionMessage =
207
- "You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
208
- const onboardingLink = `https://dash.cloudflare.com/${accountIdRef.current}/workers/onboarding`;
209
- logger.error(
210
- `${errorMessage}\n${solutionMessage}\n${onboardingLink}`
211
- );
212
- } else {
213
- logger.error("Error on remote worker:", err);
214
- }
215
- }
216
- });
217
-
218
- return () => {
219
- abortController.abort();
220
- };
221
- }, [
222
- name,
223
- bundle,
224
- format,
225
- accountId,
226
- port,
227
- assetPaths,
228
- props.public,
229
- compatibilityDate,
230
- compatibilityFlags,
231
- usageModel,
232
- bindings,
233
- modules,
234
- props.env,
235
- props.legacyEnv,
236
- props.zone,
237
- props.host,
238
- ]);
239
- return token;
163
+ const {
164
+ name,
165
+ bundle,
166
+ format,
167
+ modules,
168
+ accountId,
169
+ bindings,
170
+ assetPaths,
171
+ compatibilityDate,
172
+ compatibilityFlags,
173
+ usageModel,
174
+ port,
175
+ onReady,
176
+ } = props;
177
+ const [session, setSession] = useState<CfPreviewSession | undefined>();
178
+ const [token, setToken] = useState<CfPreviewToken | undefined>();
179
+
180
+ // This is the most reliable way to detect whether
181
+ // something's "happened" in our system; We make a ref and
182
+ // mark it once we log our initial message. Refs are vars!
183
+ const startedRef = useRef(false);
184
+
185
+ // This effect sets up the preview session
186
+ useEffect(() => {
187
+ const abortController = new AbortController();
188
+ async function start() {
189
+ if (accountId === undefined) {
190
+ return;
191
+ }
192
+
193
+ const workerAccount: CfAccount = {
194
+ accountId,
195
+ apiToken: requireApiToken(),
196
+ };
197
+
198
+ const workerCtx: CfWorkerContext = {
199
+ env: props.env,
200
+ legacyEnv: props.legacyEnv,
201
+ zone: props.zone,
202
+ host: props.host,
203
+ routes: props.routes,
204
+ };
205
+
206
+ setSession(
207
+ await createPreviewSession(
208
+ workerAccount,
209
+ workerCtx,
210
+ abortController.signal
211
+ )
212
+ );
213
+ }
214
+ start().catch((err) => {
215
+ // we want to log the error, but not end the process
216
+ // since it could recover after the developer fixes whatever's wrong
217
+ if ((err as { code: string }).code !== "ABORT_ERR") {
218
+ logger.error("Error while creating remote dev session:", err);
219
+ }
220
+ });
221
+
222
+ return () => {
223
+ abortController.abort();
224
+ };
225
+ }, [
226
+ accountId,
227
+ props.env,
228
+ props.host,
229
+ props.legacyEnv,
230
+ props.routes,
231
+ props.zone,
232
+ ]);
233
+
234
+ // This effect uses the session to upload the worker and create a preview
235
+ useEffect(() => {
236
+ const abortController = new AbortController();
237
+ async function start() {
238
+ if (accountId === undefined) {
239
+ return;
240
+ }
241
+ if (session === undefined) {
242
+ return;
243
+ }
244
+ setToken(undefined); // reset token in case we're re-running
245
+
246
+ if (!bundle || !format) return;
247
+
248
+ if (!startedRef.current) {
249
+ startedRef.current = true;
250
+ } else {
251
+ logger.log("⎔ Detected changes, restarted server.");
252
+ }
253
+
254
+ const content = await readFile(bundle.path, "utf-8");
255
+
256
+ // TODO: For Dev we could show the reporter message in the interactive box.
257
+ void printBundleSize(
258
+ { name: path.basename(bundle.path), content: content },
259
+ modules
260
+ );
261
+
262
+ const assets = await syncAssets(
263
+ accountId,
264
+ // When we're using the newer service environments, we wouldn't
265
+ // have added the env name on to the script name. However, we must
266
+ // include it in the kv namespace name regardless (since there's no
267
+ // concept of service environments for kv namespaces yet).
268
+ name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
269
+ props.isWorkersSite ? assetPaths : undefined,
270
+ true,
271
+ false
272
+ ); // TODO: cancellable?
273
+
274
+ const init: CfWorkerInit = {
275
+ name,
276
+ main: {
277
+ name: path.basename(bundle.path),
278
+ type: format === "modules" ? "esm" : "commonjs",
279
+ content,
280
+ },
281
+ modules: modules.concat(
282
+ assets.manifest
283
+ ? {
284
+ name: "__STATIC_CONTENT_MANIFEST",
285
+ content: JSON.stringify(assets.manifest),
286
+ type: "text",
287
+ }
288
+ : []
289
+ ),
290
+ bindings: {
291
+ ...bindings,
292
+ kv_namespaces: (bindings.kv_namespaces || []).concat(
293
+ assets.namespace
294
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
295
+ : []
296
+ ),
297
+ text_blobs: {
298
+ ...bindings.text_blobs,
299
+ ...(assets.manifest &&
300
+ format === "service-worker" && {
301
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
302
+ }),
303
+ },
304
+ },
305
+ migrations: undefined, // no migrations in dev
306
+ compatibility_date: compatibilityDate,
307
+ compatibility_flags: compatibilityFlags,
308
+ usage_model: usageModel,
309
+ };
310
+
311
+ const workerAccount: CfAccount = {
312
+ accountId,
313
+ apiToken: requireApiToken(),
314
+ };
315
+
316
+ const workerCtx: CfWorkerContext = {
317
+ env: props.env,
318
+ legacyEnv: props.legacyEnv,
319
+ zone: props.zone,
320
+ host: props.host,
321
+ routes: props.routes,
322
+ };
323
+
324
+ setToken(
325
+ await createWorkerPreview(
326
+ init,
327
+ workerAccount,
328
+ workerCtx,
329
+ session,
330
+ abortController.signal
331
+ )
332
+ );
333
+ onReady?.();
334
+ }
335
+ start().catch((err) => {
336
+ // we want to log the error, but not end the process
337
+ // since it could recover after the developer fixes whatever's wrong
338
+ if ((err as { code: string }).code !== "ABORT_ERR") {
339
+ // instead of logging the raw API error to the user,
340
+ // give them friendly instructions
341
+ // for error 10063 (workers.dev subdomain required)
342
+ if (err.code === 10063) {
343
+ const errorMessage =
344
+ "Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
345
+ const solutionMessage =
346
+ "You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
347
+ const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
348
+ logger.error(
349
+ `${errorMessage}\n${solutionMessage}\n${onboardingLink}`
350
+ );
351
+ } else {
352
+ logger.error("Error on remote worker:", err);
353
+ }
354
+ }
355
+ });
356
+
357
+ return () => {
358
+ abortController.abort();
359
+ };
360
+ }, [
361
+ name,
362
+ bundle,
363
+ format,
364
+ accountId,
365
+ port,
366
+ assetPaths,
367
+ props.isWorkersSite,
368
+ compatibilityDate,
369
+ compatibilityFlags,
370
+ usageModel,
371
+ bindings,
372
+ modules,
373
+ props.env,
374
+ props.legacyEnv,
375
+ props.zone,
376
+ props.host,
377
+ props.routes,
378
+ session,
379
+ onReady,
380
+ ]);
381
+ return token;
240
382
  }