wrangler 0.0.0-e64812e → 0.0.0-e8e684c7

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 (214) hide show
  1. package/README.md +27 -3
  2. package/bin/wrangler.js +150 -62
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +663 -7
  5. package/package.json +173 -152
  6. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  7. package/src/__tests__/config-cache.test.ts +30 -24
  8. package/src/__tests__/configuration.test.ts +4015 -3363
  9. package/src/__tests__/dev.test.tsx +1290 -952
  10. package/src/__tests__/generate.test.ts +91 -0
  11. package/src/__tests__/guess-worker-format.test.ts +68 -68
  12. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  13. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  14. package/src/__tests__/helpers/mock-bin.ts +20 -20
  15. package/src/__tests__/helpers/mock-cfetch.ts +179 -94
  16. package/src/__tests__/helpers/mock-console.ts +49 -39
  17. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  18. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  20. package/src/__tests__/helpers/mock-istty.ts +65 -18
  21. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  22. package/src/__tests__/helpers/mock-kv.ts +26 -26
  23. package/src/__tests__/helpers/mock-oauth-flow.ts +223 -228
  24. package/src/__tests__/helpers/mock-process.ts +39 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  26. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  27. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  28. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  29. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  30. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  31. package/src/__tests__/https-options.test.ts +142 -109
  32. package/src/__tests__/index.test.ts +222 -233
  33. package/src/__tests__/init.test.ts +2139 -1603
  34. package/src/__tests__/jest.setup.ts +114 -34
  35. package/src/__tests__/kv.test.ts +1222 -1032
  36. package/src/__tests__/logger.test.ts +100 -74
  37. package/src/__tests__/metrics.test.ts +450 -0
  38. package/src/__tests__/package-manager.test.ts +303 -303
  39. package/src/__tests__/pages.test.ts +1173 -652
  40. package/src/__tests__/parse.test.ts +252 -252
  41. package/src/__tests__/publish.test.ts +6788 -5301
  42. package/src/__tests__/pubsub.test.ts +367 -0
  43. package/src/__tests__/r2.test.ts +328 -225
  44. package/src/__tests__/route.test.ts +18 -18
  45. package/src/__tests__/secret.test.ts +470 -459
  46. package/src/__tests__/tail.test.ts +676 -564
  47. package/src/__tests__/test-old-node-version.js +31 -0
  48. package/src/__tests__/user.test.ts +136 -112
  49. package/src/__tests__/validate-dev-props.test.ts +56 -0
  50. package/src/__tests__/version.test.ts +35 -0
  51. package/src/__tests__/whoami.test.tsx +267 -83
  52. package/src/__tests__/worker-namespace.test.ts +329 -0
  53. package/src/abort.d.ts +1 -1
  54. package/src/api/dev.ts +93 -0
  55. package/src/api/index.ts +1 -0
  56. package/src/bundle-reporter.tsx +29 -0
  57. package/src/bundle.ts +430 -157
  58. package/src/cfetch/index.ts +80 -80
  59. package/src/cfetch/internal.ts +244 -91
  60. package/src/cli.ts +21 -7
  61. package/src/config/config.ts +224 -195
  62. package/src/config/diagnostics.ts +61 -61
  63. package/src/config/environment.ts +422 -357
  64. package/src/config/index.ts +219 -193
  65. package/src/config/validation-helpers.ts +379 -357
  66. package/src/config/validation.ts +1690 -1367
  67. package/src/config-cache.ts +81 -41
  68. package/src/create-worker-preview.ts +208 -136
  69. package/src/create-worker-upload-form.ts +275 -238
  70. package/src/dev/dev-vars.ts +13 -13
  71. package/src/dev/dev.tsx +477 -351
  72. package/src/dev/local.tsx +426 -295
  73. package/src/dev/remote.tsx +406 -211
  74. package/src/dev/use-esbuild.ts +154 -94
  75. package/src/dev/validate-dev-props.ts +31 -0
  76. package/src/dev-registry.tsx +160 -0
  77. package/src/dev.tsx +696 -0
  78. package/src/dialogs.tsx +97 -97
  79. package/src/dispatch-namespace.ts +206 -0
  80. package/src/durable.ts +87 -87
  81. package/src/entry.ts +234 -228
  82. package/src/environment-variables.ts +23 -23
  83. package/src/errors.ts +6 -6
  84. package/src/faye-websocket.d.ts +6 -0
  85. package/src/generate.ts +131 -0
  86. package/src/git-client.ts +42 -0
  87. package/src/global-wrangler-config-path.ts +26 -0
  88. package/src/https-options.ts +84 -80
  89. package/src/index.tsx +2164 -2768
  90. package/src/init.ts +622 -0
  91. package/src/inspect.ts +678 -593
  92. package/src/intl-polyfill.d.ts +123 -123
  93. package/src/is-ci.ts +14 -0
  94. package/src/is-interactive.ts +12 -0
  95. package/src/kv.ts +299 -277
  96. package/src/logger.ts +46 -39
  97. package/src/metrics/index.ts +5 -0
  98. package/src/metrics/metrics-config.ts +239 -0
  99. package/src/metrics/metrics-dispatcher.ts +96 -0
  100. package/src/metrics/metrics-usage-headers.ts +24 -0
  101. package/src/metrics/send-event.ts +92 -0
  102. package/src/miniflare-cli/assets.ts +554 -0
  103. package/src/miniflare-cli/enum-keys.ts +8 -8
  104. package/src/miniflare-cli/index.ts +198 -32
  105. package/src/miniflare-cli/request-context.ts +18 -18
  106. package/src/module-collection.ts +212 -212
  107. package/src/open-in-browser.ts +4 -6
  108. package/src/package-manager.ts +173 -128
  109. package/src/pages/build.tsx +238 -0
  110. package/src/pages/constants.ts +12 -0
  111. package/src/pages/deployments.tsx +106 -0
  112. package/src/pages/dev.tsx +528 -0
  113. package/src/pages/errors.ts +22 -0
  114. package/src/pages/functions/buildPlugin.ts +109 -0
  115. package/src/pages/functions/buildWorker.ts +155 -0
  116. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  117. package/src/pages/functions/filepath-routing.ts +189 -0
  118. package/src/pages/functions/identifiers.ts +78 -0
  119. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  120. package/src/pages/functions/routes-consolidation.ts +73 -0
  121. package/src/pages/functions/routes-transformation.test.ts +271 -0
  122. package/src/pages/functions/routes-transformation.ts +122 -0
  123. package/src/pages/functions/routes.ts +151 -0
  124. package/src/pages/functions.tsx +96 -0
  125. package/src/pages/index.tsx +94 -0
  126. package/src/pages/projects.tsx +169 -0
  127. package/src/pages/publish.tsx +391 -0
  128. package/src/pages/types.ts +49 -0
  129. package/src/pages/upload.tsx +413 -0
  130. package/src/pages/utils.ts +12 -0
  131. package/src/parse.ts +209 -125
  132. package/src/paths.ts +6 -6
  133. package/src/preview.ts +31 -0
  134. package/src/proxy.ts +410 -389
  135. package/src/publish.ts +773 -534
  136. package/src/pubsub/index.ts +286 -0
  137. package/src/pubsub/pubsub-commands.tsx +623 -0
  138. package/src/r2.ts +100 -19
  139. package/src/selfsigned.d.ts +23 -23
  140. package/src/sites.tsx +278 -201
  141. package/src/tail/filters.ts +111 -109
  142. package/src/tail/index.ts +230 -217
  143. package/src/tail/printing.ts +86 -46
  144. package/src/update-check.ts +11 -11
  145. package/src/user/choose-account.tsx +69 -0
  146. package/src/user/env-vars.ts +46 -0
  147. package/src/user/generate-auth-url.ts +33 -0
  148. package/src/user/generate-random-state.ts +16 -0
  149. package/src/user/index.ts +3 -0
  150. package/src/user/user.tsx +1191 -0
  151. package/src/whoami.tsx +141 -42
  152. package/src/worker.ts +123 -99
  153. package/src/zones.ts +167 -0
  154. package/templates/checked-fetch.js +17 -0
  155. package/templates/first-party-worker-module-facade.ts +18 -0
  156. package/templates/format-dev-errors.ts +32 -0
  157. package/templates/new-worker-scheduled.js +3 -3
  158. package/templates/new-worker-scheduled.ts +15 -15
  159. package/templates/new-worker.js +3 -3
  160. package/templates/new-worker.ts +15 -15
  161. package/templates/no-op-worker.js +10 -0
  162. package/templates/pages-shim.ts +9 -0
  163. package/templates/pages-template-plugin.ts +167 -0
  164. package/templates/pages-template-worker.ts +172 -0
  165. package/templates/serve-static-assets.ts +63 -0
  166. package/templates/service-bindings-module-facade.js +54 -0
  167. package/templates/service-bindings-sw-facade.js +42 -0
  168. package/templates/tsconfig.json +95 -95
  169. package/wrangler-dist/cli.d.ts +338 -0
  170. package/wrangler-dist/cli.js +95449 -67524
  171. package/pages/functions/buildPlugin.ts +0 -105
  172. package/pages/functions/buildWorker.ts +0 -151
  173. package/pages/functions/filepath-routing.ts +0 -189
  174. package/pages/functions/identifiers.ts +0 -78
  175. package/pages/functions/routes.ts +0 -156
  176. package/pages/functions/template-plugin.ts +0 -147
  177. package/pages/functions/template-worker.ts +0 -143
  178. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  179. package/src/pages.tsx +0 -2038
  180. package/src/user.tsx +0 -1203
  181. package/templates/static-asset-facade.js +0 -47
  182. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  183. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  184. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  185. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  186. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  187. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  188. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  189. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  190. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  191. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  192. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  193. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  194. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  195. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  196. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  197. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  198. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  199. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  200. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  201. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  202. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  203. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  204. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  205. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  206. package/vendor/wrangler-mime/LICENSE +0 -21
  207. package/vendor/wrangler-mime/Mime.js +0 -97
  208. package/vendor/wrangler-mime/README.md +0 -187
  209. package/vendor/wrangler-mime/cli.js +0 -46
  210. package/vendor/wrangler-mime/index.js +0 -4
  211. package/vendor/wrangler-mime/lite.js +0 -4
  212. package/vendor/wrangler-mime/package.json +0 -52
  213. package/vendor/wrangler-mime/types/other.js +0 -1
  214. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/dev/local.tsx CHANGED
@@ -1,318 +1,449 @@
1
- import { spawn } from "node:child_process";
1
+ import { fork } from "node:child_process";
2
2
  import { realpathSync } from "node:fs";
3
3
  import { writeFile } from "node:fs/promises";
4
4
  import path from "node:path";
5
5
  import { useState, useEffect, useRef } from "react";
6
6
  import onExit from "signal-exit";
7
+ import { registerWorker } from "../dev-registry";
7
8
  import useInspector from "../inspect";
8
9
  import { logger } from "../logger";
9
10
  import { DEFAULT_MODULE_RULES } from "../module-collection";
10
11
  import { waitForPortToBeAvailable } from "../proxy";
11
12
  import type { Config } from "../config";
13
+ import type { WorkerRegistry } from "../dev-registry";
14
+ import type { EnablePagesAssetsServiceBindingOptions } from "../miniflare-cli";
12
15
  import type { AssetPaths } from "../sites";
13
16
  import type { CfWorkerInit, CfScriptFormat } from "../worker";
14
17
  import type { EsbuildBundle } from "./use-esbuild";
15
18
  import type { MiniflareOptions } from "miniflare";
16
-
19
+ import type { ChildProcess } from "node:child_process";
17
20
  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"];
21
+ name: string | undefined;
22
+ bundle: EsbuildBundle | undefined;
23
+ format: CfScriptFormat | undefined;
24
+ compatibilityDate: string;
25
+ compatibilityFlags: string[] | undefined;
26
+ usageModel: "bundled" | "unbound" | undefined;
27
+ bindings: CfWorkerInit["bindings"];
28
+ workerDefinitions: WorkerRegistry;
29
+ assetPaths: AssetPaths | undefined;
30
+ port: number;
31
+ ip: string;
32
+ rules: Config["rules"];
33
+ inspectorPort: number;
34
+ enableLocalPersistence: boolean;
35
+ liveReload: boolean;
36
+ crons: Config["triggers"]["crons"];
37
+ localProtocol: "http" | "https";
38
+ localUpstream: string | undefined;
39
+ inspect: boolean;
40
+ onReady: (() => void) | undefined;
41
+ logLevel: "none" | "error" | "log" | "warn" | "debug" | undefined;
42
+ logPrefix?: string;
43
+ enablePagesAssetsServiceBinding?: EnablePagesAssetsServiceBindingOptions;
32
44
  }
33
45
 
34
46
  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;
47
+ const { inspectorUrl } = useLocalWorker(props);
48
+ useInspector({
49
+ inspectorUrl,
50
+ port: props.inspectorPort,
51
+ logToTerminal: false,
52
+ });
53
+ return null;
42
54
  }
43
55
 
44
56
  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,
57
+ name: workerName,
58
+ bundle,
59
+ format,
60
+ compatibilityDate,
61
+ compatibilityFlags,
62
+ usageModel,
63
+ bindings,
64
+ workerDefinitions,
65
+ assetPaths,
66
+ port,
67
+ inspectorPort,
68
+ rules,
69
+ enableLocalPersistence,
70
+ liveReload,
71
+ ip,
72
+ crons,
73
+ localProtocol,
74
+ localUpstream,
75
+ inspect,
76
+ onReady,
77
+ logLevel,
78
+ logPrefix,
79
+ enablePagesAssetsServiceBinding,
58
80
  }: 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
- if (bindings.services && bindings.services.length > 0) {
91
- throw new Error(
92
- "⎔ Service bindings are not yet supported in local mode."
93
- );
94
- }
95
-
96
- // In local mode, we want to copy all referenced modules into
97
- // the output bundle directory before starting up
98
- for (const module of bundle.modules) {
99
- await writeFile(
100
- path.join(path.dirname(bundle.path), module.name),
101
- module.content
102
- );
103
- }
104
-
105
- const scriptPath = realpathSync(bundle.path);
106
-
107
- // the wasm_modules/text_blobs/data_blobs bindings are
108
- // relative to process.cwd(), but the actual worker bundle
109
- // is in the temp output directory; so we rewrite the paths to be absolute,
110
- // letting miniflare resolve them correctly
111
-
112
- // wasm
113
- const wasmBindings: Record<string, string> = {};
114
- for (const [name, filePath] of Object.entries(
115
- bindings.wasm_modules || {}
116
- )) {
117
- wasmBindings[name] = path.join(process.cwd(), filePath);
118
- }
119
-
120
- // text
121
- const textBlobBindings: Record<string, string> = {};
122
- for (const [name, filePath] of Object.entries(
123
- bindings.text_blobs || {}
124
- )) {
125
- textBlobBindings[name] = path.join(process.cwd(), filePath);
126
- }
127
-
128
- // data
129
- const dataBlobBindings: Record<string, string> = {};
130
- for (const [name, filePath] of Object.entries(
131
- bindings.data_blobs || {}
132
- )) {
133
- dataBlobBindings[name] = path.join(process.cwd(), filePath);
134
- }
135
-
136
- if (format === "service-worker") {
137
- for (const { type, name } of bundle.modules) {
138
- if (type === "compiled-wasm") {
139
- // In service-worker format, .wasm modules are referenced by global identifiers,
140
- // so we convert it here.
141
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
142
- // characters with an underscore.
143
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
144
- wasmBindings[identifier] = name;
145
- } else if (type === "text") {
146
- // In service-worker format, text modules are referenced by global identifiers,
147
- // so we convert it here.
148
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
149
- // characters with an underscore.
150
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
151
- textBlobBindings[identifier] = name;
152
- } else if (type === "buffer") {
153
- // In service-worker format, data blobs are referenced by global identifiers,
154
- // so we convert it here.
155
- // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
156
- // characters with an underscore.
157
- const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
158
- dataBlobBindings[identifier] = name;
159
- }
160
- }
161
- }
162
-
163
- const options: MiniflareOptions = {
164
- name: workerName,
165
- port,
166
- scriptPath,
167
- host: ip,
168
- modules: format === "modules",
169
- modulesRules: (rules || [])
170
- .concat(DEFAULT_MODULE_RULES)
171
- .map(({ type, globs: include, fallthrough }) => ({
172
- type,
173
- include,
174
- fallthrough,
175
- })),
176
- compatibilityDate,
177
- compatibilityFlags,
178
- kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
179
- durableObjects: Object.fromEntries(
180
- (bindings.durable_objects?.bindings ?? []).map<[string, string]>(
181
- (value) => [value.name, value.class_name]
182
- )
183
- ),
184
- ...(localPersistencePath
185
- ? {
186
- kvPersist: path.join(localPersistencePath, "kv"),
187
- durableObjectsPersist: path.join(localPersistencePath, "do"),
188
- cachePersist: path.join(localPersistencePath, "cache"),
189
- }
190
- : {
191
- // We mark these as true, so that they'll
192
- // persist in the temp directory.
193
- // This means they'll persist across a dev session,
194
- // even if we change source and reload,
195
- // and be deleted when the dev session ends
196
- durableObjectsPersist: true,
197
- cachePersist: true,
198
- kvPersist: true,
199
- }),
200
-
201
- sitePath: assetPaths?.assetDirectory
202
- ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
203
- : undefined,
204
- siteInclude: assetPaths?.includePatterns.length
205
- ? assetPaths?.includePatterns
206
- : undefined,
207
- siteExclude: assetPaths?.excludePatterns.length
208
- ? assetPaths.excludePatterns
209
- : undefined,
210
- bindings: bindings.vars,
211
- wasmBindings,
212
- textBlobBindings,
213
- dataBlobBindings,
214
- sourceMap: true,
215
- logUnhandledRejections: true,
216
- crons,
217
- };
218
-
219
- // The path to the Miniflare CLI assumes that this file is being run from
220
- // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
221
- // If either of those paths change this line needs updating.
222
- const miniflareCLIPath = path.resolve(
223
- __dirname,
224
- "../miniflare-dist/index.mjs"
225
- );
226
- const optionsArg = JSON.stringify(options, null);
227
-
228
- logger.log("⎔ Starting a local server...");
229
- local.current = spawn(
230
- "node",
231
- [
232
- "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
233
- "--no-warnings", // hide annoying Node warnings
234
- "--inspect", // start Miniflare listening for a debugger to attach
235
- miniflareCLIPath,
236
- optionsArg,
237
- // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
238
- ],
239
- {
240
- cwd: path.dirname(scriptPath),
241
- }
242
- );
243
-
244
- local.current.on("close", (code) => {
245
- if (code) {
246
- logger.log(`Miniflare process exited with code ${code}`);
247
- }
248
- });
249
-
250
- local.current.stdout?.on("data", (data: Buffer) => {
251
- process.stdout.write(data);
252
- });
253
-
254
- local.current.stderr?.on("data", (data: Buffer) => {
255
- const matches =
256
- /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
257
- data.toString()
258
- );
259
- if (matches) {
260
- setInspectorUrl(matches[1]);
261
- }
262
- });
263
-
264
- local.current.on("exit", (code) => {
265
- if (code) {
266
- logger.error(`Miniflare process exited with code ${code}`);
267
- }
268
- });
269
-
270
- local.current.on("error", (error: Error) => {
271
- logger.error(`Miniflare process failed to spawn`);
272
- logger.error(error);
273
- });
274
-
275
- removeSignalExitListener.current = onExit((_code, _signal) => {
276
- logger.log("⎔ Shutting down local server.");
277
- local.current?.kill();
278
- local.current = undefined;
279
- });
280
- }
281
-
282
- startLocalWorker().catch((err) => {
283
- logger.error("local worker:", err);
284
- });
285
-
286
- return () => {
287
- abortController.abort();
288
- if (local.current) {
289
- logger.log("⎔ Shutting down local server.");
290
- local.current?.kill();
291
- local.current = undefined;
292
- removeSignalExitListener.current && removeSignalExitListener.current();
293
- removeSignalExitListener.current = undefined;
294
- }
295
- };
296
- }, [
297
- bundle,
298
- workerName,
299
- format,
300
- port,
301
- ip,
302
- bindings.durable_objects?.bindings,
303
- bindings.kv_namespaces,
304
- bindings.vars,
305
- bindings.services,
306
- compatibilityDate,
307
- compatibilityFlags,
308
- localPersistencePath,
309
- assetPaths,
310
- publicDirectory,
311
- rules,
312
- bindings.wasm_modules,
313
- bindings.text_blobs,
314
- bindings.data_blobs,
315
- crons,
316
- ]);
317
- return { inspectorUrl };
81
+ // TODO: pass vars via command line
82
+ const local = useRef<ChildProcess>();
83
+ const removeSignalExitListener = useRef<() => void>();
84
+ const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
85
+ // if we're using local persistence for data, we should use the cwd
86
+ // as an explicit path, or else it'll use the temp dir
87
+ // which disappears when dev ends
88
+ const localPersistencePath = enableLocalPersistence
89
+ ? // Maybe we could make the path configurable as well?
90
+ path.join(process.cwd(), "wrangler-local-state")
91
+ : // We otherwise choose null, but choose true later
92
+ // so that it's persisted in the temp dir across a dev session
93
+ // even when we change source and reload
94
+ null;
95
+
96
+ useEffect(() => {
97
+ if (bindings.services && bindings.services.length > 0) {
98
+ logger.warn(
99
+ "⎔ Support for service bindings in local mode is experimental and may change."
100
+ );
101
+ }
102
+ }, [bindings.services]);
103
+
104
+ useEffect(() => {
105
+ const externalDurableObjects = (
106
+ bindings.durable_objects?.bindings || []
107
+ ).filter((binding) => binding.script_name);
108
+
109
+ if (externalDurableObjects.length > 0) {
110
+ logger.warn(
111
+ "⎔ Support for external Durable Objects in local mode is experimental and may change."
112
+ );
113
+ }
114
+ }, [bindings.durable_objects?.bindings]);
115
+
116
+ useEffect(() => {
117
+ const abortController = new AbortController();
118
+ async function startLocalWorker() {
119
+ if (!bundle || !format) return;
120
+
121
+ // port for the worker
122
+ await waitForPortToBeAvailable(port, {
123
+ retryPeriod: 200,
124
+ timeout: 2000,
125
+ abortSignal: abortController.signal,
126
+ });
127
+
128
+ // In local mode, we want to copy all referenced modules into
129
+ // the output bundle directory before starting up
130
+ for (const module of bundle.modules) {
131
+ await writeFile(
132
+ path.join(path.dirname(bundle.path), module.name),
133
+ module.content
134
+ );
135
+ }
136
+
137
+ const scriptPath = realpathSync(bundle.path);
138
+
139
+ // the wasm_modules/text_blobs/data_blobs bindings are
140
+ // relative to process.cwd(), but the actual worker bundle
141
+ // is in the temp output directory; so we rewrite the paths to be absolute,
142
+ // letting miniflare resolve them correctly
143
+
144
+ // wasm
145
+ const wasmBindings: Record<string, string> = {};
146
+ for (const [name, filePath] of Object.entries(
147
+ bindings.wasm_modules || {}
148
+ )) {
149
+ wasmBindings[name] = path.join(process.cwd(), filePath);
150
+ }
151
+
152
+ // text
153
+ const textBlobBindings: Record<string, string> = {};
154
+ for (const [name, filePath] of Object.entries(
155
+ bindings.text_blobs || {}
156
+ )) {
157
+ textBlobBindings[name] = path.join(process.cwd(), filePath);
158
+ }
159
+
160
+ // data
161
+ const dataBlobBindings: Record<string, string> = {};
162
+ for (const [name, filePath] of Object.entries(
163
+ bindings.data_blobs || {}
164
+ )) {
165
+ dataBlobBindings[name] = path.join(process.cwd(), filePath);
166
+ }
167
+
168
+ if (format === "service-worker") {
169
+ for (const { type, name } of bundle.modules) {
170
+ if (type === "compiled-wasm") {
171
+ // In service-worker format, .wasm modules are referenced by global identifiers,
172
+ // so we convert it here.
173
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
174
+ // characters with an underscore.
175
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
176
+ wasmBindings[identifier] = name;
177
+ } else if (type === "text") {
178
+ // In service-worker format, text modules are referenced by global identifiers,
179
+ // so we convert it here.
180
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
181
+ // characters with an underscore.
182
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
183
+ textBlobBindings[identifier] = name;
184
+ } else if (type === "buffer") {
185
+ // In service-worker format, data blobs are referenced by global identifiers,
186
+ // so we convert it here.
187
+ // This identifier has to be a valid JS identifier, so we replace all non alphanumeric
188
+ // characters with an underscore.
189
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
190
+ dataBlobBindings[identifier] = name;
191
+ }
192
+ }
193
+ }
194
+
195
+ const upstream =
196
+ typeof localUpstream === "string"
197
+ ? `${localProtocol}://${localUpstream}`
198
+ : undefined;
199
+
200
+ const internalDurableObjects = (
201
+ bindings.durable_objects?.bindings || []
202
+ ).filter((binding) => !binding.script_name);
203
+ const externalDurableObjects = (
204
+ bindings.durable_objects?.bindings || []
205
+ ).filter((binding) => binding.script_name);
206
+
207
+ // TODO: This was already messy with the custom `disableLogs` and `logOptions`.
208
+ // It's now getting _really_ messy now with Pages ASSETS binding outside and the external Durable Objects inside.
209
+ const options: MiniflareOptions = {
210
+ name: workerName,
211
+ port,
212
+ scriptPath,
213
+ https: localProtocol === "https",
214
+ host: ip,
215
+ modules: format === "modules",
216
+ modulesRules: (rules || [])
217
+ .concat(DEFAULT_MODULE_RULES)
218
+ .map(({ type, globs: include, fallthrough }) => ({
219
+ type,
220
+ include,
221
+ fallthrough,
222
+ })),
223
+ compatibilityDate,
224
+ compatibilityFlags,
225
+ usageModel,
226
+ kvNamespaces: bindings.kv_namespaces?.map((kv) => kv.binding),
227
+ r2Buckets: bindings.r2_buckets?.map((r2) => r2.binding),
228
+ durableObjects: Object.fromEntries(
229
+ internalDurableObjects.map((binding) => [
230
+ binding.name,
231
+ binding.class_name,
232
+ ])
233
+ ),
234
+ externalDurableObjects: Object.fromEntries(
235
+ externalDurableObjects
236
+ .map((binding) => {
237
+ const service = workerDefinitions[binding.script_name as string];
238
+ if (!service) return [binding.name, undefined];
239
+
240
+ const name = service.durableObjects.find(
241
+ (durableObject) =>
242
+ durableObject.className === binding.class_name
243
+ )?.name;
244
+ if (!name) return [binding.name, undefined];
245
+
246
+ return [
247
+ binding.name,
248
+ {
249
+ name,
250
+ host: service.durableObjectsHost,
251
+ port: service.durableObjectsPort,
252
+ },
253
+ ];
254
+ })
255
+ .filter(([_, details]) => !!details)
256
+ ),
257
+ ...(localPersistencePath
258
+ ? {
259
+ cachePersist: path.join(localPersistencePath, "cache"),
260
+ durableObjectsPersist: path.join(localPersistencePath, "do"),
261
+ kvPersist: path.join(localPersistencePath, "kv"),
262
+ r2Persist: path.join(localPersistencePath, "r2"),
263
+ }
264
+ : {
265
+ // We mark these as true, so that they'll
266
+ // persist in the temp directory.
267
+ // This means they'll persist across a dev session,
268
+ // even if we change source and reload,
269
+ // and be deleted when the dev session ends
270
+ cachePersist: true,
271
+ durableObjectsPersist: true,
272
+ kvPersist: true,
273
+ r2Persist: true,
274
+ }),
275
+
276
+ liveReload,
277
+ sitePath: assetPaths?.assetDirectory
278
+ ? path.join(assetPaths.baseDirectory, assetPaths.assetDirectory)
279
+ : undefined,
280
+ siteInclude: assetPaths?.includePatterns.length
281
+ ? assetPaths?.includePatterns
282
+ : undefined,
283
+ siteExclude: assetPaths?.excludePatterns.length
284
+ ? assetPaths.excludePatterns
285
+ : undefined,
286
+ bindings: bindings.vars,
287
+ wasmBindings,
288
+ textBlobBindings,
289
+ dataBlobBindings,
290
+ sourceMap: true,
291
+ logUnhandledRejections: true,
292
+ crons,
293
+ upstream,
294
+ disableLogs: logLevel === "none",
295
+ logOptions: logPrefix ? { prefix: logPrefix } : undefined,
296
+ };
297
+
298
+ // The path to the Miniflare CLI assumes that this file is being run from
299
+ // `wrangler-dist` and that the CLI is found in `miniflare-dist`.
300
+ // If either of those paths change this line needs updating.
301
+ const miniflareCLIPath = path.resolve(
302
+ __dirname,
303
+ "../miniflare-dist/index.mjs"
304
+ );
305
+ const miniflareOptions = JSON.stringify(options, null);
306
+
307
+ logger.log("⎔ Starting a local server...");
308
+ const nodeOptions = [
309
+ "--experimental-vm-modules", // ensures that Miniflare can run ESM Workers
310
+ "--no-warnings", // hide annoying Node warnings
311
+ // "--log=VERBOSE", // uncomment this to Miniflare to log "everything"!
312
+ ];
313
+ if (inspect) {
314
+ nodeOptions.push("--inspect=" + `${ip}:${inspectorPort}`); // start Miniflare listening for a debugger to attach
315
+ }
316
+
317
+ const forkOptions = [miniflareOptions];
318
+
319
+ if (enablePagesAssetsServiceBinding) {
320
+ forkOptions.push(JSON.stringify(enablePagesAssetsServiceBinding));
321
+ }
322
+
323
+ const child = (local.current = fork(miniflareCLIPath, forkOptions, {
324
+ cwd: path.dirname(scriptPath),
325
+ execArgv: nodeOptions,
326
+ stdio: "pipe",
327
+ }));
328
+
329
+ child.on("message", async (messageString) => {
330
+ const message = JSON.parse(messageString as string);
331
+ if (message.ready) {
332
+ // Let's register our presence in the dev registry
333
+ if (workerName) {
334
+ await registerWorker(workerName, {
335
+ protocol: localProtocol,
336
+ mode: "local",
337
+ port,
338
+ host: ip,
339
+ durableObjects: internalDurableObjects.map((binding) => ({
340
+ name: binding.name,
341
+ className: binding.class_name,
342
+ })),
343
+ ...(message.durableObjectsPort
344
+ ? {
345
+ durableObjectsHost: ip,
346
+ durableObjectsPort: message.durableObjectsPort,
347
+ }
348
+ : {}),
349
+ });
350
+ }
351
+ onReady?.();
352
+ }
353
+ });
354
+
355
+ child.on("close", (code) => {
356
+ if (code) {
357
+ logger.log(`Miniflare process exited with code ${code}`);
358
+ }
359
+ });
360
+
361
+ child.stdout?.on("data", (data: Buffer) => {
362
+ process.stdout.write(data);
363
+ });
364
+
365
+ // parse the node inspector url (which may be received in chunks) from stderr
366
+ let stderrData = "";
367
+ let inspectorUrlFound = false;
368
+ child.stderr?.on("data", (data: Buffer) => {
369
+ if (!inspectorUrlFound) {
370
+ stderrData += data.toString();
371
+ const matches =
372
+ /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)[\r|\n]/.exec(
373
+ stderrData
374
+ );
375
+ if (matches) {
376
+ inspectorUrlFound = true;
377
+ setInspectorUrl(matches[1]);
378
+ }
379
+ }
380
+
381
+ process.stderr.write(data);
382
+ });
383
+
384
+ child.on("exit", (code) => {
385
+ if (code) {
386
+ logger.error(`Miniflare process exited with code ${code}`);
387
+ }
388
+ });
389
+
390
+ child.on("error", (error: Error) => {
391
+ logger.error(`Miniflare process failed to spawn`);
392
+ logger.error(error);
393
+ });
394
+
395
+ removeSignalExitListener.current = onExit((_code, _signal) => {
396
+ logger.log("⎔ Shutting down local server.");
397
+ child.kill();
398
+ local.current = undefined;
399
+ });
400
+ }
401
+
402
+ startLocalWorker().catch((err) => {
403
+ logger.error("local worker:", err);
404
+ });
405
+
406
+ return () => {
407
+ abortController.abort();
408
+ if (local.current) {
409
+ logger.log("⎔ Shutting down local server.");
410
+ local.current?.kill();
411
+ local.current = undefined;
412
+ removeSignalExitListener.current && removeSignalExitListener.current();
413
+ removeSignalExitListener.current = undefined;
414
+ }
415
+ };
416
+ }, [
417
+ bundle,
418
+ workerName,
419
+ format,
420
+ port,
421
+ inspectorPort,
422
+ ip,
423
+ bindings.durable_objects?.bindings,
424
+ bindings.kv_namespaces,
425
+ bindings.r2_buckets,
426
+ bindings.vars,
427
+ bindings.services,
428
+ workerDefinitions,
429
+ compatibilityDate,
430
+ compatibilityFlags,
431
+ usageModel,
432
+ localPersistencePath,
433
+ liveReload,
434
+ assetPaths,
435
+ rules,
436
+ bindings.wasm_modules,
437
+ bindings.text_blobs,
438
+ bindings.data_blobs,
439
+ crons,
440
+ localProtocol,
441
+ localUpstream,
442
+ inspect,
443
+ logLevel,
444
+ logPrefix,
445
+ onReady,
446
+ enablePagesAssetsServiceBinding,
447
+ ]);
448
+ return { inspectorUrl };
318
449
  }