wrangler 0.0.0-e2a26a0 → 0.0.0-e3a458e

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 (84) hide show
  1. package/package.json +24 -11
  2. package/pages/functions/filepath-routing.test.ts +212 -36
  3. package/pages/functions/filepath-routing.ts +69 -119
  4. package/pages/functions/routes.ts +8 -17
  5. package/pages/functions/template-worker.ts +3 -9
  6. package/src/__tests__/configuration.test.ts +2598 -0
  7. package/src/__tests__/dev.test.tsx +437 -63
  8. package/src/__tests__/dev2.test.tsx +154 -0
  9. package/src/__tests__/guess-worker-format.test.ts +58 -0
  10. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  11. package/src/__tests__/helpers/mock-account-id.ts +26 -8
  12. package/src/__tests__/helpers/mock-bin.ts +4 -1
  13. package/src/__tests__/helpers/mock-cfetch.ts +5 -5
  14. package/src/__tests__/helpers/mock-console.ts +21 -7
  15. package/src/__tests__/helpers/mock-kv.ts +9 -16
  16. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  17. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  18. package/src/__tests__/helpers/run-in-tmp.ts +3 -0
  19. package/src/__tests__/helpers/run-wrangler.ts +5 -3
  20. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  21. package/src/__tests__/https-options.test.ts +127 -0
  22. package/src/__tests__/index.test.ts +468 -20
  23. package/src/__tests__/jest.setup.ts +37 -5
  24. package/src/__tests__/kv.test.ts +426 -183
  25. package/src/__tests__/logout.test.ts +15 -13
  26. package/src/__tests__/package-manager.test.ts +2 -2
  27. package/src/__tests__/pages.test.ts +44 -0
  28. package/src/__tests__/parse.test.ts +322 -0
  29. package/src/__tests__/publish.test.ts +1733 -344
  30. package/src/__tests__/r2.test.ts +198 -0
  31. package/src/__tests__/route.test.ts +45 -0
  32. package/src/__tests__/secret.test.ts +301 -86
  33. package/src/__tests__/sentry.test.ts +146 -0
  34. package/src/__tests__/tail.test.ts +564 -0
  35. package/src/__tests__/whoami.test.tsx +21 -7
  36. package/src/bundle.ts +142 -0
  37. package/src/cfetch/index.ts +8 -6
  38. package/src/cfetch/internal.ts +60 -22
  39. package/src/cli.ts +10 -0
  40. package/src/config/README.md +107 -0
  41. package/src/config/config.ts +279 -0
  42. package/src/config/diagnostics.ts +80 -0
  43. package/src/config/environment.ts +305 -0
  44. package/src/config/index.ts +52 -0
  45. package/src/config/validation-helpers.ts +468 -0
  46. package/src/config/validation.ts +1057 -0
  47. package/src/{api/preview.ts → create-worker-preview.ts} +59 -21
  48. package/src/create-worker-upload-form.ts +217 -0
  49. package/src/dev/dev.tsx +362 -0
  50. package/src/dev/local.tsx +247 -0
  51. package/src/dev/remote.tsx +203 -0
  52. package/src/dev/use-esbuild.ts +100 -0
  53. package/src/entry.ts +159 -0
  54. package/src/environment-variables.ts +33 -0
  55. package/src/https-options.ts +122 -0
  56. package/src/index.tsx +1030 -766
  57. package/src/inspect.ts +25 -4
  58. package/src/{kv.tsx → kv.ts} +110 -55
  59. package/src/module-collection.ts +212 -22
  60. package/src/open-in-browser.ts +25 -0
  61. package/src/package-manager.ts +21 -15
  62. package/src/pages.tsx +10 -11
  63. package/src/parse.ts +183 -0
  64. package/src/proxy.ts +115 -45
  65. package/src/publish.ts +273 -329
  66. package/src/r2.ts +50 -0
  67. package/src/reporting.ts +131 -0
  68. package/src/selfsigned.d.ts +29 -0
  69. package/src/sites.tsx +66 -33
  70. package/src/tail/filters.ts +279 -0
  71. package/src/tail/index.ts +299 -0
  72. package/src/tail/printing.ts +62 -0
  73. package/src/user.tsx +223 -124
  74. package/src/{api/worker.ts → worker.ts} +44 -36
  75. package/templates/new-worker.js +1 -1
  76. package/templates/new-worker.ts +1 -1
  77. package/templates/tsconfig.json +105 -0
  78. package/wrangler-dist/cli.js +129900 -113128
  79. package/wrangler-dist/cli.js.map +3 -3
  80. package/src/__tests__/helpers/mock-user.ts +0 -27
  81. package/src/api/form_data.ts +0 -134
  82. package/src/config.ts +0 -641
  83. package/src/dev.tsx +0 -834
  84. package/src/tail.tsx +0 -73
@@ -0,0 +1,247 @@
1
+ import { spawn } from "node:child_process";
2
+ import { realpathSync } from "node:fs";
3
+ import { writeFile } from "node:fs/promises";
4
+ import path from "node:path";
5
+ import { useState, useEffect, useRef } from "react";
6
+ import onExit from "signal-exit";
7
+ import useInspector from "../inspect";
8
+ import { DEFAULT_MODULE_RULES } from "../module-collection";
9
+ import { waitForPortToBeAvailable } from "../proxy";
10
+ import type { Config } from "../config";
11
+ import type { AssetPaths } from "../sites";
12
+ import type { CfWorkerInit, CfScriptFormat } from "../worker";
13
+ import type { EsbuildBundle } from "./use-esbuild";
14
+
15
+ export function Local(props: {
16
+ name: undefined | string;
17
+ bundle: EsbuildBundle | undefined;
18
+ format: CfScriptFormat | undefined;
19
+ bindings: CfWorkerInit["bindings"];
20
+ assetPaths: undefined | AssetPaths;
21
+ public: undefined | string;
22
+ port: number;
23
+ ip: string;
24
+ rules: Config["rules"];
25
+ inspectorPort: number;
26
+ enableLocalPersistence: boolean;
27
+ }) {
28
+ const { inspectorUrl } = useLocalWorker({
29
+ name: props.name,
30
+ bundle: props.bundle,
31
+ format: props.format,
32
+ bindings: props.bindings,
33
+ assetPaths: props.assetPaths,
34
+ public: props.public,
35
+ port: props.port,
36
+ ip: props.ip,
37
+ rules: props.rules,
38
+ enableLocalPersistence: props.enableLocalPersistence,
39
+ });
40
+ useInspector({
41
+ inspectorUrl,
42
+ port: props.inspectorPort,
43
+ logToTerminal: false,
44
+ });
45
+ return null;
46
+ }
47
+
48
+ function useLocalWorker(props: {
49
+ name: undefined | string;
50
+ bundle: EsbuildBundle | undefined;
51
+ rules: Config["rules"];
52
+ format: CfScriptFormat | undefined;
53
+ bindings: CfWorkerInit["bindings"];
54
+ assetPaths: undefined | AssetPaths;
55
+ public: undefined | string;
56
+ port: number;
57
+ ip: string;
58
+ enableLocalPersistence: boolean;
59
+ }) {
60
+ // TODO: pass vars via command line
61
+ const { bundle, format, bindings, port, ip, assetPaths } = props;
62
+ const local = useRef<ReturnType<typeof spawn>>();
63
+ const removeSignalExitListener = useRef<() => void>();
64
+ const [inspectorUrl, setInspectorUrl] = useState<string | undefined>();
65
+ useEffect(() => {
66
+ async function startLocalWorker() {
67
+ if (!bundle || !format) return;
68
+
69
+ // port for the worker
70
+ await waitForPortToBeAvailable(port, { retryPeriod: 200, timeout: 2000 });
71
+
72
+ if (props.public) {
73
+ throw new Error(
74
+ '⎔ A "public" folder is not yet supported in local mode.'
75
+ );
76
+ }
77
+
78
+ // In local mode, we want to copy all referenced modules into
79
+ // the output bundle directory before starting up
80
+ for (const module of bundle.modules) {
81
+ await writeFile(
82
+ path.join(path.dirname(bundle.path), module.name),
83
+ module.content
84
+ );
85
+ }
86
+
87
+ console.log("⎔ Starting a local server...");
88
+ // TODO: just use execa for this
89
+ local.current = spawn(
90
+ "node",
91
+ [
92
+ "--experimental-vm-modules",
93
+ "--inspect",
94
+ require.resolve("miniflare/cli"),
95
+ realpathSync(bundle.path),
96
+ "--watch",
97
+ "--wrangler-config",
98
+ path.join(__dirname, "../miniflare-config-stubs/wrangler.empty.toml"),
99
+ "--env",
100
+ path.join(__dirname, "../miniflare-config-stubs/.env.empty"),
101
+ "--package",
102
+ path.join(__dirname, "../miniflare-config-stubs/package.empty.json"),
103
+ "--port",
104
+ port.toString(),
105
+ "--host",
106
+ ip,
107
+ ...(assetPaths
108
+ ? [
109
+ "--site",
110
+ path.join(process.cwd(), assetPaths.baseDirectory),
111
+ ...assetPaths.includePatterns.map((pattern) => [
112
+ "--site-include",
113
+ pattern,
114
+ ]),
115
+ ...assetPaths.excludePatterns.map((pattern) => [
116
+ "--site-exclude",
117
+ pattern,
118
+ ]),
119
+ ].flatMap((x) => x)
120
+ : []),
121
+ ...(props.enableLocalPersistence
122
+ ? ["--kv-persist", "--cache-persist", "--do-persist"]
123
+ : []),
124
+ ...Object.entries(bindings.vars || {}).flatMap(([key, value]) => {
125
+ return ["--binding", `${key}=${value}`];
126
+ }),
127
+ ...(bindings.kv_namespaces || []).flatMap(({ binding }) => {
128
+ return ["--kv", binding];
129
+ }),
130
+ ...(bindings.durable_objects?.bindings || []).flatMap(
131
+ ({ name, class_name }) => {
132
+ return ["--do", `${name}=${class_name}`];
133
+ }
134
+ ),
135
+ ...Object.entries(bindings.wasm_modules || {}).flatMap(
136
+ ([name, filePath]) => {
137
+ return [
138
+ "--wasm",
139
+ `${name}=${path.join(process.cwd(), filePath)}`,
140
+ ];
141
+ }
142
+ ),
143
+ ...bundle.modules.reduce<string[]>((cmd, { name, type }) => {
144
+ if (format === "service-worker") {
145
+ if (type === "compiled-wasm") {
146
+ // In service-worker format, .wasm modules are referenced
147
+ // by global identifiers, so we convert it here.
148
+ // This identifier has to be a valid JS identifier,
149
+ // so we replace all non alphanumeric characters
150
+ // with an underscore.
151
+ const identifier = name.replace(/[^a-zA-Z0-9_$]/g, "_");
152
+ return cmd.concat([`--wasm`, `${identifier}=${name}`]);
153
+ } else {
154
+ // TODO: we should actually support this
155
+ throw new Error(
156
+ `⎔ Unsupported module type ${type} for file ${name} in service-worker format`
157
+ );
158
+ }
159
+ }
160
+ return cmd;
161
+ }, []),
162
+ "--modules",
163
+ String(format === "modules"),
164
+ ...(props.rules || [])
165
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
166
+ .concat(DEFAULT_MODULE_RULES!)
167
+ .flatMap((rule) =>
168
+ rule.globs.flatMap((glob) => [
169
+ "--modules-rule",
170
+ `${rule.type}=${glob}`,
171
+ ])
172
+ ),
173
+ ],
174
+ {
175
+ cwd: path.dirname(realpathSync(bundle.path)),
176
+ }
177
+ );
178
+ console.log(`⬣ Listening at http://localhost:${port}`);
179
+
180
+ local.current.on("close", (code) => {
181
+ if (code) {
182
+ console.log(`miniflare process exited with code ${code}`);
183
+ }
184
+ });
185
+
186
+ local.current.stdout?.on("data", (data: Buffer) => {
187
+ console.log(`${data.toString()}`);
188
+ });
189
+
190
+ local.current.stderr?.on("data", (data: Buffer) => {
191
+ console.error(`${data.toString()}`);
192
+ const matches =
193
+ /Debugger listening on (ws:\/\/127\.0\.0\.1:\d+\/[A-Za-z0-9-]+)/.exec(
194
+ data.toString()
195
+ );
196
+ if (matches) {
197
+ setInspectorUrl(matches[1]);
198
+ }
199
+ });
200
+
201
+ local.current.on("exit", (code) => {
202
+ if (code) {
203
+ console.error(`miniflare process exited with code ${code}`);
204
+ }
205
+ });
206
+
207
+ local.current.on("error", (error: Error) => {
208
+ console.error(`miniflare process failed to spawn`);
209
+ console.error(error);
210
+ });
211
+
212
+ removeSignalExitListener.current = onExit((_code, _signal) => {
213
+ console.log("⎔ Shutting down local server.");
214
+ local.current?.kill();
215
+ local.current = undefined;
216
+ });
217
+ }
218
+
219
+ startLocalWorker().catch((err) => {
220
+ console.error("local worker:", err);
221
+ });
222
+
223
+ return () => {
224
+ if (local.current) {
225
+ console.log("⎔ Shutting down local server.");
226
+ local.current?.kill();
227
+ local.current = undefined;
228
+ removeSignalExitListener.current && removeSignalExitListener.current();
229
+ removeSignalExitListener.current = undefined;
230
+ }
231
+ };
232
+ }, [
233
+ bundle,
234
+ format,
235
+ port,
236
+ ip,
237
+ bindings.durable_objects?.bindings,
238
+ bindings.kv_namespaces,
239
+ bindings.vars,
240
+ props.enableLocalPersistence,
241
+ assetPaths,
242
+ props.public,
243
+ props.rules,
244
+ bindings.wasm_modules,
245
+ ]);
246
+ return { inspectorUrl };
247
+ }
@@ -0,0 +1,203 @@
1
+ import assert from "node:assert";
2
+ import { readFile } from "node:fs/promises";
3
+ import path from "node:path";
4
+ import { useState, useEffect, useRef } from "react";
5
+ import { createWorkerPreview } from "../create-worker-preview";
6
+ import useInspector from "../inspect";
7
+ import { usePreviewServer } from "../proxy";
8
+ import { syncAssets } from "../sites";
9
+ import type { CfPreviewToken } from "../create-worker-preview";
10
+ import type { AssetPaths } from "../sites";
11
+ import type { CfModule, CfWorkerInit, CfScriptFormat } from "../worker";
12
+ import type { EsbuildBundle } from "./use-esbuild";
13
+
14
+ export function Remote(props: {
15
+ name: string | undefined;
16
+ bundle: EsbuildBundle | undefined;
17
+ format: CfScriptFormat | undefined;
18
+ public: undefined | string;
19
+ assetPaths: undefined | AssetPaths;
20
+ port: number;
21
+ ip: string;
22
+ localProtocol: "https" | "http";
23
+ inspectorPort: number;
24
+ accountId: undefined | string;
25
+ apiToken: undefined | string;
26
+ bindings: CfWorkerInit["bindings"];
27
+ compatibilityDate: string | undefined;
28
+ compatibilityFlags: undefined | string[];
29
+ usageModel: undefined | "bundled" | "unbound";
30
+ env: string | undefined;
31
+ legacyEnv: boolean | undefined;
32
+ zone: { id: string; host: string } | undefined;
33
+ }) {
34
+ assert(props.accountId, "accountId is required");
35
+ assert(props.apiToken, "apiToken is required");
36
+ const previewToken = useWorker({
37
+ name: props.name,
38
+ bundle: props.bundle,
39
+ format: props.format,
40
+ modules: props.bundle ? props.bundle.modules : [],
41
+ accountId: props.accountId,
42
+ apiToken: props.apiToken,
43
+ bindings: props.bindings,
44
+ assetPaths: props.assetPaths,
45
+ port: props.port,
46
+ compatibilityDate: props.compatibilityDate,
47
+ compatibilityFlags: props.compatibilityFlags,
48
+ usageModel: props.usageModel,
49
+ env: props.env,
50
+ legacyEnv: props.legacyEnv,
51
+ zone: props.zone,
52
+ });
53
+
54
+ usePreviewServer({
55
+ previewToken,
56
+ publicRoot: props.public,
57
+ localProtocol: props.localProtocol,
58
+ localPort: props.port,
59
+ ip: props.ip,
60
+ });
61
+
62
+ useInspector({
63
+ inspectorUrl: previewToken ? previewToken.inspectorUrl.href : undefined,
64
+ port: props.inspectorPort,
65
+ logToTerminal: true,
66
+ });
67
+ return null;
68
+ }
69
+
70
+ export function useWorker(props: {
71
+ name: string | undefined;
72
+ bundle: EsbuildBundle | undefined;
73
+ format: CfScriptFormat | undefined;
74
+ modules: CfModule[];
75
+ accountId: string;
76
+ apiToken: string;
77
+ bindings: CfWorkerInit["bindings"];
78
+ assetPaths: undefined | AssetPaths;
79
+ port: number;
80
+ compatibilityDate: string | undefined;
81
+ compatibilityFlags: string[] | undefined;
82
+ usageModel: undefined | "bundled" | "unbound";
83
+ env: string | undefined;
84
+ legacyEnv: boolean | undefined;
85
+ zone: { id: string; host: string } | undefined;
86
+ }): CfPreviewToken | undefined {
87
+ const {
88
+ name,
89
+ bundle,
90
+ format,
91
+ modules,
92
+ accountId,
93
+ apiToken,
94
+ bindings,
95
+ assetPaths,
96
+ compatibilityDate,
97
+ compatibilityFlags,
98
+ usageModel,
99
+ port,
100
+ } = props;
101
+ const [token, setToken] = useState<CfPreviewToken | undefined>();
102
+
103
+ // This is the most reliable way to detect whether
104
+ // something's "happened" in our system; We make a ref and
105
+ // mark it once we log our initial message. Refs are vars!
106
+ const startedRef = useRef(false);
107
+
108
+ useEffect(() => {
109
+ async function start() {
110
+ setToken(undefined); // reset token in case we're re-running
111
+
112
+ if (!bundle || !format) return;
113
+
114
+ if (!startedRef.current) {
115
+ startedRef.current = true;
116
+ } else {
117
+ console.log("⎔ Detected changes, restarted server.");
118
+ }
119
+
120
+ const assets = await syncAssets(
121
+ accountId,
122
+ // When we're using the newer service environments, we wouldn't
123
+ // have added the env name on to the script name. However, we must
124
+ // include it in the kv namespace name regardless (since there's no
125
+ // concept of service environments for kv namespaces yet).
126
+ name + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
127
+ assetPaths,
128
+ true
129
+ ); // TODO: cancellable?
130
+
131
+ const content = await readFile(bundle.path, "utf-8");
132
+
133
+ const init: CfWorkerInit = {
134
+ name,
135
+ main: {
136
+ name: path.basename(bundle.path),
137
+ type: format === "modules" ? "esm" : "commonjs",
138
+ content,
139
+ },
140
+ modules: modules.concat(
141
+ assets.manifest
142
+ ? {
143
+ name: "__STATIC_CONTENT_MANIFEST",
144
+ content: JSON.stringify(assets.manifest),
145
+ type: "text",
146
+ }
147
+ : []
148
+ ),
149
+ bindings: {
150
+ ...bindings,
151
+ kv_namespaces: (bindings.kv_namespaces || []).concat(
152
+ assets.namespace
153
+ ? { binding: "__STATIC_CONTENT", id: assets.namespace }
154
+ : []
155
+ ),
156
+ text_blobs: {
157
+ ...bindings.text_blobs,
158
+ ...(assets.manifest &&
159
+ format === "service-worker" && {
160
+ __STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
161
+ }),
162
+ },
163
+ },
164
+ migrations: undefined, // no migrations in dev
165
+ compatibility_date: compatibilityDate,
166
+ compatibility_flags: compatibilityFlags,
167
+ usage_model: usageModel,
168
+ };
169
+ setToken(
170
+ await createWorkerPreview(
171
+ init,
172
+ {
173
+ accountId,
174
+ apiToken,
175
+ },
176
+ { env: props.env, legacyEnv: props.legacyEnv, zone: props.zone }
177
+ )
178
+ );
179
+ }
180
+ start().catch((err) => {
181
+ // we want to log the error, but not end the process
182
+ // since it could recover after the developer fixes whatever's wrong
183
+ console.error("remote worker:", err);
184
+ });
185
+ }, [
186
+ name,
187
+ bundle,
188
+ format,
189
+ accountId,
190
+ apiToken,
191
+ port,
192
+ assetPaths,
193
+ compatibilityDate,
194
+ compatibilityFlags,
195
+ usageModel,
196
+ bindings,
197
+ modules,
198
+ props.env,
199
+ props.legacyEnv,
200
+ props.zone,
201
+ ]);
202
+ return token;
203
+ }
@@ -0,0 +1,100 @@
1
+ import assert from "node:assert";
2
+ import { useState, useEffect } from "react";
3
+ import { bundleWorker } from "../bundle";
4
+ import type { Config } from "../config";
5
+ import type { Entry } from "../entry";
6
+ import type { CfModule } from "../worker";
7
+ import type { WatchMode } from "esbuild";
8
+
9
+ export type EsbuildBundle = {
10
+ id: number;
11
+ path: string;
12
+ entry: Entry;
13
+ type: "esm" | "commonjs";
14
+ modules: CfModule[];
15
+ serveAssetsFromWorker: boolean;
16
+ };
17
+
18
+ export function useEsbuild({
19
+ entry,
20
+ destination,
21
+ staticRoot,
22
+ jsxFactory,
23
+ jsxFragment,
24
+ rules,
25
+ serveAssetsFromWorker,
26
+ }: {
27
+ entry: Entry;
28
+ destination: string | undefined;
29
+ staticRoot: undefined | string;
30
+ jsxFactory: string | undefined;
31
+ jsxFragment: string | undefined;
32
+ rules: Config["rules"];
33
+ serveAssetsFromWorker: boolean;
34
+ }): EsbuildBundle | undefined {
35
+ const [bundle, setBundle] = useState<EsbuildBundle>();
36
+ useEffect(() => {
37
+ let stopWatching: (() => void) | undefined = undefined;
38
+
39
+ const watchMode: WatchMode = {
40
+ async onRebuild(error) {
41
+ if (error) console.error("watch build failed:", error);
42
+ else {
43
+ // nothing really changes here, so let's increment the id
44
+ // to change the return object's identity
45
+ setBundle((previousBundle) => {
46
+ assert(
47
+ previousBundle,
48
+ "Rebuild triggered with no previous build available"
49
+ );
50
+ return { ...previousBundle, id: previousBundle.id + 1 };
51
+ });
52
+ }
53
+ },
54
+ };
55
+
56
+ async function build() {
57
+ if (!destination) return;
58
+
59
+ const { resolvedEntryPointPath, bundleType, modules, stop } =
60
+ await bundleWorker(entry, destination, {
61
+ // In dev, we serve assets from the local proxy before we send the request to the worker.
62
+ serveAssetsFromWorker: false,
63
+ jsxFactory,
64
+ jsxFragment,
65
+ rules,
66
+ watch: watchMode,
67
+ });
68
+
69
+ // Capture the `stop()` method to use as the `useEffect()` destructor.
70
+ stopWatching = stop;
71
+
72
+ setBundle({
73
+ id: 0,
74
+ entry,
75
+ path: resolvedEntryPointPath,
76
+ type: bundleType,
77
+ modules,
78
+ serveAssetsFromWorker,
79
+ });
80
+ }
81
+
82
+ build().catch(() => {
83
+ // esbuild already logs errors to stderr and we don't want to end the process
84
+ // on build errors anyway so this is a no-op error handler
85
+ });
86
+
87
+ return () => {
88
+ stopWatching?.();
89
+ };
90
+ }, [
91
+ entry,
92
+ destination,
93
+ staticRoot,
94
+ jsxFactory,
95
+ jsxFragment,
96
+ serveAssetsFromWorker,
97
+ rules,
98
+ ]);
99
+ return bundle;
100
+ }
package/src/entry.ts ADDED
@@ -0,0 +1,159 @@
1
+ import assert from "node:assert";
2
+ import { existsSync } from "node:fs";
3
+ import path from "node:path";
4
+ import * as esbuild from "esbuild";
5
+ import { execaCommand } from "execa";
6
+ import type { Config } from "./config";
7
+ import type { CfScriptFormat } from "./worker";
8
+ import type { Metafile } from "esbuild";
9
+
10
+ /**
11
+ * An entry point for the Worker.
12
+ *
13
+ * It consists not just of a `file`, but also of a `directory` that is used to resolve relative paths.
14
+ */
15
+ export type Entry = { file: string; directory: string; format: CfScriptFormat };
16
+
17
+ /**
18
+ * Compute the entry-point for the Worker.
19
+ */
20
+ export async function getEntry(
21
+ args: { script?: string; format?: CfScriptFormat | undefined },
22
+ config: Config,
23
+ command: string
24
+ ): Promise<Entry> {
25
+ let file: string;
26
+ let directory = process.cwd();
27
+ if (args.script) {
28
+ // If the script name comes from the command line it is relative to the current working directory.
29
+ file = path.resolve(args.script);
30
+ } else if (config.main === undefined) {
31
+ throw new Error(
32
+ `Missing entry-point: The entry-point should be specified via the command line (e.g. \`wrangler ${command} path/to/script\`) or the \`main\` config field.`
33
+ );
34
+ } else {
35
+ directory = path.resolve(path.dirname(config.configPath ?? "."));
36
+ file = path.resolve(directory, config.main);
37
+ }
38
+
39
+ await runCustomBuild(file, config.build);
40
+
41
+ if (fileExists(file) === false) {
42
+ throw new Error(
43
+ `Could not resolve "${path.relative(process.cwd(), file)}".`
44
+ );
45
+ }
46
+ const format = await guessWorkerFormat(
47
+ file,
48
+ directory,
49
+ args.format ?? config.build?.upload?.format
50
+ );
51
+ return { file, directory, format };
52
+ }
53
+
54
+ export async function runCustomBuild(
55
+ expectedEntry: string,
56
+ build: Config["build"]
57
+ ) {
58
+ if (build?.command) {
59
+ // TODO: add a deprecation message here?
60
+ console.log("running:", build.command);
61
+ await execaCommand(build.command, {
62
+ shell: true,
63
+ stdout: "inherit",
64
+ stderr: "inherit",
65
+ timeout: 1000 * 30,
66
+ ...(build.cwd && { cwd: build.cwd }),
67
+ });
68
+
69
+ if (fileExists(expectedEntry) === false) {
70
+ throw new Error(
71
+ `Could not resolve "${path.relative(
72
+ process.cwd(),
73
+ expectedEntry
74
+ )}" after running custom build: ${build.command}`
75
+ );
76
+ }
77
+ }
78
+ }
79
+
80
+ /**
81
+ * A function to "guess" the type of worker.
82
+ * We do this by running a lightweight build of the actual script,
83
+ * and looking at the metafile generated by esbuild. If it has a default
84
+ * export (or really, any exports), that means it's a "modules" worker.
85
+ * Else, it's a "service-worker" worker. This seems hacky, but works remarkably
86
+ * well in practice.
87
+ */
88
+ export default async function guessWorkerFormat(
89
+ entryFile: string,
90
+ entryWorkingDirectory: string,
91
+ hint: CfScriptFormat | undefined
92
+ ): Promise<CfScriptFormat> {
93
+ const result = await esbuild.build({
94
+ entryPoints: [entryFile],
95
+ absWorkingDir: entryWorkingDirectory,
96
+ metafile: true,
97
+ bundle: false,
98
+ format: "esm",
99
+ write: false,
100
+ });
101
+ // result.metafile is defined because of the `metafile: true` option above.
102
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
103
+ const metafile = result.metafile!;
104
+ const entryPoints = Object.entries(metafile.outputs).filter(
105
+ ([_path, output]) => output.entryPoint !== undefined
106
+ );
107
+ assert(
108
+ entryPoints.length > 0,
109
+ `Cannot find entry-point "${entryFile}" in generated bundle.` +
110
+ listEntryPoints(entryPoints)
111
+ );
112
+ assert(
113
+ entryPoints.length < 2,
114
+ "More than one entry-point found for generated bundle." +
115
+ listEntryPoints(entryPoints)
116
+ );
117
+ const guessedWorkerFormat =
118
+ entryPoints[0][1].exports.length > 0 ? "modules" : "service-worker";
119
+
120
+ if (hint) {
121
+ if (hint !== guessedWorkerFormat) {
122
+ if (hint === "service-worker") {
123
+ throw new Error(
124
+ "You configured this worker to be a 'service-worker', but the file you are trying to build appears to have ES module exports. Please pass `--format modules`, or simply remove the configuration."
125
+ );
126
+ } else {
127
+ throw new Error(
128
+ "You configured this worker to be 'modules', but the file you are trying to build doesn't export a handler. Please pass `--format service-worker`, or simply remove the configuration."
129
+ );
130
+ }
131
+ }
132
+ }
133
+ return guessedWorkerFormat;
134
+ }
135
+
136
+ function listEntryPoints(
137
+ outputs: [string, ValueOf<Metafile["outputs"]>][]
138
+ ): string {
139
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
140
+ }
141
+
142
+ type ValueOf<T> = T[keyof T];
143
+
144
+ /**
145
+ * Returns true if the given `filePath` exists as-is,
146
+ * or if some version of it (by appending a common extension) exists.
147
+ */
148
+ export function fileExists(filePath: string): boolean {
149
+ if (path.extname(filePath) !== "") {
150
+ return existsSync(filePath);
151
+ }
152
+ const base = path.join(path.dirname(filePath), path.basename(filePath));
153
+ for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
154
+ if (existsSync(base + ext)) {
155
+ return true;
156
+ }
157
+ }
158
+ return false;
159
+ }