wrangler 0.0.0-e9307365 → 0.0.0-e94b46ff7

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 (199) hide show
  1. package/README.md +35 -49
  2. package/bin/wrangler.js +25 -100
  3. package/config-schema.json +2277 -0
  4. package/package.json +182 -172
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +19 -6
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +2 -3
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +134 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  21. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  22. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +29 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.js +1 -1
  28. package/templates/new-worker.ts +4 -1
  29. package/templates/pages-dev-pipeline.ts +33 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +1 -1
  32. package/templates/pages-template-plugin.ts +53 -18
  33. package/templates/pages-template-worker.ts +49 -12
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +22 -0
  38. package/templates/tsconfig.json +12 -102
  39. package/templates/tsconfig.tsbuildinfo +1 -0
  40. package/wrangler-dist/InspectorProxyWorker.js +460 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +238 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +26533 -167
  45. package/wrangler-dist/cli.js +146609 -141820
  46. package/Cloudflare_CA.pem +0 -18
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -5416
  52. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  53. package/src/__tests__/config-cache.test.ts +0 -42
  54. package/src/__tests__/configuration.test.ts +0 -4022
  55. package/src/__tests__/dev.test.tsx +0 -1294
  56. package/src/__tests__/generate.test.ts +0 -93
  57. package/src/__tests__/guess-worker-format.test.ts +0 -85
  58. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  59. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  60. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  61. package/src/__tests__/helpers/mock-bin.ts +0 -36
  62. package/src/__tests__/helpers/mock-cfetch.ts +0 -263
  63. package/src/__tests__/helpers/mock-console.ts +0 -97
  64. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  65. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  66. package/src/__tests__/helpers/mock-istty.ts +0 -74
  67. package/src/__tests__/helpers/mock-kv.ts +0 -33
  68. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  69. package/src/__tests__/helpers/mock-process.ts +0 -39
  70. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  71. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  72. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  73. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  74. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  75. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  76. package/src/__tests__/https-options.test.ts +0 -163
  77. package/src/__tests__/index.test.ts +0 -245
  78. package/src/__tests__/init.test.ts +0 -1992
  79. package/src/__tests__/jest.setup.ts +0 -150
  80. package/src/__tests__/kv.test.ts +0 -1671
  81. package/src/__tests__/logger.test.ts +0 -141
  82. package/src/__tests__/metrics.test.ts +0 -450
  83. package/src/__tests__/package-manager.test.ts +0 -353
  84. package/src/__tests__/pages.test.ts +0 -1261
  85. package/src/__tests__/parse.test.ts +0 -330
  86. package/src/__tests__/publish.test.ts +0 -6914
  87. package/src/__tests__/pubsub.test.ts +0 -367
  88. package/src/__tests__/r2.test.ts +0 -317
  89. package/src/__tests__/route.test.ts +0 -45
  90. package/src/__tests__/secret.test.ts +0 -492
  91. package/src/__tests__/tail.test.ts +0 -698
  92. package/src/__tests__/test-old-node-version.js +0 -31
  93. package/src/__tests__/user.test.ts +0 -144
  94. package/src/__tests__/validate-dev-props.test.ts +0 -56
  95. package/src/__tests__/version.test.ts +0 -35
  96. package/src/__tests__/whoami.test.tsx +0 -289
  97. package/src/__tests__/worker-namespace.test.ts +0 -327
  98. package/src/abort.d.ts +0 -3
  99. package/src/api/dev.ts +0 -86
  100. package/src/api/index.ts +0 -1
  101. package/src/bundle-reporter.tsx +0 -29
  102. package/src/bundle.ts +0 -472
  103. package/src/cfetch/index.ts +0 -121
  104. package/src/cfetch/internal.ts +0 -181
  105. package/src/cli.ts +0 -27
  106. package/src/config/README.md +0 -107
  107. package/src/config/config.ts +0 -263
  108. package/src/config/diagnostics.ts +0 -80
  109. package/src/config/environment.ts +0 -485
  110. package/src/config/index.ts +0 -251
  111. package/src/config/validation-helpers.ts +0 -584
  112. package/src/config/validation.ts +0 -1856
  113. package/src/config-cache.ts +0 -84
  114. package/src/create-worker-preview.ts +0 -257
  115. package/src/create-worker-upload-form.ts +0 -288
  116. package/src/dev/dev-vars.ts +0 -36
  117. package/src/dev/dev.tsx +0 -531
  118. package/src/dev/local.tsx +0 -385
  119. package/src/dev/remote.tsx +0 -413
  120. package/src/dev/use-esbuild.ts +0 -175
  121. package/src/dev/validate-dev-props.ts +0 -31
  122. package/src/dev-registry.tsx +0 -157
  123. package/src/dev.tsx +0 -616
  124. package/src/dialogs.tsx +0 -135
  125. package/src/durable.ts +0 -102
  126. package/src/entry.ts +0 -328
  127. package/src/environment-variables.ts +0 -35
  128. package/src/errors.ts +0 -11
  129. package/src/faye-websocket.d.ts +0 -6
  130. package/src/generate.ts +0 -131
  131. package/src/git-client.ts +0 -42
  132. package/src/global-wrangler-config-path.ts +0 -26
  133. package/src/https-options.ts +0 -127
  134. package/src/index.tsx +0 -2184
  135. package/src/init.ts +0 -549
  136. package/src/inspect.ts +0 -750
  137. package/src/intl-polyfill.d.ts +0 -139
  138. package/src/is-interactive.ts +0 -12
  139. package/src/kv.ts +0 -430
  140. package/src/logger.ts +0 -73
  141. package/src/metrics/index.ts +0 -5
  142. package/src/metrics/is-ci.ts +0 -14
  143. package/src/metrics/metrics-config.ts +0 -239
  144. package/src/metrics/metrics-dispatcher.ts +0 -96
  145. package/src/metrics/metrics-usage-headers.ts +0 -24
  146. package/src/metrics/send-event.ts +0 -92
  147. package/src/miniflare-cli/README.md +0 -30
  148. package/src/miniflare-cli/assets.ts +0 -543
  149. package/src/miniflare-cli/enum-keys.ts +0 -17
  150. package/src/miniflare-cli/index.ts +0 -85
  151. package/src/miniflare-cli/request-context.ts +0 -40
  152. package/src/module-collection.ts +0 -258
  153. package/src/open-in-browser.ts +0 -17
  154. package/src/package-manager.ts +0 -219
  155. package/src/pages/build.tsx +0 -204
  156. package/src/pages/constants.ts +0 -8
  157. package/src/pages/deployments.tsx +0 -106
  158. package/src/pages/dev.tsx +0 -414
  159. package/src/pages/functions/buildPlugin.ts +0 -105
  160. package/src/pages/functions/buildWorker.ts +0 -151
  161. package/src/pages/functions/filepath-routing.test.ts +0 -234
  162. package/src/pages/functions/filepath-routing.ts +0 -189
  163. package/src/pages/functions/identifiers.ts +0 -78
  164. package/src/pages/functions/routes.ts +0 -151
  165. package/src/pages/index.tsx +0 -84
  166. package/src/pages/projects.tsx +0 -163
  167. package/src/pages/publish.tsx +0 -338
  168. package/src/pages/types.ts +0 -40
  169. package/src/pages/upload.tsx +0 -415
  170. package/src/pages/utils.ts +0 -12
  171. package/src/parse.ts +0 -286
  172. package/src/paths.ts +0 -26
  173. package/src/preview.ts +0 -31
  174. package/src/proxy.ts +0 -476
  175. package/src/publish.ts +0 -807
  176. package/src/pubsub/index.ts +0 -286
  177. package/src/pubsub/pubsub-commands.tsx +0 -623
  178. package/src/r2.ts +0 -118
  179. package/src/selfsigned.d.ts +0 -29
  180. package/src/sites.tsx +0 -372
  181. package/src/tail/filters.ts +0 -279
  182. package/src/tail/index.ts +0 -299
  183. package/src/tail/printing.ts +0 -67
  184. package/src/update-check.ts +0 -19
  185. package/src/user/choose-account.tsx +0 -69
  186. package/src/user/env-vars.ts +0 -46
  187. package/src/user/generate-auth-url.ts +0 -33
  188. package/src/user/generate-random-state.ts +0 -16
  189. package/src/user/index.ts +0 -3
  190. package/src/user/user.tsx +0 -1189
  191. package/src/whoami.tsx +0 -169
  192. package/src/worker-namespace.ts +0 -206
  193. package/src/worker.ts +0 -203
  194. package/src/zones.ts +0 -76
  195. package/templates/first-party-worker-module-facade.ts +0 -18
  196. package/templates/format-dev-errors.ts +0 -32
  197. package/templates/serve-static-assets.ts +0 -63
  198. package/templates/service-bindings-module-facade.js +0 -51
  199. package/templates/service-bindings-sw-facade.js +0 -39
@@ -1,106 +0,0 @@
1
- import { render, Text } from "ink";
2
- import SelectInput from "ink-select-input";
3
- import Table from "ink-table";
4
- import React from "react";
5
- import { format as timeagoFormat } from "timeago.js";
6
- import { fetchResult } from "../cfetch";
7
- import { getConfigCache, saveToConfigCache } from "../config-cache";
8
- import { FatalError } from "../errors";
9
- import * as metrics from "../metrics";
10
- import { requireAuth } from "../user";
11
- import { PAGES_CONFIG_CACHE_FILENAME } from "./constants";
12
- import { listProjects } from "./projects";
13
- import { pagesBetaWarning } from "./utils";
14
- import type { Deployment, PagesConfigCache } from "./types";
15
- import type { ArgumentsCamelCase, Argv } from "yargs";
16
-
17
- type ListArgs = {
18
- "project-name"?: string;
19
- };
20
-
21
- export function ListOptions(yargs: Argv): Argv<ListArgs> {
22
- return yargs
23
- .options({
24
- "project-name": {
25
- type: "string",
26
- description:
27
- "The name of the project you would like to list deployments for",
28
- },
29
- })
30
- .epilogue(pagesBetaWarning);
31
- }
32
-
33
- export async function ListHandler({
34
- projectName,
35
- }: ArgumentsCamelCase<ListArgs>) {
36
- const config = getConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME);
37
- const accountId = await requireAuth(config);
38
-
39
- projectName ??= config.project_name;
40
-
41
- const isInteractive = process.stdin.isTTY;
42
- if (!projectName && isInteractive) {
43
- const projects = await listProjects({ accountId });
44
- projectName = await new Promise((resolve) => {
45
- const { unmount } = render(
46
- <>
47
- <Text>Select a project:</Text>
48
- <SelectInput
49
- items={projects.map((project) => ({
50
- key: project.name,
51
- label: project.name,
52
- value: project,
53
- }))}
54
- onSelect={async (selected) => {
55
- resolve(selected.value.name);
56
- unmount();
57
- }}
58
- />
59
- </>
60
- );
61
- });
62
- }
63
-
64
- if (!projectName) {
65
- throw new FatalError("Must specify a project name.", 1);
66
- }
67
-
68
- const deployments: Array<Deployment> = await fetchResult(
69
- `/accounts/${accountId}/pages/projects/${projectName}/deployments`
70
- );
71
-
72
- const titleCase = (word: string) =>
73
- word.charAt(0).toUpperCase() + word.slice(1);
74
-
75
- const shortSha = (sha: string) => sha.slice(0, 7);
76
-
77
- const getStatus = (deployment: Deployment) => {
78
- // Return a pretty time since timestamp if successful otherwise the status
79
- if (deployment.latest_stage.status === `success`) {
80
- return timeagoFormat(deployment.latest_stage.ended_on);
81
- }
82
- return titleCase(deployment.latest_stage.status);
83
- };
84
-
85
- const data = deployments.map((deployment) => {
86
- return {
87
- Environment: titleCase(deployment.environment),
88
- Branch: deployment.deployment_trigger.metadata.branch,
89
- Source: shortSha(deployment.deployment_trigger.metadata.commit_hash),
90
- Deployment: deployment.url,
91
- Status: getStatus(deployment),
92
- // TODO: Use a url shortener
93
- Build: `https://dash.cloudflare.com/${accountId}/pages/view/${deployment.project_name}/${deployment.id}`,
94
- };
95
- });
96
-
97
- saveToConfigCache<PagesConfigCache>(PAGES_CONFIG_CACHE_FILENAME, {
98
- account_id: accountId,
99
- });
100
-
101
- const { unmount } = render(<Table data={data}></Table>, {
102
- patchConsole: false,
103
- });
104
- unmount();
105
- await metrics.sendMetricsEvent("list pages deployments");
106
- }
package/src/pages/dev.tsx DELETED
@@ -1,414 +0,0 @@
1
- import { execSync, spawn } from "node:child_process";
2
- import { existsSync } from "node:fs";
3
- import { tmpdir } from "node:os";
4
- import { join, resolve } from "node:path";
5
- import { watch } from "chokidar";
6
- import { unstable_dev } from "../api";
7
- import { FatalError } from "../errors";
8
- import { logger } from "../logger";
9
- import * as metrics from "../metrics";
10
- import { buildFunctions } from "./build";
11
- import { SECONDS_TO_WAIT_FOR_PROXY } from "./constants";
12
- import { CLEANUP, CLEANUP_CALLBACKS, pagesBetaWarning } from "./utils";
13
- import type { ArgumentsCamelCase, Argv } from "yargs";
14
-
15
- type PagesDevArgs = {
16
- directory?: string;
17
- command?: string;
18
- local: boolean;
19
- port: number;
20
- proxy?: number;
21
- "script-path": string;
22
- binding?: (string | number)[];
23
- kv?: (string | number)[];
24
- do?: (string | number)[];
25
- "live-reload": boolean;
26
- "local-protocol"?: "https" | "http";
27
- "experimental-enable-local-persistence": boolean;
28
- "node-compat": boolean;
29
- };
30
-
31
- export function Options(yargs: Argv): Argv<PagesDevArgs> {
32
- return yargs
33
- .positional("directory", {
34
- type: "string",
35
- demandOption: undefined,
36
- description: "The directory of static assets to serve",
37
- })
38
- .positional("command", {
39
- type: "string",
40
- demandOption: undefined,
41
- description: "The proxy command to run",
42
- })
43
- .options({
44
- local: {
45
- type: "boolean",
46
- default: true,
47
- description: "Run on my machine",
48
- },
49
- port: {
50
- type: "number",
51
- default: 8788,
52
- description: "The port to listen on (serve from)",
53
- },
54
- proxy: {
55
- type: "number",
56
- description: "The port to proxy (where the static assets are served)",
57
- },
58
- "script-path": {
59
- type: "string",
60
- default: "_worker.js",
61
- description:
62
- "The location of the single Worker script if not using functions",
63
- },
64
- binding: {
65
- type: "array",
66
- description: "Bind variable/secret (KEY=VALUE)",
67
- alias: "b",
68
- },
69
- kv: {
70
- type: "array",
71
- description: "KV namespace to bind",
72
- alias: "k",
73
- },
74
- do: {
75
- type: "array",
76
- description: "Durable Object to bind (NAME=CLASS)",
77
- alias: "o",
78
- },
79
- "live-reload": {
80
- type: "boolean",
81
- default: false,
82
- description: "Auto reload HTML pages when change is detected",
83
- },
84
- "local-protocol": {
85
- describe: "Protocol to listen to requests on, defaults to http.",
86
- choices: ["http", "https"] as const,
87
- },
88
- "experimental-enable-local-persistence": {
89
- type: "boolean",
90
- default: false,
91
- describe: "Enable persistence for this session (only for local mode)",
92
- },
93
- "node-compat": {
94
- describe: "Enable node.js compatibility",
95
- default: false,
96
- type: "boolean",
97
- hidden: true,
98
- },
99
- config: {
100
- describe: "Pages does not support wrangler.toml",
101
- type: "string",
102
- hidden: true,
103
- },
104
- })
105
- .epilogue(pagesBetaWarning);
106
- }
107
-
108
- export const Handler = async ({
109
- local,
110
- directory,
111
- port,
112
- proxy: requestedProxyPort,
113
- "script-path": singleWorkerScriptPath,
114
- binding: bindings = [],
115
- kv: kvs = [],
116
- do: durableObjects = [],
117
- "live-reload": liveReload,
118
- "local-protocol": localProtocol,
119
- "experimental-enable-local-persistence": experimentalEnableLocalPersistence,
120
- "node-compat": nodeCompat,
121
- config: config,
122
- _: [_pages, _dev, ...remaining],
123
- }: ArgumentsCamelCase<PagesDevArgs>) => {
124
- // Beta message for `wrangler pages <commands>` usage
125
- logger.log(pagesBetaWarning);
126
-
127
- if (!local) {
128
- throw new FatalError("Only local mode is supported at the moment.", 1);
129
- }
130
-
131
- if (config) {
132
- throw new FatalError("Pages does not support wrangler.toml", 1);
133
- }
134
-
135
- const functionsDirectory = "./functions";
136
- const usingFunctions = existsSync(functionsDirectory);
137
-
138
- const command = remaining;
139
-
140
- let proxyPort: number | undefined;
141
-
142
- if (directory !== undefined && command.length > 0) {
143
- throw new FatalError(
144
- "Specify either a directory OR a proxy command, not both.",
145
- 1
146
- );
147
- } else if (directory === undefined) {
148
- proxyPort = await spawnProxyProcess({
149
- port: requestedProxyPort,
150
- command,
151
- });
152
- if (proxyPort === undefined) return undefined;
153
- } else {
154
- directory = resolve(directory);
155
- }
156
-
157
- let scriptReadyResolve: () => void;
158
- const scriptReadyPromise = new Promise<void>(
159
- (promiseResolve) => (scriptReadyResolve = promiseResolve)
160
- );
161
-
162
- let scriptPath: string;
163
-
164
- if (usingFunctions) {
165
- const outfile = join(tmpdir(), `./functionsWorker-${Math.random()}.js`);
166
- scriptPath = outfile;
167
-
168
- if (nodeCompat) {
169
- console.warn(
170
- "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."
171
- );
172
- }
173
-
174
- logger.log(`Compiling worker to "${outfile}"...`);
175
-
176
- try {
177
- await buildFunctions({
178
- outfile,
179
- functionsDirectory,
180
- sourcemap: true,
181
- watch: true,
182
- onEnd: () => scriptReadyResolve(),
183
- buildOutputDirectory: directory,
184
- nodeCompat,
185
- });
186
- await metrics.sendMetricsEvent("build pages functions");
187
- } catch {}
188
-
189
- watch([functionsDirectory], {
190
- persistent: true,
191
- ignoreInitial: true,
192
- }).on("all", async () => {
193
- await buildFunctions({
194
- outfile,
195
- functionsDirectory,
196
- sourcemap: true,
197
- watch: true,
198
- onEnd: () => scriptReadyResolve(),
199
- buildOutputDirectory: directory,
200
- nodeCompat,
201
- });
202
- await metrics.sendMetricsEvent("build pages functions");
203
- });
204
- } else {
205
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
206
- scriptReadyResolve!();
207
-
208
- scriptPath =
209
- directory !== undefined
210
- ? join(directory, singleWorkerScriptPath)
211
- : singleWorkerScriptPath;
212
-
213
- if (!existsSync(scriptPath)) {
214
- logger.log("No functions. Shimming...");
215
- scriptPath = resolve(__dirname, "../templates/pages-shim.ts");
216
- }
217
- }
218
-
219
- await scriptReadyPromise;
220
-
221
- const { stop, waitUntilExit } = await unstable_dev(
222
- scriptPath,
223
- {
224
- port,
225
- watch: true,
226
- localProtocol,
227
- liveReload,
228
-
229
- compatibilityDate: "2021-11-02",
230
- nodeCompat,
231
- vars: Object.fromEntries(
232
- bindings
233
- .map((binding) => binding.toString().split("="))
234
- .map(([key, ...values]) => [key, values.join("=")])
235
- ),
236
- kv: kvs.map((val) => ({
237
- binding: val.toString(),
238
- id: "",
239
- })),
240
- durableObjects: durableObjects.map((durableObject) => {
241
- const [name, class_name] = durableObject.toString().split("=");
242
- return {
243
- name,
244
- class_name,
245
- };
246
- }),
247
-
248
- enablePagesAssetsServiceBinding: {
249
- proxyPort,
250
- directory,
251
- },
252
- forceLocal: true,
253
- experimentalEnableLocalPersistence,
254
- showInteractiveDevSession: undefined,
255
- inspect: true,
256
- logLevel: "error",
257
- logPrefix: "pages",
258
- },
259
- true
260
- );
261
- await metrics.sendMetricsEvent("run pages dev");
262
-
263
- waitUntilExit().then(() => {
264
- CLEANUP();
265
- stop();
266
- process.exit(0);
267
- });
268
-
269
- process.on("exit", () => {
270
- CLEANUP();
271
- stop();
272
- });
273
- process.on("SIGINT", () => {
274
- CLEANUP();
275
- stop();
276
- });
277
- process.on("SIGTERM", () => {
278
- CLEANUP();
279
- stop();
280
- });
281
- };
282
-
283
- function isWindows() {
284
- return process.platform === "win32";
285
- }
286
-
287
- async function sleep(ms: number) {
288
- await new Promise((promiseResolve) => setTimeout(promiseResolve, ms));
289
- }
290
-
291
- function getPids(pid: number) {
292
- const pids: number[] = [pid];
293
- let command: string, regExp: RegExp;
294
-
295
- if (isWindows()) {
296
- command = `wmic process where (ParentProcessId=${pid}) get ProcessId`;
297
- regExp = new RegExp(/(\d+)/);
298
- } else {
299
- command = `pgrep -P ${pid}`;
300
- regExp = new RegExp(/(\d+)/);
301
- }
302
-
303
- try {
304
- const newPids = (
305
- execSync(command)
306
- .toString()
307
- .split("\n")
308
- .map((line) => line.match(regExp))
309
- .filter((line) => line !== null) as RegExpExecArray[]
310
- ).map((match) => parseInt(match[1]));
311
-
312
- pids.push(...newPids.map(getPids).flat());
313
- } catch {}
314
-
315
- return pids;
316
- }
317
-
318
- function getPort(pid: number) {
319
- let command: string, regExp: RegExp;
320
-
321
- if (isWindows()) {
322
- command = "\\windows\\system32\\netstat.exe -nao";
323
- regExp = new RegExp(`TCP\\s+.*:(\\d+)\\s+.*:\\d+\\s+LISTENING\\s+${pid}`);
324
- } else {
325
- command = "lsof -nPi";
326
- regExp = new RegExp(`${pid}\\s+.*TCP\\s+.*:(\\d+)\\s+\\(LISTEN\\)`);
327
- }
328
-
329
- try {
330
- const matches = execSync(command)
331
- .toString()
332
- .split("\n")
333
- .map((line) => line.match(regExp))
334
- .filter((line) => line !== null) as RegExpExecArray[];
335
-
336
- const match = matches[0];
337
- if (match) return parseInt(match[1]);
338
- } catch (thrown) {
339
- logger.error(
340
- `Error scanning for ports of process with PID ${pid}: ${thrown}`
341
- );
342
- }
343
- }
344
-
345
- async function spawnProxyProcess({
346
- port,
347
- command,
348
- }: {
349
- port?: number;
350
- command: (string | number)[];
351
- }): Promise<undefined | number> {
352
- if (command.length === 0) {
353
- CLEANUP();
354
- throw new FatalError(
355
- "Must specify a directory of static assets to serve or a command to run.",
356
- 1
357
- );
358
- }
359
-
360
- logger.log(`Running ${command.join(" ")}...`);
361
- const proxy = spawn(
362
- command[0].toString(),
363
- command.slice(1).map((value) => value.toString()),
364
- {
365
- shell: isWindows(),
366
- env: {
367
- BROWSER: "none",
368
- ...process.env,
369
- },
370
- }
371
- );
372
- CLEANUP_CALLBACKS.push(() => {
373
- proxy.kill();
374
- });
375
-
376
- proxy.stdout.on("data", (data) => {
377
- logger.log(`[proxy]: ${data}`);
378
- });
379
-
380
- proxy.stderr.on("data", (data) => {
381
- logger.error(`[proxy]: ${data}`);
382
- });
383
-
384
- proxy.on("close", (code) => {
385
- logger.error(`Proxy exited with status ${code}.`);
386
- });
387
-
388
- // Wait for proxy process to start...
389
- while (!proxy.pid) {}
390
-
391
- if (port === undefined) {
392
- logger.log(
393
- `Sleeping ${SECONDS_TO_WAIT_FOR_PROXY} seconds to allow proxy process to start before attempting to automatically determine port...`
394
- );
395
- logger.log("To skip, specify the proxy port with --proxy.");
396
- await sleep(SECONDS_TO_WAIT_FOR_PROXY * 1000);
397
-
398
- port = getPids(proxy.pid)
399
- .map(getPort)
400
- .filter((nr) => nr !== undefined)[0];
401
-
402
- if (port === undefined) {
403
- CLEANUP();
404
- throw new FatalError(
405
- "Could not automatically determine proxy port. Please specify the proxy port with --proxy.",
406
- 1
407
- );
408
- } else {
409
- logger.log(`Automatically determined the proxy port to be ${port}.`);
410
- }
411
- }
412
-
413
- return port;
414
- }
@@ -1,105 +0,0 @@
1
- import { access, lstat } from "node:fs/promises";
2
- import { dirname, relative, resolve } from "node:path";
3
- import NodeGlobalsPolyfills from "@esbuild-plugins/node-globals-polyfill";
4
- import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
5
- import { build } from "esbuild";
6
-
7
- type Options = {
8
- routesModule: string;
9
- outfile: string;
10
- minify?: boolean;
11
- sourcemap?: boolean;
12
- watch?: boolean;
13
- nodeCompat?: boolean;
14
- onEnd?: () => void;
15
- };
16
-
17
- export function buildPlugin({
18
- routesModule,
19
- outfile = "bundle.js",
20
- minify = false,
21
- sourcemap = false,
22
- watch = false,
23
- nodeCompat,
24
- onEnd = () => {},
25
- }: Options) {
26
- return build({
27
- entryPoints: [resolve(__dirname, "../templates/pages-template-plugin.ts")],
28
- inject: [routesModule],
29
- bundle: true,
30
- format: "esm",
31
- target: "esnext",
32
- outfile,
33
- minify,
34
- sourcemap,
35
- watch,
36
- allowOverwrite: true,
37
- define: { ...(nodeCompat ? { global: "globalThis" } : {}) },
38
- plugins: [
39
- {
40
- name: "wrangler notifier and monitor",
41
- setup(pluginBuild) {
42
- pluginBuild.onEnd((result) => {
43
- if (result.errors.length > 0) {
44
- console.error(
45
- `${result.errors.length} error(s) and ${result.warnings.length} warning(s) when compiling Worker.`
46
- );
47
- } else if (result.warnings.length > 0) {
48
- console.warn(
49
- `${result.warnings.length} warning(s) when compiling Worker.`
50
- );
51
- onEnd();
52
- } else {
53
- console.log("Compiled Worker successfully.");
54
- onEnd();
55
- }
56
- });
57
- },
58
- },
59
- {
60
- name: "Assets",
61
- setup(pluginBuild) {
62
- if (pluginBuild.initialOptions.outfile) {
63
- const outdir = dirname(pluginBuild.initialOptions.outfile);
64
-
65
- pluginBuild.onResolve({ filter: /^assets:/ }, async (args) => {
66
- const directory = resolve(
67
- args.resolveDir,
68
- args.path.slice("assets:".length)
69
- );
70
-
71
- const exists = await access(directory)
72
- .then(() => true)
73
- .catch(() => false);
74
-
75
- const isDirectory =
76
- exists && (await lstat(directory)).isDirectory();
77
-
78
- if (!isDirectory) {
79
- return {
80
- errors: [
81
- {
82
- text: `'${directory}' does not exist or is not a directory.`,
83
- },
84
- ],
85
- };
86
- }
87
-
88
- const path = `assets:./${relative(outdir, directory)}`;
89
-
90
- return { path, external: true, namespace: "assets" };
91
- });
92
- }
93
- },
94
- },
95
- ...(nodeCompat
96
- ? [
97
- NodeGlobalsPolyfills({
98
- buffer: true,
99
- }),
100
- NodeModulesPolyfills(),
101
- ]
102
- : []),
103
- ],
104
- });
105
- }