wrangler 0.0.0-fd3517a → 0.0.0-fd39ae64

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