wrangler 0.0.0-e5d3690 → 0.0.0-e88a54e

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 (98) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/miniflare-dist/index.mjs +79 -0
  3. package/miniflare-dist/index.mjs.map +7 -0
  4. package/package.json +32 -16
  5. package/pages/functions/buildWorker.ts +1 -1
  6. package/pages/functions/filepath-routing.test.ts +212 -28
  7. package/pages/functions/filepath-routing.ts +83 -130
  8. package/pages/functions/routes.ts +11 -18
  9. package/pages/functions/template-worker.ts +3 -9
  10. package/src/__tests__/configuration.test.ts +2796 -0
  11. package/src/__tests__/dev.test.tsx +488 -59
  12. package/src/__tests__/dev2.test.tsx +154 -0
  13. package/src/__tests__/guess-worker-format.test.ts +58 -0
  14. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  15. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  16. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  17. package/src/__tests__/helpers/mock-account-id.ts +48 -0
  18. package/src/__tests__/helpers/mock-bin.ts +36 -0
  19. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +48 -14
  20. package/src/__tests__/helpers/mock-console.ts +70 -0
  21. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  22. package/src/__tests__/helpers/mock-kv.ts +33 -0
  23. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  24. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  25. package/src/__tests__/helpers/run-in-tmp.ts +32 -0
  26. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  27. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  28. package/src/__tests__/https-options.test.ts +127 -0
  29. package/src/__tests__/index.test.ts +777 -75
  30. package/src/__tests__/jest.setup.ts +53 -6
  31. package/src/__tests__/kv.test.ts +674 -491
  32. package/src/__tests__/logout.test.ts +52 -0
  33. package/src/__tests__/package-manager.test.ts +206 -0
  34. package/src/__tests__/pages.test.ts +44 -0
  35. package/src/__tests__/parse.test.ts +322 -0
  36. package/src/__tests__/publish.test.ts +2327 -295
  37. package/src/__tests__/r2.test.ts +198 -0
  38. package/src/__tests__/route.test.ts +45 -0
  39. package/src/__tests__/secret.test.ts +425 -0
  40. package/src/__tests__/sentry.test.ts +146 -0
  41. package/src/__tests__/tail.test.ts +564 -0
  42. package/src/__tests__/whoami.test.tsx +26 -56
  43. package/src/bundle.ts +142 -0
  44. package/src/cfetch/index.ts +13 -19
  45. package/src/cfetch/internal.ts +91 -23
  46. package/src/cli.ts +10 -0
  47. package/src/config/README.md +107 -0
  48. package/src/config/config.ts +218 -0
  49. package/src/config/diagnostics.ts +80 -0
  50. package/src/config/environment.ts +366 -0
  51. package/src/config/index.ts +62 -0
  52. package/src/config/validation-helpers.ts +486 -0
  53. package/src/config/validation.ts +1090 -0
  54. package/src/{api/preview.ts → create-worker-preview.ts} +61 -23
  55. package/src/create-worker-upload-form.ts +217 -0
  56. package/src/dev/dev.tsx +364 -0
  57. package/src/dev/local.tsx +232 -0
  58. package/src/dev/remote.tsx +203 -0
  59. package/src/dev/use-esbuild.ts +100 -0
  60. package/src/dialogs.tsx +2 -2
  61. package/src/entry.ts +208 -0
  62. package/src/environment-variables.ts +33 -0
  63. package/src/https-options.ts +122 -0
  64. package/src/index.tsx +1175 -777
  65. package/src/inspect.ts +95 -21
  66. package/src/{kv.tsx → kv.ts} +104 -61
  67. package/src/miniflare-cli/README.md +30 -0
  68. package/src/miniflare-cli/enum-keys.ts +17 -0
  69. package/src/miniflare-cli/index.ts +37 -0
  70. package/src/module-collection.ts +229 -35
  71. package/src/open-in-browser.ts +25 -0
  72. package/src/package-manager.ts +126 -0
  73. package/src/pages.tsx +39 -32
  74. package/src/parse.ts +183 -0
  75. package/src/paths.ts +26 -0
  76. package/src/proxy.ts +177 -39
  77. package/src/publish.ts +274 -309
  78. package/src/r2.ts +50 -0
  79. package/src/reporting.ts +131 -0
  80. package/src/selfsigned.d.ts +29 -0
  81. package/src/sites.tsx +95 -58
  82. package/src/tail/filters.ts +279 -0
  83. package/src/tail/index.ts +299 -0
  84. package/src/tail/printing.ts +62 -0
  85. package/src/user.tsx +233 -134
  86. package/src/{api/worker.ts → worker.ts} +45 -37
  87. package/templates/new-worker.js +15 -0
  88. package/templates/new-worker.ts +15 -0
  89. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  90. package/templates/tsconfig.json +105 -0
  91. package/wrangler-dist/cli.js +130352 -112740
  92. package/wrangler-dist/cli.js.map +3 -3
  93. package/src/__tests__/run-in-tmp.ts +0 -19
  94. package/src/__tests__/run-wrangler.ts +0 -32
  95. package/src/api/form_data.ts +0 -131
  96. package/src/config.ts +0 -646
  97. package/src/dev.tsx +0 -779
  98. package/src/tail.tsx +0 -73
package/src/entry.ts ADDED
@@ -0,0 +1,208 @@
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
+
52
+ if (format === "service-worker" && hasDurableObjectImplementations(config)) {
53
+ const errorMessage =
54
+ "You seem to be trying to use Durable Objects in a Worker written with Service Worker syntax.";
55
+ const addScriptName =
56
+ "You can use Durable Objects defined in other Workers by specifying a `script_name` in your wrangler.toml, where `script_name` is the name of the Worker that implements that Durable Object. For example:";
57
+ const addScriptNameExamples = generateAddScriptNameExamples(config);
58
+ const migrateText =
59
+ "Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:";
60
+ const migrateUrl =
61
+ "https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/";
62
+ throw new Error(
63
+ `${errorMessage}\n${addScriptName}\n${addScriptNameExamples}\n${migrateText}\n${migrateUrl}`
64
+ );
65
+ }
66
+
67
+ return { file, directory, format };
68
+ }
69
+
70
+ export async function runCustomBuild(
71
+ expectedEntry: string,
72
+ build: Config["build"]
73
+ ) {
74
+ if (build?.command) {
75
+ // TODO: add a deprecation message here?
76
+ console.log("running:", build.command);
77
+ await execaCommand(build.command, {
78
+ shell: true,
79
+ stdout: "inherit",
80
+ stderr: "inherit",
81
+ timeout: 1000 * 30,
82
+ ...(build.cwd && { cwd: build.cwd }),
83
+ });
84
+
85
+ if (fileExists(expectedEntry) === false) {
86
+ throw new Error(
87
+ `Could not resolve "${path.relative(
88
+ process.cwd(),
89
+ expectedEntry
90
+ )}" after running custom build: ${build.command}`
91
+ );
92
+ }
93
+ }
94
+ }
95
+
96
+ /**
97
+ * A function to "guess" the type of worker.
98
+ * We do this by running a lightweight build of the actual script,
99
+ * and looking at the metafile generated by esbuild. If it has a default
100
+ * export (or really, any exports), that means it's a "modules" worker.
101
+ * Else, it's a "service-worker" worker. This seems hacky, but works remarkably
102
+ * well in practice.
103
+ */
104
+ export default async function guessWorkerFormat(
105
+ entryFile: string,
106
+ entryWorkingDirectory: string,
107
+ hint: CfScriptFormat | undefined
108
+ ): Promise<CfScriptFormat> {
109
+ const result = await esbuild.build({
110
+ entryPoints: [entryFile],
111
+ absWorkingDir: entryWorkingDirectory,
112
+ metafile: true,
113
+ bundle: false,
114
+ format: "esm",
115
+ write: false,
116
+ });
117
+ // result.metafile is defined because of the `metafile: true` option above.
118
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
119
+ const metafile = result.metafile!;
120
+ const entryPoints = Object.entries(metafile.outputs).filter(
121
+ ([_path, output]) => output.entryPoint !== undefined
122
+ );
123
+ assert(
124
+ entryPoints.length > 0,
125
+ `Cannot find entry-point "${entryFile}" in generated bundle.` +
126
+ listEntryPoints(entryPoints)
127
+ );
128
+ assert(
129
+ entryPoints.length < 2,
130
+ "More than one entry-point found for generated bundle." +
131
+ listEntryPoints(entryPoints)
132
+ );
133
+ const guessedWorkerFormat =
134
+ entryPoints[0][1].exports.length > 0 ? "modules" : "service-worker";
135
+
136
+ if (hint) {
137
+ if (hint !== guessedWorkerFormat) {
138
+ if (hint === "service-worker") {
139
+ throw new Error(
140
+ "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."
141
+ );
142
+ } else {
143
+ throw new Error(
144
+ "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."
145
+ );
146
+ }
147
+ }
148
+ }
149
+ return guessedWorkerFormat;
150
+ }
151
+
152
+ function listEntryPoints(
153
+ outputs: [string, ValueOf<Metafile["outputs"]>][]
154
+ ): string {
155
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
156
+ }
157
+
158
+ type ValueOf<T> = T[keyof T];
159
+
160
+ /**
161
+ * Returns true if the given `filePath` exists as-is,
162
+ * or if some version of it (by appending a common extension) exists.
163
+ */
164
+ export function fileExists(filePath: string): boolean {
165
+ if (path.extname(filePath) !== "") {
166
+ return existsSync(filePath);
167
+ }
168
+ const base = path.join(path.dirname(filePath), path.basename(filePath));
169
+ for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
170
+ if (existsSync(base + ext)) {
171
+ return true;
172
+ }
173
+ }
174
+ return false;
175
+ }
176
+
177
+ /**
178
+ * Returns true if the given config contains Durable Object bindings that are implemented
179
+ * in this worker instead of being implemented elsewhere, and bound via a `script_name`
180
+ * property in wrangler.toml
181
+ */
182
+ function hasDurableObjectImplementations(config: Config): boolean {
183
+ return config.durable_objects.bindings.some(
184
+ (binding) => binding.script_name === undefined
185
+ );
186
+ }
187
+
188
+ /**
189
+ * Generates some help text based on the Durable Object bindings in a given
190
+ * config indicating how the user can add a `script_name` field to bind an
191
+ * externally defined Durable Object.
192
+ */
193
+ function generateAddScriptNameExamples(config: Config): string {
194
+ function exampleScriptName(binding_name: string): string {
195
+ return `${binding_name.toLowerCase().replaceAll("_", "-")}-worker`;
196
+ }
197
+
198
+ return config.durable_objects.bindings
199
+ .filter((binding) => binding.script_name === undefined)
200
+ .map(({ name, class_name }) => {
201
+ const script_name = exampleScriptName(name);
202
+ const currentBinding = `{ name = ${name}, class_name = ${class_name} }`;
203
+ const fixedBinding = `{ name = ${name}, class_name = ${class_name}, script_name = ${script_name} }`;
204
+
205
+ return `${currentBinding} ==> ${fixedBinding}`;
206
+ })
207
+ .join("\n");
208
+ }
@@ -0,0 +1,33 @@
1
+ /**
2
+ * Create a function used to access an environment variable.
3
+ *
4
+ * This is not memoized to allow us to change the value at runtime, such as in testing.
5
+ * A warning is shown if the client is using a deprecated version - but only once.
6
+ */
7
+ export function getEnvironmentVariableFactory({
8
+ variableName,
9
+ deprecatedName,
10
+ defaultValue,
11
+ }: {
12
+ variableName: string;
13
+ deprecatedName?: string;
14
+ defaultValue?: string;
15
+ }) {
16
+ let hasWarned = false;
17
+ return () => {
18
+ if (process.env[variableName]) {
19
+ return process.env[variableName];
20
+ } else if (deprecatedName && process.env[deprecatedName]) {
21
+ if (!hasWarned) {
22
+ // Only show the warning once.
23
+ hasWarned = true;
24
+ console.warn(
25
+ `Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
26
+ );
27
+ }
28
+ return process.env[deprecatedName];
29
+ } else {
30
+ return defaultValue;
31
+ }
32
+ };
33
+ }
@@ -0,0 +1,122 @@
1
+ import * as fs from "node:fs";
2
+ import { homedir, networkInterfaces } from "node:os";
3
+ import * as path from "node:path";
4
+ import { promisify } from "node:util";
5
+ import type { Attributes, Options } from "selfsigned";
6
+
7
+ // Most of this file has been borrowed from the implementation in Miniflare.
8
+ // See https://github.com/cloudflare/miniflare/blob/870b401ef5/packages/http-server/src/plugin.ts#L313-L397
9
+ // Thanks @mrbbot.
10
+ const CERT_EXPIRY_DAYS = 30;
11
+ const ONE_DAY_IN_MS = 86400000;
12
+
13
+ /**
14
+ * Get the options (i.e. SSL certificates) for running an HTTPS server.
15
+ *
16
+ * The certificates are self-signed and generated locally, and cached in the `CERT_ROOT` directory.
17
+ */
18
+ export async function getHttpsOptions() {
19
+ const certDirectory = path.join(homedir(), ".wrangler/local-cert");
20
+ const keyPath = path.join(certDirectory, "key.pem");
21
+ const certPath = path.join(certDirectory, "cert.pem");
22
+
23
+ const regenerate =
24
+ !fs.existsSync(keyPath) ||
25
+ !fs.existsSync(certPath) ||
26
+ hasCertificateExpired(keyPath, certPath);
27
+
28
+ if (regenerate) {
29
+ console.log("Generating new self-signed certificate...");
30
+ const { key, cert } = await generateCertificate();
31
+ try {
32
+ // Write certificate files so we can reuse them later.
33
+ fs.mkdirSync(certDirectory, { recursive: true });
34
+ fs.writeFileSync(keyPath, key, "utf8");
35
+ fs.writeFileSync(certPath, cert, "utf8");
36
+ } catch (e) {
37
+ const message = e instanceof Error ? e.message : `${e}`;
38
+ console.warn(
39
+ `Unable to cache generated self-signed certificate in ${certDirectory}.\n${message}`
40
+ );
41
+ }
42
+ return { key, cert };
43
+ } else {
44
+ return {
45
+ key: fs.readFileSync(keyPath, "utf8"),
46
+ cert: fs.readFileSync(certPath, "utf8"),
47
+ };
48
+ }
49
+ }
50
+
51
+ /**
52
+ * Determine if the certificate defined in `keyPath` and `certPath` files
53
+ * have expired based on the date when they were last modified.
54
+ */
55
+ function hasCertificateExpired(keyPath: string, certPath: string): boolean {
56
+ const keyStat = fs.statSync(keyPath);
57
+ const certStat = fs.statSync(certPath);
58
+ const created = Math.max(keyStat.mtimeMs, certStat.mtimeMs);
59
+ return Date.now() - created > (CERT_EXPIRY_DAYS - 2) * ONE_DAY_IN_MS;
60
+ }
61
+
62
+ /**
63
+ * Generate a new self-signed certificate and cache it in `CERT_ROOT` directory.
64
+ */
65
+ async function generateCertificate() {
66
+ // `selfsigned` imports `node-forge`, which is a pretty big library.
67
+ // To reduce startup time, only load this dynamically when needed.
68
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
69
+ const generate: typeof import("selfsigned").generate = promisify(
70
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
71
+ require("selfsigned").generate
72
+ );
73
+
74
+ const certAttrs: Attributes = [{ name: "commonName", value: "localhost" }];
75
+
76
+ const certOptions: Options = {
77
+ algorithm: "sha256",
78
+ days: CERT_EXPIRY_DAYS,
79
+ keySize: 2048,
80
+ extensions: [
81
+ { name: "basicConstraints", cA: true },
82
+ {
83
+ name: "keyUsage",
84
+ keyCertSign: true,
85
+ digitalSignature: true,
86
+ nonRepudiation: true,
87
+ keyEncipherment: true,
88
+ dataEncipherment: true,
89
+ },
90
+ {
91
+ name: "extKeyUsage",
92
+ serverAuth: true,
93
+ clientAuth: true,
94
+ codeSigning: true,
95
+ timeStamping: true,
96
+ },
97
+ {
98
+ name: "subjectAltName",
99
+ altNames: [
100
+ { type: 2, value: "localhost" },
101
+ ...getAccessibleHosts().map((ip) => ({ type: 7, ip })),
102
+ ],
103
+ },
104
+ ],
105
+ };
106
+
107
+ const { private: key, cert } = await generate(certAttrs, certOptions);
108
+ return { key, cert };
109
+ }
110
+
111
+ /**
112
+ * Ask the OS for the addresses of locally accessible hosts.
113
+ */
114
+ function getAccessibleHosts(ipv4 = false): string[] {
115
+ const hosts: string[] = [];
116
+ Object.values(networkInterfaces()).forEach((net) =>
117
+ net?.forEach(({ family, address }) => {
118
+ if (!ipv4 || family === "IPv4") hosts.push(address);
119
+ })
120
+ );
121
+ return hosts;
122
+ }