wrangler 0.0.0-e2f9bb2 → 0.0.0-e305903a

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 (258) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +30 -4
  3. package/bin/wrangler.js +154 -34
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +1437 -21
  6. package/package.json +185 -148
  7. package/src/__tests__/api-dev.test.ts +209 -0
  8. package/src/__tests__/api-devregistry.test.js +56 -0
  9. package/src/__tests__/api.test.ts +80 -0
  10. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  11. package/src/__tests__/config-cache.test.ts +30 -24
  12. package/src/__tests__/configuration.test.ts +4121 -3114
  13. package/src/__tests__/dev.test.tsx +1331 -738
  14. package/src/__tests__/dialogs.test.tsx +40 -0
  15. package/src/__tests__/generate.test.ts +91 -0
  16. package/src/__tests__/guess-worker-format.test.ts +68 -68
  17. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  18. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  19. package/src/__tests__/helpers/mock-bin.ts +20 -20
  20. package/src/__tests__/helpers/mock-cfetch.ts +199 -94
  21. package/src/__tests__/helpers/mock-console.ts +58 -39
  22. package/src/__tests__/helpers/mock-dialogs.ts +115 -51
  23. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  24. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  25. package/src/__tests__/helpers/mock-istty.ts +65 -18
  26. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  27. package/src/__tests__/helpers/mock-kv.ts +26 -26
  28. package/src/__tests__/helpers/mock-oauth-flow.ts +225 -228
  29. package/src/__tests__/helpers/mock-process.ts +39 -0
  30. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  31. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  32. package/src/__tests__/helpers/msw/handlers/index.ts +13 -0
  33. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  34. package/src/__tests__/helpers/msw/handlers/oauth.ts +36 -0
  35. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  36. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  37. package/src/__tests__/helpers/msw/index.ts +4 -0
  38. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  39. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  40. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  41. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  42. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  43. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  44. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  45. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  46. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  47. package/src/__tests__/https-options.test.ts +142 -109
  48. package/src/__tests__/index.test.ts +231 -231
  49. package/src/__tests__/init.test.ts +2689 -1014
  50. package/src/__tests__/jest.setup.ts +147 -30
  51. package/src/__tests__/kv.test.ts +1311 -1094
  52. package/src/__tests__/logger.test.ts +100 -74
  53. package/src/__tests__/metrics.test.ts +450 -0
  54. package/src/__tests__/middleware.scheduled.test.ts +135 -0
  55. package/src/__tests__/middleware.test.ts +726 -0
  56. package/src/__tests__/package-manager.test.ts +312 -165
  57. package/src/__tests__/pages.test.ts +1988 -322
  58. package/src/__tests__/parse.test.ts +253 -245
  59. package/src/__tests__/paths.test.ts +39 -0
  60. package/src/__tests__/publish.test.ts +6955 -4743
  61. package/src/__tests__/pubsub.test.ts +367 -0
  62. package/src/__tests__/r2.test.ts +363 -206
  63. package/src/__tests__/route.test.ts +18 -18
  64. package/src/__tests__/secret.test.ts +624 -426
  65. package/src/__tests__/tail.test.ts +650 -565
  66. package/src/__tests__/test-old-node-version.js +31 -0
  67. package/src/__tests__/user.test.ts +140 -116
  68. package/src/__tests__/validate-dev-props.test.ts +56 -0
  69. package/src/__tests__/version.test.ts +35 -0
  70. package/src/__tests__/whoami.test.tsx +259 -91
  71. package/src/__tests__/worker-namespace.test.ts +319 -0
  72. package/src/abort.d.ts +3 -0
  73. package/src/api/dev.ts +206 -0
  74. package/src/api/index.ts +2 -0
  75. package/src/bundle-reporter.tsx +29 -0
  76. package/src/bundle.ts +721 -134
  77. package/src/cfetch/index.ts +83 -66
  78. package/src/cfetch/internal.ts +267 -90
  79. package/src/cli.ts +23 -7
  80. package/src/config/config.ts +236 -195
  81. package/src/config/diagnostics.ts +61 -61
  82. package/src/config/environment.ts +450 -339
  83. package/src/config/index.ts +258 -38
  84. package/src/config/validation-helpers.ts +379 -357
  85. package/src/config/validation.ts +1769 -1263
  86. package/src/config-cache.ts +81 -41
  87. package/src/create-worker-preview.ts +232 -132
  88. package/src/create-worker-upload-form.ts +285 -224
  89. package/src/d1/backups.tsx +212 -0
  90. package/src/d1/create.tsx +54 -0
  91. package/src/d1/delete.tsx +56 -0
  92. package/src/d1/execute.tsx +294 -0
  93. package/src/d1/formatTimeAgo.ts +14 -0
  94. package/src/d1/index.ts +75 -0
  95. package/src/d1/list.tsx +48 -0
  96. package/src/d1/options.ts +12 -0
  97. package/src/d1/types.tsx +14 -0
  98. package/src/d1/utils.ts +39 -0
  99. package/src/dev/dev-vars.ts +13 -13
  100. package/src/dev/dev.tsx +500 -353
  101. package/src/dev/get-local-persistence-path.tsx +31 -0
  102. package/src/dev/local.tsx +628 -290
  103. package/src/dev/remote.tsx +397 -197
  104. package/src/dev/start-server.ts +443 -0
  105. package/src/dev/use-esbuild.ts +173 -94
  106. package/src/dev/validate-dev-props.ts +31 -0
  107. package/src/dev-registry.tsx +190 -0
  108. package/src/dev.tsx +869 -0
  109. package/src/dialogs.tsx +134 -63
  110. package/src/dispatch-namespace.ts +206 -0
  111. package/src/durable.ts +102 -0
  112. package/src/entry.ts +248 -186
  113. package/src/environment-variables.ts +38 -23
  114. package/src/errors.ts +6 -6
  115. package/src/faye-websocket.d.ts +6 -0
  116. package/src/generate.ts +131 -0
  117. package/src/git-client.ts +42 -0
  118. package/src/global-wrangler-config-path.ts +26 -0
  119. package/src/https-options.ts +84 -80
  120. package/src/index.tsx +2288 -2534
  121. package/src/init.ts +967 -0
  122. package/src/inspect.ts +686 -562
  123. package/src/intl-polyfill.d.ts +123 -123
  124. package/src/is-ci.ts +14 -0
  125. package/src/is-interactive.ts +12 -0
  126. package/src/kv.ts +353 -242
  127. package/src/logger.ts +53 -39
  128. package/src/metrics/index.ts +5 -0
  129. package/src/metrics/metrics-config.ts +239 -0
  130. package/src/metrics/metrics-dispatcher.ts +96 -0
  131. package/src/metrics/metrics-usage-headers.ts +24 -0
  132. package/src/metrics/send-event.ts +93 -0
  133. package/src/miniflare-cli/assets.ts +215 -0
  134. package/src/miniflare-cli/index.ts +200 -33
  135. package/src/miniflare-cli/request-context.ts +18 -18
  136. package/src/module-collection.ts +212 -212
  137. package/src/open-in-browser.ts +5 -14
  138. package/src/package-manager.ts +182 -90
  139. package/src/pages/build.tsx +238 -0
  140. package/src/pages/constants.ts +16 -0
  141. package/src/pages/deployments.tsx +106 -0
  142. package/src/pages/dev.tsx +684 -0
  143. package/src/pages/errors.ts +66 -0
  144. package/src/pages/functions/buildPlugin.ts +110 -0
  145. package/src/pages/functions/buildWorker.ts +156 -0
  146. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  147. package/src/pages/functions/filepath-routing.ts +189 -0
  148. package/src/pages/functions/identifiers.ts +78 -0
  149. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  150. package/src/pages/functions/routes-consolidation.ts +73 -0
  151. package/src/pages/functions/routes-transformation.test.ts +282 -0
  152. package/src/pages/functions/routes-transformation.ts +115 -0
  153. package/src/pages/functions/routes-validation.test.ts +403 -0
  154. package/src/pages/functions/routes-validation.ts +202 -0
  155. package/src/pages/functions/routes.ts +151 -0
  156. package/src/pages/functions.tsx +82 -0
  157. package/src/pages/hash.tsx +13 -0
  158. package/src/pages/index.tsx +94 -0
  159. package/src/pages/projects.tsx +169 -0
  160. package/src/pages/publish.tsx +419 -0
  161. package/src/pages/types.ts +49 -0
  162. package/src/pages/upload.tsx +398 -0
  163. package/src/pages/utils.ts +12 -0
  164. package/src/parse.ts +223 -120
  165. package/src/paths.ts +53 -8
  166. package/src/preview.ts +31 -0
  167. package/src/proxy.ts +435 -383
  168. package/src/publish.ts +837 -441
  169. package/src/pubsub/index.ts +286 -0
  170. package/src/pubsub/pubsub-commands.tsx +623 -0
  171. package/src/r2.ts +100 -19
  172. package/src/selfsigned.d.ts +23 -23
  173. package/src/sites.tsx +279 -200
  174. package/src/tail/filters.ts +108 -110
  175. package/src/tail/index.ts +234 -218
  176. package/src/tail/printing.ts +86 -46
  177. package/src/update-check.ts +11 -11
  178. package/src/user/choose-account.tsx +69 -0
  179. package/src/user/env-vars.ts +46 -0
  180. package/src/user/generate-auth-url.ts +33 -0
  181. package/src/user/generate-random-state.ts +16 -0
  182. package/src/user/index.ts +3 -0
  183. package/src/user/user.tsx +1192 -0
  184. package/src/whoami.tsx +141 -42
  185. package/src/worker.ts +163 -101
  186. package/src/zones.ts +167 -0
  187. package/templates/checked-fetch.js +17 -0
  188. package/templates/d1-beta-facade.js +174 -0
  189. package/templates/experimental-local-cache-stubs.js +27 -0
  190. package/templates/first-party-worker-module-facade.ts +18 -0
  191. package/templates/format-dev-errors.ts +32 -0
  192. package/templates/init-tests/test-jest-new-worker.js +25 -0
  193. package/templates/init-tests/test-vitest-new-worker.js +26 -0
  194. package/templates/middleware/common.ts +62 -0
  195. package/templates/middleware/loader-modules.ts +84 -0
  196. package/templates/middleware/loader-sw.ts +213 -0
  197. package/templates/middleware/middleware-pretty-error.ts +40 -0
  198. package/templates/middleware/middleware-scheduled.ts +15 -0
  199. package/templates/new-worker-scheduled.js +17 -0
  200. package/templates/new-worker-scheduled.ts +32 -0
  201. package/templates/new-worker.js +3 -3
  202. package/templates/new-worker.ts +18 -3
  203. package/templates/no-op-worker.js +10 -0
  204. package/templates/pages-dev-pipeline.ts +35 -0
  205. package/templates/pages-shim.ts +9 -0
  206. package/templates/pages-template-plugin.ts +167 -0
  207. package/templates/pages-template-worker.ts +172 -0
  208. package/templates/serve-static-assets.ts +63 -0
  209. package/templates/service-bindings-module-facade.js +54 -0
  210. package/templates/service-bindings-sw-facade.js +42 -0
  211. package/templates/tsconfig.json +95 -95
  212. package/wrangler-dist/cli.d.ts +841 -0
  213. package/wrangler-dist/cli.js +120834 -70331
  214. package/pages/functions/buildPlugin.ts +0 -92
  215. package/pages/functions/buildWorker.ts +0 -138
  216. package/pages/functions/filepath-routing.ts +0 -189
  217. package/pages/functions/identifiers.ts +0 -78
  218. package/pages/functions/routes.ts +0 -156
  219. package/pages/functions/template-plugin.ts +0 -146
  220. package/pages/functions/template-worker.ts +0 -143
  221. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  222. package/src/miniflare-cli/enum-keys.ts +0 -17
  223. package/src/pages.tsx +0 -1866
  224. package/src/user.tsx +0 -1193
  225. package/templates/static-asset-facade.js +0 -47
  226. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  227. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  228. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  229. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  230. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  231. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  232. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  233. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  234. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  235. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  236. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  237. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  238. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  239. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  240. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  241. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  242. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  243. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  244. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  245. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  246. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  247. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  248. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  249. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  250. package/vendor/wrangler-mime/LICENSE +0 -21
  251. package/vendor/wrangler-mime/Mime.js +0 -97
  252. package/vendor/wrangler-mime/README.md +0 -187
  253. package/vendor/wrangler-mime/cli.js +0 -46
  254. package/vendor/wrangler-mime/index.js +0 -4
  255. package/vendor/wrangler-mime/lite.js +0 -4
  256. package/vendor/wrangler-mime/package.json +0 -52
  257. package/vendor/wrangler-mime/types/other.js +0 -1
  258. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -0,0 +1,684 @@
1
+ import { execSync, spawn } from "node:child_process";
2
+ import { existsSync, readFileSync } from "node:fs";
3
+ import { homedir, tmpdir } from "node:os";
4
+ import { join, resolve } from "node:path";
5
+ import { watch } from "chokidar";
6
+ import * as esbuild from "esbuild";
7
+ import { unstable_dev } from "../api";
8
+ import { esbuildAliasExternalPlugin } from "../bundle";
9
+ import { FatalError } from "../errors";
10
+ import { logger } from "../logger";
11
+ import * as metrics from "../metrics";
12
+ import { getBasePath } from "../paths";
13
+ import { buildFunctions } from "./build";
14
+ import { ROUTES_SPEC_VERSION, SECONDS_TO_WAIT_FOR_PROXY } from "./constants";
15
+ import { FunctionsNoRoutesError, getFunctionsNoRoutesWarning } from "./errors";
16
+ import { validateRoutes } from "./functions/routes-validation";
17
+ import { CLEANUP, CLEANUP_CALLBACKS, pagesBetaWarning } from "./utils";
18
+ import type { AdditionalDevProps } from "../dev";
19
+ import type { RoutesJSONSpec } from "./functions/routes-transformation";
20
+ import type { YargsOptionsToInterface } from "./types";
21
+ import type { Argv } from "yargs";
22
+
23
+ const DURABLE_OBJECTS_BINDING_REGEXP = new RegExp(
24
+ /^(?<binding>[^=]+)=(?<className>[^@\s]+)(@(?<scriptName>.*)$)?$/
25
+ );
26
+
27
+ type PagesDevArgs = YargsOptionsToInterface<typeof Options>;
28
+
29
+ export function Options(yargs: Argv) {
30
+ return yargs
31
+ .positional("directory", {
32
+ type: "string",
33
+ demandOption: undefined,
34
+ description: "The directory of static assets to serve",
35
+ })
36
+ .positional("command", {
37
+ type: "string",
38
+ demandOption: undefined,
39
+ description: "The proxy command to run",
40
+ })
41
+ .options({
42
+ local: {
43
+ type: "boolean",
44
+ default: true,
45
+ description: "Run on my machine",
46
+ },
47
+ "compatibility-date": {
48
+ describe: "Date to use for compatibility checks",
49
+ type: "string",
50
+ },
51
+ "compatibility-flags": {
52
+ describe: "Flags to use for compatibility checks",
53
+ alias: "compatibility-flag",
54
+ type: "string",
55
+ array: true,
56
+ },
57
+
58
+ // TODO
59
+ // For now, all Pages projects are set to 2021-11-02. We're adding compat date soon, and we can then adopt `wrangler dev`'s `default: true`.
60
+ // However, it looks like it isn't actually connected up properly in `wrangler dev` at the moment, hence commenting this out for now.
61
+
62
+ // latest: {
63
+ // describe: "Use the latest version of the worker runtime",
64
+ // type: "boolean",
65
+ // default: false,
66
+ // },
67
+
68
+ ip: {
69
+ type: "string",
70
+ default: "0.0.0.0",
71
+ description: "The IP address to listen on",
72
+ },
73
+ port: {
74
+ type: "number",
75
+ default: 8788,
76
+ description: "The port to listen on (serve from)",
77
+ },
78
+ "inspector-port": {
79
+ type: "number",
80
+ describe: "Port for devtools to connect to",
81
+ },
82
+ proxy: {
83
+ type: "number",
84
+ description: "The port to proxy (where the static assets are served)",
85
+ },
86
+ "script-path": {
87
+ type: "string",
88
+ default: "_worker.js",
89
+ description:
90
+ "The location of the single Worker script if not using functions",
91
+ },
92
+ binding: {
93
+ type: "array",
94
+ description: "Bind variable/secret (KEY=VALUE)",
95
+ alias: "b",
96
+ },
97
+ kv: {
98
+ type: "array",
99
+ description: "KV namespace to bind (--kv KV_BINDING)",
100
+ alias: "k",
101
+ },
102
+ d1: {
103
+ type: "array",
104
+ description: "D1 database to bind",
105
+ },
106
+ do: {
107
+ type: "array",
108
+ description: "Durable Object to bind (--do NAME=CLASS)",
109
+ alias: "o",
110
+ },
111
+ r2: {
112
+ type: "array",
113
+ description: "R2 bucket to bind (--r2 R2_BINDING)",
114
+ },
115
+ "live-reload": {
116
+ type: "boolean",
117
+ default: false,
118
+ description: "Auto reload HTML pages when change is detected",
119
+ },
120
+ "local-protocol": {
121
+ describe: "Protocol to listen to requests on, defaults to http.",
122
+ choices: ["http", "https"] as const,
123
+ },
124
+ "experimental-enable-local-persistence": {
125
+ describe:
126
+ "Enable persistence for local mode (deprecated, use --persist)",
127
+ type: "boolean",
128
+ deprecated: true,
129
+ hidden: true,
130
+ },
131
+ persist: {
132
+ describe:
133
+ "Enable persistence for local mode, using default path: .wrangler/state",
134
+ type: "boolean",
135
+ },
136
+ "persist-to": {
137
+ describe:
138
+ "Specify directory to use for local persistence (implies --persist)",
139
+ type: "string",
140
+ requiresArg: true,
141
+ },
142
+ "node-compat": {
143
+ describe: "Enable node.js compatibility",
144
+ default: false,
145
+ type: "boolean",
146
+ hidden: true,
147
+ },
148
+ config: {
149
+ describe: "Pages does not support wrangler.toml",
150
+ type: "string",
151
+ hidden: true,
152
+ },
153
+ "log-level": {
154
+ choices: ["debug", "info", "log", "warn", "error", "none"] as const,
155
+ describe: "Specify logging level",
156
+ },
157
+ })
158
+ .epilogue(pagesBetaWarning);
159
+ }
160
+
161
+ export const Handler = async ({
162
+ local,
163
+ directory,
164
+ "compatibility-date": compatibilityDate = "2021-11-02",
165
+ "compatibility-flags": compatibilityFlags,
166
+ ip,
167
+ port,
168
+ "inspector-port": inspectorPort,
169
+ proxy: requestedProxyPort,
170
+ "script-path": singleWorkerScriptPath,
171
+ binding: bindings = [],
172
+ kv: kvs = [],
173
+ do: durableObjects = [],
174
+ d1: d1s = [],
175
+ r2: r2s = [],
176
+ "live-reload": liveReload,
177
+ "local-protocol": localProtocol,
178
+ experimentalEnableLocalPersistence,
179
+ persist,
180
+ persistTo,
181
+ "node-compat": nodeCompat,
182
+ config: config,
183
+ _: [_pages, _dev, ...remaining],
184
+ logLevel,
185
+ }: PagesDevArgs) => {
186
+ // Beta message for `wrangler pages <commands>` usage
187
+ logger.log(pagesBetaWarning);
188
+
189
+ type LogLevelArg = "debug" | "info" | "log" | "warn" | "error" | "none";
190
+ if (logLevel) {
191
+ // The YargsOptionsToInterface doesn't handle the passing in of Unions from choices in Yargs
192
+ logger.loggerLevel = logLevel as LogLevelArg;
193
+ }
194
+
195
+ if (!local) {
196
+ throw new FatalError("Only local mode is supported at the moment.", 1);
197
+ }
198
+
199
+ if (config) {
200
+ throw new FatalError("Pages does not support wrangler.toml", 1);
201
+ }
202
+
203
+ const functionsDirectory = "./functions";
204
+ let usingFunctions = existsSync(functionsDirectory);
205
+ let usingWorkerScript = false;
206
+
207
+ const command = remaining;
208
+
209
+ let proxyPort: number | undefined;
210
+
211
+ if (directory !== undefined && command.length > 0) {
212
+ throw new FatalError(
213
+ "Specify either a directory OR a proxy command, not both.",
214
+ 1
215
+ );
216
+ } else if (directory === undefined) {
217
+ proxyPort = await spawnProxyProcess({
218
+ port: requestedProxyPort,
219
+ command,
220
+ });
221
+ if (proxyPort === undefined) return undefined;
222
+ } else {
223
+ directory = resolve(directory);
224
+ }
225
+
226
+ if (experimentalEnableLocalPersistence) {
227
+ logger.warn(
228
+ `--experimental-enable-local-persistence is deprecated.\n` +
229
+ `Move any existing data to .wrangler/state and use --persist, or\n` +
230
+ `use --persist-to=./wrangler-local-state to keep using the old path.`
231
+ );
232
+ }
233
+
234
+ let scriptReadyResolve: () => void;
235
+ const scriptReadyPromise = new Promise<void>(
236
+ (promiseResolve) => (scriptReadyResolve = promiseResolve)
237
+ );
238
+
239
+ let scriptPath = "";
240
+
241
+ // Try to use Functions
242
+ if (usingFunctions) {
243
+ const outfile = join(tmpdir(), `./functionsWorker-${Math.random()}.js`);
244
+ scriptPath = outfile;
245
+
246
+ if (nodeCompat) {
247
+ console.warn(
248
+ "Enabling node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
249
+ );
250
+ }
251
+
252
+ logger.log(`Compiling worker to "${outfile}"...`);
253
+ const onEnd = () => scriptReadyResolve();
254
+ try {
255
+ await buildFunctions({
256
+ outfile,
257
+ functionsDirectory,
258
+ sourcemap: true,
259
+ watch: true,
260
+ onEnd,
261
+ buildOutputDirectory: directory,
262
+ nodeCompat,
263
+ });
264
+ await metrics.sendMetricsEvent("build pages functions");
265
+
266
+ // If Functions found routes, continue using Functions
267
+ watch([functionsDirectory], {
268
+ persistent: true,
269
+ ignoreInitial: true,
270
+ }).on("all", async () => {
271
+ try {
272
+ await buildFunctions({
273
+ outfile,
274
+ functionsDirectory,
275
+ sourcemap: true,
276
+ watch: true,
277
+ onEnd,
278
+ buildOutputDirectory: directory,
279
+ nodeCompat,
280
+ });
281
+ await metrics.sendMetricsEvent("build pages functions");
282
+ } catch (e) {
283
+ if (e instanceof FunctionsNoRoutesError) {
284
+ logger.warn(
285
+ getFunctionsNoRoutesWarning(functionsDirectory, "skipping")
286
+ );
287
+ } else {
288
+ throw e;
289
+ }
290
+ }
291
+ });
292
+ } catch (e) {
293
+ // If there are no Functions, then Pages will only serve assets.
294
+ if (e instanceof FunctionsNoRoutesError) {
295
+ logger.warn(
296
+ getFunctionsNoRoutesWarning(functionsDirectory, "skipping")
297
+ );
298
+ // Resolve anyway and run without Functions
299
+ onEnd();
300
+ // Turn off Functions
301
+ usingFunctions = false;
302
+ } else {
303
+ throw e;
304
+ }
305
+ }
306
+ }
307
+
308
+ // Depending on the result of building Functions, we may not actually be using
309
+ // Functions even if the directory exists.
310
+ if (!usingFunctions) {
311
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
312
+ scriptReadyResolve!();
313
+
314
+ scriptPath =
315
+ directory !== undefined
316
+ ? join(directory, singleWorkerScriptPath)
317
+ : singleWorkerScriptPath;
318
+ usingWorkerScript = existsSync(scriptPath);
319
+
320
+ if (!usingWorkerScript) {
321
+ logger.log("No functions. Shimming...");
322
+ scriptPath = resolve(getBasePath(), "templates/pages-shim.ts");
323
+ } else {
324
+ const runBuild = async () => {
325
+ try {
326
+ await esbuild.build({
327
+ entryPoints: [scriptPath],
328
+ write: false,
329
+ plugins: [blockWorkerJsImports],
330
+ });
331
+ } catch {}
332
+ };
333
+ await runBuild();
334
+ watch([scriptPath], {
335
+ persistent: true,
336
+ ignoreInitial: true,
337
+ }).on("all", async () => {
338
+ await runBuild();
339
+ });
340
+ }
341
+ }
342
+
343
+ await scriptReadyPromise;
344
+
345
+ if (scriptPath === "") {
346
+ // Failed to get a script with or without Functions,
347
+ // something really bad must have happend.
348
+ throw new FatalError(
349
+ "Failed to start wrangler pages dev due to an unknown error",
350
+ 1
351
+ );
352
+ }
353
+
354
+ let entrypoint = scriptPath;
355
+
356
+ // custom _routes.json apply only to Functions or Advanced Mode Pages projects
357
+ if (directory && (usingFunctions || usingWorkerScript)) {
358
+ const routesJSONPath = join(directory, "_routes.json");
359
+
360
+ if (existsSync(routesJSONPath)) {
361
+ let routesJSONContents: string;
362
+ const runBuild = async (
363
+ entrypointFile: string,
364
+ outfile: string,
365
+ routes: string
366
+ ) => {
367
+ await esbuild.build({
368
+ entryPoints: [
369
+ resolve(getBasePath(), "templates/pages-dev-pipeline.ts"),
370
+ ],
371
+ bundle: true,
372
+ sourcemap: true,
373
+ format: "esm",
374
+ plugins: [
375
+ esbuildAliasExternalPlugin({
376
+ __ENTRY_POINT__: entrypointFile,
377
+ }),
378
+ ],
379
+ outfile,
380
+ define: {
381
+ __ROUTES__: routes,
382
+ },
383
+ });
384
+ };
385
+
386
+ try {
387
+ // always run the routes validation first. If _routes.json is invalid we
388
+ // want to throw accordingly and exit.
389
+ routesJSONContents = readFileSync(routesJSONPath, "utf-8");
390
+ validateRoutes(JSON.parse(routesJSONContents), directory);
391
+
392
+ entrypoint = join(
393
+ tmpdir(),
394
+ `${Math.random().toString(36).slice(2)}.js`
395
+ );
396
+ await runBuild(scriptPath, entrypoint, routesJSONContents);
397
+ } catch (err) {
398
+ if (err instanceof FatalError) {
399
+ throw err;
400
+ } else {
401
+ throw new FatalError(
402
+ `Could not validate _routes.json at ${directory}: ${err}`,
403
+ 1
404
+ );
405
+ }
406
+ }
407
+
408
+ watch([routesJSONPath], {
409
+ persistent: true,
410
+ ignoreInitial: true,
411
+ }).on("all", async () => {
412
+ try {
413
+ /**
414
+ * Watch for _routes.json file changes and validate file each time.
415
+ * If file is valid proceed to running the build.
416
+ */
417
+ routesJSONContents = readFileSync(routesJSONPath, "utf-8");
418
+ validateRoutes(JSON.parse(routesJSONContents), directory as string);
419
+ await runBuild(scriptPath, entrypoint, routesJSONContents);
420
+ } catch (err) {
421
+ /**
422
+ * If _routes.json is invalid, don't exit but instead fallback to a sensible default
423
+ * and continue to serve the assets. At the same time make sure we warn users that we
424
+ * we detected an invalid file and that we'll be using a default.
425
+ * This basically equivalates to serving a Functions or _worker.js project as is,
426
+ * without applying any additional routing rules on top.
427
+ */
428
+ const error =
429
+ err instanceof FatalError
430
+ ? err
431
+ : `Could not validate _routes.json at ${directory}: ${err}`;
432
+ const defaultRoutesJSONSpec: RoutesJSONSpec = {
433
+ version: ROUTES_SPEC_VERSION,
434
+ include: ["/*"],
435
+ exclude: [],
436
+ };
437
+
438
+ logger.error(error);
439
+ logger.warn(
440
+ `Falling back to the following _routes.json default: ${JSON.stringify(
441
+ defaultRoutesJSONSpec,
442
+ null,
443
+ 2
444
+ )}`
445
+ );
446
+
447
+ routesJSONContents = JSON.stringify(defaultRoutesJSONSpec);
448
+ await runBuild(scriptPath, entrypoint, routesJSONContents);
449
+ }
450
+ });
451
+ }
452
+ }
453
+
454
+ const { stop, waitUntilExit } = await unstable_dev(
455
+ entrypoint,
456
+ {
457
+ ip,
458
+ port,
459
+ inspectorPort,
460
+ watch: true,
461
+ localProtocol,
462
+ liveReload,
463
+ compatibilityDate,
464
+ compatibilityFlags,
465
+ nodeCompat,
466
+ vars: Object.fromEntries(
467
+ bindings
468
+ .map((binding) => binding.toString().split("="))
469
+ .map(([key, ...values]) => [key, values.join("=")])
470
+ ),
471
+ kv: kvs.map((val) => ({
472
+ binding: val.toString(),
473
+ id: "",
474
+ })),
475
+ durableObjects: durableObjects
476
+ .map((durableObject) => {
477
+ const { binding, className, scriptName } =
478
+ DURABLE_OBJECTS_BINDING_REGEXP.exec(durableObject.toString())
479
+ ?.groups || {};
480
+
481
+ if (!binding || !className) {
482
+ logger.warn(
483
+ "Could not parse Durable Object binding:",
484
+ durableObject.toString()
485
+ );
486
+ return;
487
+ }
488
+
489
+ return {
490
+ name: binding,
491
+ class_name: className,
492
+ script_name: scriptName,
493
+ };
494
+ })
495
+ .filter(Boolean) as AdditionalDevProps["durableObjects"],
496
+ r2: r2s.map((binding) => {
497
+ return { binding: binding.toString(), bucket_name: "" };
498
+ }),
499
+
500
+ d1Databases: d1s.map((binding) => ({
501
+ binding: binding.toString(),
502
+ database_id: "", // Required for types, but unused by dev
503
+ database_name: `local-${binding}`,
504
+ })),
505
+
506
+ enablePagesAssetsServiceBinding: {
507
+ proxyPort,
508
+ directory,
509
+ },
510
+ forceLocal: true,
511
+ persist,
512
+ persistTo,
513
+ showInteractiveDevSession: undefined,
514
+ inspect: true,
515
+ logPrefix: "pages",
516
+ logLevel: logLevel ?? "warn",
517
+ },
518
+ { testMode: false, disableExperimentalWarning: true }
519
+ );
520
+ await metrics.sendMetricsEvent("run pages dev");
521
+
522
+ CLEANUP_CALLBACKS.push(stop);
523
+
524
+ waitUntilExit().then(() => {
525
+ CLEANUP();
526
+ process.exit(0);
527
+ });
528
+
529
+ process.on("exit", CLEANUP);
530
+ process.on("SIGINT", CLEANUP);
531
+ process.on("SIGTERM", CLEANUP);
532
+ };
533
+
534
+ function isWindows() {
535
+ return process.platform === "win32";
536
+ }
537
+
538
+ async function sleep(ms: number) {
539
+ await new Promise((promiseResolve) => setTimeout(promiseResolve, ms));
540
+ }
541
+
542
+ function getPids(pid: number) {
543
+ const pids: number[] = [pid];
544
+ let command: string, regExp: RegExp;
545
+
546
+ if (isWindows()) {
547
+ command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
548
+ regExp = new RegExp(/(\d+)/);
549
+ } else {
550
+ command = `pgrep -P ${pid}`;
551
+ regExp = new RegExp(/(\d+)/);
552
+ }
553
+
554
+ try {
555
+ const newPids = (
556
+ execSync(command)
557
+ .toString()
558
+ .split("\n")
559
+ .map((line) => line.match(regExp))
560
+ .filter((line) => line !== null) as RegExpExecArray[]
561
+ ).map((match) => parseInt(match[1]));
562
+
563
+ pids.push(...newPids.map(getPids).flat());
564
+ } catch {}
565
+
566
+ return pids;
567
+ }
568
+
569
+ function getPort(pid: number) {
570
+ let command: string, regExp: RegExp;
571
+
572
+ if (isWindows()) {
573
+ const drive = homedir().split(":\\")[0];
574
+ command = drive + ":\\windows\\system32\\netstat.exe -nao";
575
+ regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
576
+ } else {
577
+ command = "lsof -nPi";
578
+ regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
579
+ }
580
+
581
+ try {
582
+ const matches = execSync(command)
583
+ .toString()
584
+ .split("\n")
585
+ .map((line) => line.match(regExp))
586
+ .filter((line) => line !== null) as RegExpExecArray[];
587
+
588
+ const match = matches[0];
589
+ if (match) return parseInt(match[1]);
590
+ } catch (thrown) {
591
+ logger.error(
592
+ `Error scanning for ports of process with PID ${pid}: ${thrown}`
593
+ );
594
+ }
595
+ }
596
+
597
+ async function spawnProxyProcess({
598
+ port,
599
+ command,
600
+ }: {
601
+ port?: number;
602
+ command: (string | number)[];
603
+ }): Promise<undefined | number> {
604
+ if (command.length === 0) {
605
+ if (port !== undefined) {
606
+ return port;
607
+ }
608
+
609
+ CLEANUP();
610
+ throw new FatalError(
611
+ "Must specify a directory of static assets to serve or a command to run or a proxy port.",
612
+ 1
613
+ );
614
+ }
615
+
616
+ logger.log(`Running ${command.join(" ")}...`);
617
+ const proxy = spawn(
618
+ command[0].toString(),
619
+ command.slice(1).map((value) => value.toString()),
620
+ {
621
+ shell: isWindows(),
622
+ env: {
623
+ BROWSER: "none",
624
+ ...process.env,
625
+ },
626
+ }
627
+ );
628
+ CLEANUP_CALLBACKS.push(() => {
629
+ proxy.kill();
630
+ });
631
+
632
+ proxy.stdout.on("data", (data) => {
633
+ logger.log(`[proxy]: ${data}`);
634
+ });
635
+
636
+ proxy.stderr.on("data", (data) => {
637
+ logger.error(`[proxy]: ${data}`);
638
+ });
639
+
640
+ proxy.on("close", (code) => {
641
+ logger.error(`Proxy exited with status ${code}.`);
642
+ CLEANUP();
643
+ process.exitCode = code ?? 0;
644
+ });
645
+
646
+ // Wait for proxy process to start...
647
+ while (!proxy.pid) {}
648
+
649
+ if (port === undefined) {
650
+ logger.log(
651
+ `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
652
+ );
653
+ logger.log("To skip, specify the proxy port with --proxy.");
654
+ await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
655
+
656
+ port = getPids(proxy.pid)
657
+ .map(getPort)
658
+ .filter((nr) => nr !== undefined)[0];
659
+
660
+ if (port === undefined) {
661
+ CLEANUP();
662
+ throw new FatalError(
663
+ "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
664
+ 1
665
+ );
666
+ } else {
667
+ logger.log(`Automatically determined the proxy port to be ${port}.`);
668
+ }
669
+ }
670
+
671
+ return port;
672
+ }
673
+
674
+ const blockWorkerJsImports: esbuild.Plugin = {
675
+ name: "block-worker-js-imports",
676
+ setup(build: esbuild.PluginBuild) {
677
+ build.onResolve({ filter: /.*/g }, (_args) => {
678
+ logger.error(
679
+ `_worker.js is importing from another file. This will throw an error if deployed.\nYou should bundle your Worker or remove the import if it is unused.`
680
+ );
681
+ return null;
682
+ });
683
+ },
684
+ };