wrangler 0.0.0-e5a3814 → 0.0.0-e5b8cb40

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 (153) hide show
  1. package/README.md +29 -11
  2. package/bin/wrangler.js +86 -67
  3. package/config-schema.json +3052 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +118 -78
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +0 -4
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-pretty-error.ts +40 -0
  21. package/templates/middleware/middleware-scheduled.ts +15 -0
  22. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  23. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  24. package/templates/modules-watch-stub.js +4 -0
  25. package/templates/new-worker-scheduled.js +3 -3
  26. package/templates/new-worker-scheduled.ts +16 -16
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +19 -16
  29. package/templates/no-op-worker.js +10 -0
  30. package/templates/pages-dev-pipeline.ts +32 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +190 -0
  34. package/templates/pages-template-worker.ts +198 -0
  35. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  36. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +105 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +240 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +24360 -0
  45. package/wrangler-dist/cli.js +192828 -110221
  46. package/wrangler-dist/wasm-sync.wasm +0 -0
  47. package/Cloudflare_CA.pem +0 -18
  48. package/import_meta_url.js +0 -3
  49. package/miniflare-config-stubs/.env.empty +0 -0
  50. package/miniflare-config-stubs/package.empty.json +0 -1
  51. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  52. package/miniflare-dist/index.mjs +0 -4886
  53. package/pages/functions/buildPlugin.ts +0 -105
  54. package/pages/functions/buildWorker.ts +0 -151
  55. package/pages/functions/filepath-routing.test.ts +0 -234
  56. package/pages/functions/filepath-routing.ts +0 -189
  57. package/pages/functions/identifiers.ts +0 -78
  58. package/pages/functions/routes.ts +0 -156
  59. package/pages/functions/template-plugin.ts +0 -147
  60. package/pages/functions/template-worker.ts +0 -143
  61. package/src/__tests__/config-cache.test.ts +0 -36
  62. package/src/__tests__/configuration.test.ts +0 -3487
  63. package/src/__tests__/dev.test.tsx +0 -983
  64. package/src/__tests__/guess-worker-format.test.ts +0 -85
  65. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  66. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  67. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  68. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  69. package/src/__tests__/helpers/mock-bin.ts +0 -36
  70. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  71. package/src/__tests__/helpers/mock-console.ts +0 -87
  72. package/src/__tests__/helpers/mock-dialogs.ts +0 -130
  73. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  74. package/src/__tests__/helpers/mock-istty.ts +0 -27
  75. package/src/__tests__/helpers/mock-kv.ts +0 -33
  76. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  77. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  78. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  79. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  80. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  81. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  82. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  83. package/src/__tests__/https-options.test.ts +0 -130
  84. package/src/__tests__/index.test.ts +0 -257
  85. package/src/__tests__/init.test.ts +0 -1637
  86. package/src/__tests__/jest.setup.ts +0 -77
  87. package/src/__tests__/kv.test.ts +0 -1481
  88. package/src/__tests__/logger.test.ts +0 -115
  89. package/src/__tests__/package-manager.test.ts +0 -353
  90. package/src/__tests__/pages.test.ts +0 -754
  91. package/src/__tests__/parse.test.ts +0 -330
  92. package/src/__tests__/publish.test.ts +0 -5754
  93. package/src/__tests__/r2.test.ts +0 -233
  94. package/src/__tests__/route.test.ts +0 -45
  95. package/src/__tests__/secret.test.ts +0 -481
  96. package/src/__tests__/tail.test.ts +0 -690
  97. package/src/__tests__/user.test.ts +0 -131
  98. package/src/__tests__/whoami.test.tsx +0 -139
  99. package/src/abort.d.ts +0 -3
  100. package/src/bundle.ts +0 -197
  101. package/src/cfetch/index.ts +0 -121
  102. package/src/cfetch/internal.ts +0 -142
  103. package/src/cli.ts +0 -13
  104. package/src/config/README.md +0 -107
  105. package/src/config/config.ts +0 -234
  106. package/src/config/diagnostics.ts +0 -80
  107. package/src/config/environment.ts +0 -420
  108. package/src/config/index.ts +0 -225
  109. package/src/config/validation-helpers.ts +0 -584
  110. package/src/config/validation.ts +0 -1552
  111. package/src/config-cache.ts +0 -45
  112. package/src/create-worker-preview.ts +0 -185
  113. package/src/create-worker-upload-form.ts +0 -254
  114. package/src/dev/dev-vars.ts +0 -36
  115. package/src/dev/dev.tsx +0 -401
  116. package/src/dev/local.tsx +0 -322
  117. package/src/dev/remote.tsx +0 -237
  118. package/src/dev/use-esbuild.ts +0 -118
  119. package/src/dialogs.tsx +0 -135
  120. package/src/durable.ts +0 -102
  121. package/src/entry.ts +0 -322
  122. package/src/environment-variables.ts +0 -35
  123. package/src/errors.ts +0 -11
  124. package/src/https-options.ts +0 -123
  125. package/src/index.tsx +0 -2846
  126. package/src/inspect.ts +0 -662
  127. package/src/intl-polyfill.d.ts +0 -139
  128. package/src/kv.ts +0 -408
  129. package/src/logger.ts +0 -66
  130. package/src/miniflare-cli/README.md +0 -30
  131. package/src/miniflare-cli/enum-keys.ts +0 -17
  132. package/src/miniflare-cli/index.ts +0 -41
  133. package/src/miniflare-cli/request-context.ts +0 -40
  134. package/src/module-collection.ts +0 -258
  135. package/src/open-in-browser.ts +0 -19
  136. package/src/package-manager.ts +0 -174
  137. package/src/pages.tsx +0 -2093
  138. package/src/parse.ts +0 -203
  139. package/src/paths.ts +0 -26
  140. package/src/proxy.ts +0 -478
  141. package/src/publish.ts +0 -716
  142. package/src/r2.ts +0 -50
  143. package/src/selfsigned.d.ts +0 -29
  144. package/src/sites.tsx +0 -326
  145. package/src/tail/filters.ts +0 -279
  146. package/src/tail/index.ts +0 -299
  147. package/src/tail/printing.ts +0 -67
  148. package/src/update-check.ts +0 -19
  149. package/src/user.tsx +0 -1214
  150. package/src/whoami.tsx +0 -71
  151. package/src/worker.ts +0 -181
  152. package/src/zones.ts +0 -73
  153. package/templates/static-asset-facade.js +0 -43
package/src/dev/local.tsx DELETED
@@ -1,322 +0,0 @@
1
- import { spawn } from "node:child_process";
2
- import { realpathSync } from "node:fs";
3
- import { writeFile } from "node:fs/promises";
4
- import path from "node:path";
5
- import { useState, useEffect, useRef } from "react";
6
- import onExit from "signal-exit";
7
- import useInspector from "../inspect";
8
- import { logger } from "../logger";
9
- import { DEFAULT_MODULE_RULES } from "../module-collection";
10
- import { waitForPortToBeAvailable } from "../proxy";
11
- import type { Config } from "../config";
12
- import type { AssetPaths } from "../sites";
13
- import type { CfWorkerInit, CfScriptFormat } from "../worker";
14
- import type { EsbuildBundle } from "./use-esbuild";
15
- import type { MiniflareOptions } from "miniflare";
16
-
17
- interface LocalProps {
18
- name: string | undefined;
19
- bundle: EsbuildBundle | undefined;
20
- format: CfScriptFormat | undefined;
21
- compatibilityDate: string;
22
- compatibilityFlags: string[] | undefined;
23
- bindings: CfWorkerInit["bindings"];
24
- localProtocol: "http" | "https";
25
- assetPaths: AssetPaths | undefined;
26
- public: string | undefined;
27
- port: number;
28
- ip: string;
29
- rules: Config["rules"];
30
- inspectorPort: number;
31
- enableLocalPersistence: boolean;
32
- crons: Config["triggers"]["crons"];
33
- }
34
-
35
- export function Local(props: LocalProps) {
36
- const { inspectorUrl } = useLocalWorker(props);
37
- useInspector({
38
- inspectorUrl,
39
- port: props.inspectorPort,
40
- logToTerminal: false,
41
- });
42
- return null;
43
- }
44
-
45
- function useLocalWorker({
46
- name: workerName,
47
- bundle,
48
- format,
49
- compatibilityDate,
50
- compatibilityFlags,
51
- bindings,
52
- assetPaths,
53
- public: publicDirectory,
54
- port,
55
- rules,
56
- enableLocalPersistence,
57
- ip,
58
- localProtocol,
59
- crons,
60
- }: LocalProps) {
61
- // TODO: pass vars via command line
62
- const local = useRef<ReturnType<typeof spawn>>();
63
- const removeSignalExitListener = useRef<() => void>();
64
- const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
65
- // if we're using local persistence for data, we should use the cwd
66
- // as an explicit path, or else it'll use the temp dir
67
- // which disappears when dev ends
68
- const localPersistencePath = enableLocalPersistence
69
- ? // Maybe we could make the path configurable as well?
70
- path.join(process.cwd(), "wrangler-local-state")
71
- : // We otherwise choose null, but choose true later
72
- // so that it's persisted in the temp dir across a dev session
73
- // even when we change source and reload
74
- null;
75
- useEffect(() => {
76
- const abortController = new AbortController();
77
- async function startLocalWorker() {
78
- if (!bundle || !format) return;
79
-
80
- // port for the worker
81
- await waitForPortToBeAvailable(port, {
82
- retryPeriod: 200,
83
- timeout: 2000,
84
- abortSignal: abortController.signal,
85
- });
86
-
87
- if (publicDirectory) {
88
- throw new Error(
89
- '⎔ A "public" folder is not yet supported in local mode.'
90
- );
91
- }
92
- if (bindings.services && bindings.services.length > 0) {
93
- throw new Error(
94
- "⎔ Service bindings are not yet supported in local mode."
95
- );
96
- }
97
-
98
- // In local mode, we want to copy all referenced modules into
99
- // the output bundle directory before starting up
100
- for (const module of bundle.modules) {
101
- await writeFile(
102
- path.join(path.dirname(bundle.path), module.name),
103
- module.content
104
- );
105
- }
106
-
107
- const scriptPath = realpathSync(bundle.path);
108
-
109
- // the wasm_modules/text_blobs/data_blobs bindings are
110
- // relative to process.cwd(), but the actual worker bundle
111
- // is in the temp output directory; so we rewrite the paths to be absolute,
112
- // letting miniflare resolve them correctly
113
-
114
- // wasm
115
- const wasmBindings: Record<string, string> = {};
116
- for (const [name, filePath] of Object.entries(
117
- bindings.wasm_modules || {}
118
- )) {
119
- wasmBindings[name] = path.join(process.cwd(), filePath);
120
- }
121
-
122
- // text
123
- const textBlobBindings: Record<string, string> = {};
124
- for (const [name, filePath] of Object.entries(
125
- bindings.text_blobs || {}
126
- )) {
127
- textBlobBindings[name] = path.join(process.cwd(), filePath);
128
- }
129
-
130
- // data
131
- const dataBlobBindings: Record<string, string> = {};
132
- for (const [name, filePath] of Object.entries(
133
- bindings.data_blobs || {}
134
- )) {
135
- dataBlobBindings[name] = path.join(process.cwd(), filePath);
136
- }
137
-
138
- if (format === "service-worker") {
139
- for (const { type, name } of bundle.modules) {
140
- if (type === "compiled-wasm") {
141
- // In service-worker format, .wasm modules are referenced by global identifiers,
142
- // so we convert it here.
143
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
144
- // characters with an underscore.
145
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
146
- wasmBindings[identifier] = name;
147
- } else if (type === "text") {
148
- // In service-worker format, text modules are referenced by global identifiers,
149
- // so we convert it here.
150
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
151
- // characters with an underscore.
152
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
153
- textBlobBindings[identifier] = name;
154
- } else if (type === "buffer") {
155
- // In service-worker format, data blobs are referenced by global identifiers,
156
- // so we convert it here.
157
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
158
- // characters with an underscore.
159
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
160
- dataBlobBindings[identifier] = name;
161
- }
162
- }
163
- }
164
-
165
- const options: MiniflareOptions = {
166
- name: workerName,
167
- port,
168
- scriptPath,
169
- https: localProtocol === "https",
170
- host: ip,
171
- modules: format === "modules",
172
- modulesRules: (rules || [])
173
- .concat(DEFAULT_MODULE_RULES)
174
- .map(({ type, globs: include, fallthrough }) => ({
175
- type,
176
- include,
177
- fallthrough,
178
- })),
179
- compatibilityDate,
180
- compatibilityFlags,
181
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
182
- durableObjects: Object.fromEntries(
183
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
184
- (value) => [value.name, value.class_name]
185
- )
186
- ),
187
- ...(localPersistencePath
188
- ? {
189
- kvPersist: path.join(localPersistencePath, "kv"),
190
- durableObjectsPersist: path.join(localPersistencePath, "do"),
191
- cachePersist: path.join(localPersistencePath, "cache"),
192
- }
193
- : {
194
- // We mark these as true, so that they'll
195
- // persist in the temp directory.
196
- // This means they'll persist across a dev session,
197
- // even if we change source and reload,
198
- // and be deleted when the dev session ends
199
- durableObjectsPersist: true,
200
- cachePersist: true,
201
- kvPersist: true,
202
- }),
203
-
204
- sitePath: assetPaths?.assetDirectory
205
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
206
- : undefined,
207
- siteInclude: assetPaths?.includePatterns.length
208
- ? assetPaths?.includePatterns
209
- : undefined,
210
- siteExclude: assetPaths?.excludePatterns.length
211
- ? assetPaths.excludePatterns
212
- : undefined,
213
- bindings: bindings.vars,
214
- wasmBindings,
215
- textBlobBindings,
216
- dataBlobBindings,
217
- sourceMap: true,
218
- logUnhandledRejections: true,
219
- crons,
220
- };
221
-
222
- // The path to the Miniflare CLI assumes that this file is being run from
223
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
224
- // If either of those paths change this line needs updating.
225
- const miniflareCLIPath = path.resolve(
226
- __dirname,
227
- "../miniflare-dist/index.mjs"
228
- );
229
- const optionsArg = JSON.stringify(options, null);
230
-
231
- logger.log("⎔ Starting a local server...");
232
- local.current = spawn(
233
- "node",
234
- [
235
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
236
- "--no-warnings", // hide annoying Node warnings
237
- "--inspect", // start Miniflare listening for a debugger to attach
238
- miniflareCLIPath,
239
- optionsArg,
240
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
241
- ],
242
- {
243
- cwd: path.dirname(scriptPath),
244
- }
245
- );
246
-
247
- local.current.on("close", (code) => {
248
- if (code) {
249
- logger.log(`Miniflare process exited with code ${code}`);
250
- }
251
- });
252
-
253
- local.current.stdout?.on("data", (data: Buffer) => {
254
- process.stdout.write(data);
255
- });
256
-
257
- local.current.stderr?.on("data", (data: Buffer) => {
258
- const matches =
259
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
260
- data.toString()
261
- );
262
- if (matches) {
263
- setInspectorUrl(matches[1]);
264
- }
265
- });
266
-
267
- local.current.on("exit", (code) => {
268
- if (code) {
269
- logger.error(`Miniflare process exited with code ${code}`);
270
- }
271
- });
272
-
273
- local.current.on("error", (error: Error) => {
274
- logger.error(`Miniflare process failed to spawn`);
275
- logger.error(error);
276
- });
277
-
278
- removeSignalExitListener.current = onExit((_code, _signal) => {
279
- logger.log("⎔ Shutting down local server.");
280
- local.current?.kill();
281
- local.current = undefined;
282
- });
283
- }
284
-
285
- startLocalWorker().catch((err) => {
286
- logger.error("local worker:", err);
287
- });
288
-
289
- return () => {
290
- abortController.abort();
291
- if (local.current) {
292
- logger.log("⎔ Shutting down local server.");
293
- local.current?.kill();
294
- local.current = undefined;
295
- removeSignalExitListener.current && removeSignalExitListener.current();
296
- removeSignalExitListener.current = undefined;
297
- }
298
- };
299
- }, [
300
- bundle,
301
- workerName,
302
- format,
303
- port,
304
- localProtocol,
305
- ip,
306
- bindings.durable_objects?.bindings,
307
- bindings.kv_namespaces,
308
- bindings.vars,
309
- bindings.services,
310
- compatibilityDate,
311
- compatibilityFlags,
312
- localPersistencePath,
313
- assetPaths,
314
- publicDirectory,
315
- rules,
316
- bindings.wasm_modules,
317
- bindings.text_blobs,
318
- bindings.data_blobs,
319
- crons,
320
- ]);
321
- return { inspectorUrl };
322
- }
@@ -1,237 +0,0 @@
1
- import { readFile } from "node:fs/promises";
2
- import path from "node:path";
3
- import { useState, useEffect, useRef } from "react";
4
- import { createWorkerPreview } from "../create-worker-preview";
5
- import useInspector from "../inspect";
6
- import { logger } from "../logger";
7
- import { usePreviewServer } from "../proxy";
8
- import { syncAssets } from "../sites";
9
- import { requireApiToken, requireAuth } from "../user";
10
- import type { CfPreviewToken } from "../create-worker-preview";
11
- import type { AssetPaths } from "../sites";
12
- import type { CfModule, CfWorkerInit, CfScriptFormat } from "../worker";
13
- import type { EsbuildBundle } from "./use-esbuild";
14
-
15
- 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;
34
- }) {
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
- port: props.port,
44
- compatibilityDate: props.compatibilityDate,
45
- compatibilityFlags: props.compatibilityFlags,
46
- usageModel: props.usageModel,
47
- env: props.env,
48
- legacyEnv: props.legacyEnv,
49
- zone: props.zone,
50
- host: props.host,
51
- });
52
-
53
- usePreviewServer({
54
- previewToken,
55
- publicRoot: props.public,
56
- localProtocol: props.localProtocol,
57
- localPort: props.port,
58
- ip: props.ip,
59
- });
60
-
61
- useInspector({
62
- inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
63
- port: props.inspectorPort,
64
- logToTerminal: true,
65
- });
66
- return null;
67
- }
68
-
69
- export function useWorker(props: {
70
- name: string | undefined;
71
- bundle: EsbuildBundle | undefined;
72
- format: CfScriptFormat | undefined;
73
- modules: CfModule[];
74
- accountId: string | undefined;
75
- bindings: CfWorkerInit["bindings"];
76
- assetPaths: AssetPaths | undefined;
77
- port: number;
78
- compatibilityDate: string | undefined;
79
- compatibilityFlags: string[] | undefined;
80
- usageModel: "bundled" | "unbound" | undefined;
81
- env: string | undefined;
82
- legacyEnv: boolean | undefined;
83
- zone: string | undefined;
84
- host: string | undefined;
85
- }): CfPreviewToken | undefined {
86
- const {
87
- name,
88
- bundle,
89
- format,
90
- modules,
91
- accountId,
92
- bindings,
93
- assetPaths,
94
- compatibilityDate,
95
- compatibilityFlags,
96
- usageModel,
97
- port,
98
- } = props;
99
- const [token, setToken] = useState<CfPreviewToken | undefined>();
100
-
101
- // This is the most reliable way to detect whether
102
- // something's "happened" in our system; We make a ref and
103
- // mark it once we log our initial message. Refs are vars!
104
- const startedRef = useRef(false);
105
- // This ref holds the actual accountId being used, the `accountId` prop could be undefined
106
- // as it is only what is retrieved from the wrangler.toml config.
107
- const accountIdRef = useRef(accountId);
108
-
109
- useEffect(() => {
110
- const abortController = new AbortController();
111
- async function start() {
112
- setToken(undefined); // reset token in case we're re-running
113
-
114
- if (!bundle || !format) return;
115
-
116
- if (!startedRef.current) {
117
- startedRef.current = true;
118
- } else {
119
- logger.log("⎔ Detected changes, restarted server.");
120
- }
121
-
122
- // Ensure we have an account id, even if it means logging in here.
123
- accountIdRef.current = await requireAuth({
124
- account_id: accountIdRef.current,
125
- });
126
-
127
- const assets = await syncAssets(
128
- accountIdRef.current,
129
- // When we're using the newer service environments, we wouldn't
130
- // have added the env name on to the script name. However, we must
131
- // include it in the kv namespace name regardless (since there's no
132
- // concept of service environments for kv namespaces yet).
133
- name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
134
- assetPaths,
135
- true,
136
- false
137
- ); // TODO: cancellable?
138
-
139
- const content = await readFile(bundle.path, "utf-8");
140
-
141
- const init: CfWorkerInit = {
142
- name,
143
- main: {
144
- name: path.basename(bundle.path),
145
- type: format === "modules" ? "esm" : "commonjs",
146
- content,
147
- },
148
- modules: modules.concat(
149
- assets.manifest
150
- ? {
151
- name: "__STATIC_CONTENT_MANIFEST",
152
- content: JSON.stringify(assets.manifest),
153
- type: "text",
154
- }
155
- : []
156
- ),
157
- bindings: {
158
- ...bindings,
159
- kv_namespaces: (bindings.kv_namespaces || []).concat(
160
- assets.namespace
161
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
162
- : []
163
- ),
164
- text_blobs: {
165
- ...bindings.text_blobs,
166
- ...(assets.manifest &&
167
- format === "service-worker" && {
168
- __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
169
- }),
170
- },
171
- },
172
- migrations: undefined, // no migrations in dev
173
- compatibility_date: compatibilityDate,
174
- compatibility_flags: compatibilityFlags,
175
- usage_model: usageModel,
176
- };
177
- setToken(
178
- await createWorkerPreview(
179
- init,
180
- {
181
- accountId: accountIdRef.current,
182
- apiToken: requireApiToken(),
183
- },
184
- {
185
- env: props.env,
186
- legacyEnv: props.legacyEnv,
187
- zone: props.zone,
188
- host: props.host,
189
- },
190
- abortController.signal
191
- )
192
- );
193
- }
194
- start().catch((err) => {
195
- // we want to log the error, but not end the process
196
- // since it could recover after the developer fixes whatever's wrong
197
- if ((err as { code: string }).code !== "ABORT_ERR") {
198
- // instead of logging the raw API error to the user,
199
- // give them friendly instructions
200
- // for error 10063 (workers.dev subdomain required)
201
- if (err.code === 10063) {
202
- const errorMessage =
203
- "Error: You need to register a workers.dev subdomain before running the dev command in remote mode";
204
- const solutionMessage =
205
- "You can either enable local mode by pressing l, or register a workers.dev subdomain here:";
206
- const onboardingLink = `https://dash.cloudflare.com/${accountIdRef.current}/workers/onboarding`;
207
- logger.error(
208
- `${errorMessage}\n${solutionMessage}\n${onboardingLink}`
209
- );
210
- } else {
211
- logger.error("Error on remote worker:", err);
212
- }
213
- }
214
- });
215
-
216
- return () => {
217
- abortController.abort();
218
- };
219
- }, [
220
- name,
221
- bundle,
222
- format,
223
- accountId,
224
- port,
225
- assetPaths,
226
- compatibilityDate,
227
- compatibilityFlags,
228
- usageModel,
229
- bindings,
230
- modules,
231
- props.env,
232
- props.legacyEnv,
233
- props.zone,
234
- props.host,
235
- ]);
236
- return token;
237
- }
@@ -1,118 +0,0 @@
1
- import assert from "node:assert";
2
- import { useApp } from "ink";
3
- import { useState, useEffect } from "react";
4
- import { bundleWorker } from "../bundle";
5
- import { logger } from "../logger";
6
- import type { Config } from "../config";
7
- import type { Entry } from "../entry";
8
- import type { CfModule } from "../worker";
9
- import type { WatchMode } from "esbuild";
10
-
11
- export type EsbuildBundle = {
12
- id: number;
13
- path: string;
14
- entry: Entry;
15
- type: "esm" | "commonjs";
16
- modules: CfModule[];
17
- serveAssetsFromWorker: boolean;
18
- };
19
-
20
- export function useEsbuild({
21
- entry,
22
- destination,
23
- staticRoot,
24
- jsxFactory,
25
- jsxFragment,
26
- rules,
27
- serveAssetsFromWorker,
28
- tsconfig,
29
- minify,
30
- nodeCompat,
31
- }: {
32
- entry: Entry;
33
- destination: string | undefined;
34
- staticRoot: string | undefined;
35
- jsxFactory: string | undefined;
36
- jsxFragment: string | undefined;
37
- rules: Config["rules"];
38
- serveAssetsFromWorker: boolean;
39
- tsconfig: string | undefined;
40
- minify: boolean | undefined;
41
- nodeCompat: boolean | undefined;
42
- }): EsbuildBundle | undefined {
43
- const [bundle, setBundle] = useState<EsbuildBundle>();
44
- const { exit } = useApp();
45
- useEffect(() => {
46
- let stopWatching: (() => void) | undefined = undefined;
47
-
48
- const watchMode: WatchMode = {
49
- async onRebuild(error) {
50
- if (error) logger.error("Watch build failed:", error);
51
- else {
52
- // nothing really changes here, so let's increment the id
53
- // to change the return object's identity
54
- setBundle((previousBundle) => {
55
- assert(
56
- previousBundle,
57
- "Rebuild triggered with no previous build available"
58
- );
59
- return { ...previousBundle, id: previousBundle.id + 1 };
60
- });
61
- }
62
- },
63
- };
64
-
65
- async function build() {
66
- if (!destination) return;
67
-
68
- const { resolvedEntryPointPath, bundleType, modules, stop } =
69
- await bundleWorker(entry, destination, {
70
- // In dev, we serve assets from the local proxy before we send the request to the worker.
71
- serveAssetsFromWorker: false,
72
- jsxFactory,
73
- jsxFragment,
74
- rules,
75
- watch: watchMode,
76
- tsconfig,
77
- minify,
78
- nodeCompat,
79
- });
80
-
81
- // Capture the `stop()` method to use as the `useEffect()` destructor.
82
- stopWatching = stop;
83
-
84
- setBundle({
85
- id: 0,
86
- entry,
87
- path: resolvedEntryPointPath,
88
- type: bundleType,
89
- modules,
90
- serveAssetsFromWorker,
91
- });
92
- }
93
-
94
- build().catch((err) => {
95
- // If esbuild fails on first run, we want to quit the process
96
- // since we can't recover from here
97
- // related: https://github.com/evanw/esbuild/issues/1037
98
- exit(err);
99
- });
100
-
101
- return () => {
102
- stopWatching?.();
103
- };
104
- }, [
105
- entry,
106
- destination,
107
- staticRoot,
108
- jsxFactory,
109
- jsxFragment,
110
- serveAssetsFromWorker,
111
- rules,
112
- tsconfig,
113
- exit,
114
- minify,
115
- nodeCompat,
116
- ]);
117
- return bundle;
118
- }