wrangler 0.0.0-e3cab74 → 0.0.0-e452a35

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 (102) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +27 -14
  3. package/bin/wrangler.js +49 -5
  4. package/miniflare-dist/index.mjs +4886 -0
  5. package/package.json +42 -28
  6. package/pages/functions/buildPlugin.ts +105 -0
  7. package/pages/functions/buildWorker.ts +93 -4
  8. package/pages/functions/filepath-routing.test.ts +136 -25
  9. package/pages/functions/filepath-routing.ts +14 -3
  10. package/pages/functions/routes.ts +6 -1
  11. package/pages/functions/template-plugin.ts +147 -0
  12. package/pages/functions/template-worker.ts +21 -8
  13. package/src/__tests__/config-cache.test.ts +36 -0
  14. package/src/__tests__/configuration.test.ts +1514 -367
  15. package/src/__tests__/dev.test.tsx +870 -84
  16. package/src/__tests__/guess-worker-format.test.ts +37 -18
  17. package/src/__tests__/helpers/mock-account-id.ts +22 -4
  18. package/src/__tests__/helpers/mock-cfetch.ts +8 -4
  19. package/src/__tests__/helpers/mock-console.ts +35 -10
  20. package/src/__tests__/helpers/mock-dialogs.ts +26 -1
  21. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  22. package/src/__tests__/helpers/mock-istty.ts +27 -0
  23. package/src/__tests__/helpers/mock-kv.ts +9 -16
  24. package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
  25. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +10 -0
  27. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  28. package/src/__tests__/https-options.test.ts +130 -0
  29. package/src/__tests__/index.test.ts +137 -747
  30. package/src/__tests__/init.test.ts +1557 -0
  31. package/src/__tests__/jest.setup.ts +28 -8
  32. package/src/__tests__/kv.test.ts +598 -258
  33. package/src/__tests__/logger.test.ts +115 -0
  34. package/src/__tests__/pages.test.ts +657 -0
  35. package/src/__tests__/parse.test.ts +8 -0
  36. package/src/__tests__/publish.test.ts +4003 -941
  37. package/src/__tests__/r2.test.ts +69 -34
  38. package/src/__tests__/route.test.ts +45 -0
  39. package/src/__tests__/secret.test.ts +228 -73
  40. package/src/__tests__/tail.test.ts +146 -20
  41. package/src/__tests__/user.test.ts +131 -0
  42. package/src/__tests__/whoami.test.tsx +26 -7
  43. package/src/abort.d.ts +3 -0
  44. package/src/bundle.ts +74 -7
  45. package/src/cfetch/index.ts +21 -4
  46. package/src/cfetch/internal.ts +20 -14
  47. package/src/cli.ts +5 -11
  48. package/src/config/README.md +7 -7
  49. package/src/config/config.ts +69 -100
  50. package/src/config/environment.ts +119 -4
  51. package/src/config/index.ts +177 -4
  52. package/src/config/validation-helpers.ts +228 -23
  53. package/src/config/validation.ts +687 -174
  54. package/src/config-cache.ts +45 -0
  55. package/src/{api/preview.ts → create-worker-preview.ts} +74 -36
  56. package/src/{api/form_data.ts → create-worker-upload-form.ts} +55 -18
  57. package/src/dev/dev-vars.ts +36 -0
  58. package/src/dev/dev.tsx +422 -0
  59. package/src/dev/local.tsx +318 -0
  60. package/src/dev/remote.tsx +227 -0
  61. package/src/dev/use-esbuild.ts +118 -0
  62. package/src/dialogs.tsx +16 -6
  63. package/src/durable.ts +102 -0
  64. package/src/entry.ts +279 -14
  65. package/src/environment-variables.ts +3 -1
  66. package/src/errors.ts +11 -0
  67. package/src/https-options.ts +123 -0
  68. package/src/index.tsx +1268 -806
  69. package/src/inspect.ts +64 -11
  70. package/src/intl-polyfill.d.ts +139 -0
  71. package/src/{kv.tsx → kv.ts} +195 -62
  72. package/src/logger.ts +66 -0
  73. package/src/miniflare-cli/README.md +30 -0
  74. package/src/miniflare-cli/enum-keys.ts +17 -0
  75. package/src/miniflare-cli/index.ts +41 -0
  76. package/src/miniflare-cli/request-context.ts +40 -0
  77. package/src/module-collection.ts +94 -6
  78. package/src/open-in-browser.ts +9 -3
  79. package/src/package-manager.ts +9 -8
  80. package/src/pages.tsx +1057 -75
  81. package/src/parse.ts +24 -5
  82. package/src/proxy.ts +143 -54
  83. package/src/publish.ts +444 -229
  84. package/src/selfsigned.d.ts +29 -0
  85. package/src/sites.tsx +98 -44
  86. package/src/tail/index.ts +2 -2
  87. package/src/tail/printing.ts +13 -8
  88. package/src/update-check.ts +19 -0
  89. package/src/user.tsx +263 -109
  90. package/src/whoami.tsx +2 -1
  91. package/src/{api/worker.ts → worker.ts} +24 -30
  92. package/templates/gitignore +171 -0
  93. package/templates/new-worker.ts +16 -1
  94. package/templates/static-asset-facade.js +1 -1
  95. package/wrangler-dist/cli.js +55345 -69246
  96. package/src/__tests__/helpers/mock-user.ts +0 -27
  97. package/src/__tests__/logout.test.ts +0 -50
  98. package/src/__tests__/sentry.test.ts +0 -146
  99. package/src/dev.tsx +0 -961
  100. package/src/guess-worker-format.ts +0 -68
  101. package/src/reporting.ts +0 -115
  102. package/wrangler-dist/cli.js.map +0 -7
package/src/dialogs.tsx CHANGED
@@ -1,24 +1,28 @@
1
+ import chalk from "chalk";
1
2
  import { Box, Text, useInput, render } from "ink";
2
3
  import TextInput from "ink-text-input";
3
4
  import * as React from "react";
4
5
  import { useState } from "react";
6
+ import { logger } from "./logger";
5
7
  type ConfirmProps = {
6
8
  text: string;
7
9
  onConfirm: (answer: boolean) => void;
8
10
  };
9
11
  function Confirm(props: ConfirmProps) {
10
- useInput((input: string) => {
11
- if (input === "y") {
12
+ useInput((input: string, key) => {
13
+ if (input === "y" || key.return === true) {
12
14
  props.onConfirm(true);
13
15
  } else if (input === "n") {
14
16
  props.onConfirm(false);
15
17
  } else {
16
- console.log("Unrecognised input");
18
+ logger.warn("Unrecognised input:", input);
17
19
  }
18
20
  });
19
21
  return (
20
22
  <Box>
21
- <Text>{props.text} (y/n) </Text>
23
+ <Text>
24
+ {props.text} ({chalk.bold("y")}/n)
25
+ </Text>
22
26
  </Box>
23
27
  );
24
28
  }
@@ -39,12 +43,13 @@ export function confirm(text: string): Promise<boolean> {
39
43
 
40
44
  type PromptProps = {
41
45
  text: string;
46
+ defaultValue?: string;
42
47
  type?: "text" | "password";
43
48
  onSubmit: (text: string) => void;
44
49
  };
45
50
 
46
51
  function Prompt(props: PromptProps) {
47
- const [value, setValue] = useState("");
52
+ const [value, setValue] = useState(props.defaultValue || "");
48
53
 
49
54
  return (
50
55
  <Box>
@@ -61,11 +66,16 @@ function Prompt(props: PromptProps) {
61
66
  );
62
67
  }
63
68
 
64
- export async function prompt(text: string, type: "text" | "password" = "text") {
69
+ export async function prompt(
70
+ text: string,
71
+ type: "text" | "password" = "text",
72
+ defaultValue?: string
73
+ ): Promise<string> {
65
74
  return new Promise((resolve) => {
66
75
  const { unmount } = render(
67
76
  <Prompt
68
77
  text={text}
78
+ defaultValue={defaultValue}
69
79
  type={type}
70
80
  onSubmit={(inputText) => {
71
81
  unmount();
package/src/durable.ts ADDED
@@ -0,0 +1,102 @@
1
+ import assert from "node:assert";
2
+ import { fetchResult } from "./cfetch";
3
+ import { logger } from "./logger";
4
+ import type { Config } from "./config";
5
+ import type { CfWorkerInit } from "./worker";
6
+
7
+ /**
8
+ * For a given Worker + migrations config, figure out which migrations
9
+ * to upload based on the current migration tag of the deployed Worker.
10
+ */
11
+ export async function getMigrationsToUpload(
12
+ scriptName: string,
13
+ props: {
14
+ accountId: string | undefined;
15
+ config: Config;
16
+ legacyEnv: boolean | undefined;
17
+ env: string | undefined;
18
+ }
19
+ ): Promise<CfWorkerInit["migrations"]> {
20
+ const { config, accountId } = props;
21
+
22
+ assert(accountId, "Missing accountId");
23
+ // if config.migrations
24
+ let migrations;
25
+ if (config.migrations.length > 0) {
26
+ // get current migration tag
27
+ type ScriptData = { id: string; migration_tag?: string };
28
+ let script: ScriptData | undefined;
29
+ if (!props.legacyEnv) {
30
+ try {
31
+ if (props.env) {
32
+ const scriptData = await fetchResult<{
33
+ script: ScriptData;
34
+ }>(
35
+ `/accounts/${accountId}/workers/services/${scriptName}/environments/${props.env}`
36
+ );
37
+ script = scriptData.script;
38
+ } else {
39
+ const scriptData = await fetchResult<{
40
+ default_environment: {
41
+ script: ScriptData;
42
+ };
43
+ }>(`/accounts/${accountId}/workers/services/${scriptName}`);
44
+ script = scriptData.default_environment.script;
45
+ }
46
+ } catch (err) {
47
+ if (
48
+ ![
49
+ 10090, // corresponds to workers.api.error.service_not_found, so the script wasn't previously published at all
50
+ 10092, // workers.api.error.environment_not_found, so the script wasn't published to this environment yet
51
+ ].includes((err as { code: number }).code)
52
+ ) {
53
+ throw err;
54
+ }
55
+ // else it's a 404, no script found, and we can proceed
56
+ }
57
+ } else {
58
+ const scripts = await fetchResult<ScriptData[]>(
59
+ `/accounts/${accountId}/workers/scripts`
60
+ );
61
+ script = scripts.find(({ id }) => id === scriptName);
62
+ }
63
+
64
+ if (script?.migration_tag) {
65
+ // was already published once
66
+ const scriptMigrationTag = script.migration_tag;
67
+ const foundIndex = config.migrations.findIndex(
68
+ (migration) => migration.tag === scriptMigrationTag
69
+ );
70
+ if (foundIndex === -1) {
71
+ logger.warn(
72
+ `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
73
+ );
74
+ migrations = {
75
+ old_tag: script.migration_tag,
76
+ new_tag: config.migrations[config.migrations.length - 1].tag,
77
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
78
+ };
79
+ } else {
80
+ if (foundIndex !== config.migrations.length - 1) {
81
+ // there are new migrations to send up
82
+ migrations = {
83
+ old_tag: script.migration_tag,
84
+ new_tag: config.migrations[config.migrations.length - 1].tag,
85
+ steps: config.migrations
86
+ .slice(foundIndex + 1)
87
+ .map(({ tag: _tag, ...rest }) => rest),
88
+ };
89
+ }
90
+ // else, we're up to date, no migrations to send
91
+ }
92
+ } else {
93
+ // first time publishing durable objects to this script,
94
+ // so we send all the migrations
95
+ migrations = {
96
+ new_tag: config.migrations[config.migrations.length - 1].tag,
97
+ steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
98
+ };
99
+ }
100
+ }
101
+ return migrations;
102
+ }
package/src/entry.ts CHANGED
@@ -1,44 +1,217 @@
1
- import { existsSync } from "node:fs";
1
+ import assert from "node:assert";
2
+ import { existsSync, statSync } from "node:fs";
2
3
  import path from "node:path";
4
+ import * as esbuild from "esbuild";
5
+ import { execaCommand } from "execa";
6
+ import { logger } from "./logger";
3
7
  import type { Config } from "./config";
8
+ import type { CfScriptFormat } from "./worker";
9
+ import type { Metafile } from "esbuild";
4
10
 
5
11
  /**
6
12
  * An entry point for the Worker.
7
13
  *
8
14
  * It consists not just of a `file`, but also of a `directory` that is used to resolve relative paths.
9
15
  */
10
- export type Entry = { file: string; directory: string };
16
+ export type Entry = { file: string; directory: string; format: CfScriptFormat };
11
17
 
12
18
  /**
13
19
  * Compute the entry-point for the Worker.
14
20
  */
15
- export function getEntry(
21
+ export async function getEntry(
22
+ args: { script?: string; format?: CfScriptFormat | undefined },
16
23
  config: Config,
17
- command: string,
18
- script?: string
19
- ): Entry {
24
+ command: "dev" | "publish"
25
+ ): Promise<Entry> {
20
26
  let file: string;
21
27
  let directory = process.cwd();
22
- if (script) {
28
+ if (args.script) {
23
29
  // If the script name comes from the command line it is relative to the current working directory.
24
- file = path.resolve(script);
30
+ file = path.resolve(args.script);
25
31
  } else if (config.main === undefined) {
26
- throw new Error(
27
- `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.`
28
- );
32
+ if (config.site?.["entry-point"]) {
33
+ directory = path.resolve(path.dirname(config.configPath ?? "."));
34
+ file = path.extname(config.site?.["entry-point"])
35
+ ? path.resolve(config.site?.["entry-point"])
36
+ : // site.entry-point could be a directory
37
+ path.resolve(config.site?.["entry-point"], "index.js");
38
+ } else {
39
+ throw new Error(
40
+ `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.`
41
+ );
42
+ }
29
43
  } else {
30
44
  directory = path.resolve(path.dirname(config.configPath ?? "."));
31
45
  file = path.resolve(directory, config.main);
32
46
  }
33
47
 
34
- if (!config.build?.command && fileExists(file) === false) {
48
+ const relativeFile = path.relative(directory, file) || ".";
49
+ await runCustomBuild(file, relativeFile, config.build);
50
+
51
+ if (fileExists(file) === false) {
52
+ throw new Error(
53
+ getMissingEntryPointMessage(
54
+ `The entry-point file at "${relativeFile}" was not found.`,
55
+ file,
56
+ relativeFile
57
+ )
58
+ );
59
+ }
60
+ const format = await guessWorkerFormat(
61
+ file,
62
+ directory,
63
+ args.format ?? config.build?.upload?.format,
64
+ config.tsconfig
65
+ );
66
+
67
+ const { localBindings, remoteBindings } =
68
+ partitionDurableObjectBindings(config);
69
+
70
+ if (command === "dev" && remoteBindings.length > 0) {
71
+ logger.warn(
72
+ "WARNING: You have Durable Object bindings that are not defined locally in the worker being developed.\n" +
73
+ "Be aware that changes to the data stored in these Durable Objects will be permanent and affect the live instances.\n" +
74
+ "Remote Durable Objects that are affected:\n" +
75
+ remoteBindings.map((b) => `- ${JSON.stringify(b)}`).join("\n")
76
+ );
77
+ }
78
+
79
+ if (format === "service-worker" && localBindings.length > 0) {
80
+ const errorMessage =
81
+ "You seem to be trying to use Durable Objects in a Worker written as a service-worker.";
82
+ const addScriptName =
83
+ "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:";
84
+ const addScriptNameExamples = generateAddScriptNameExamples(localBindings);
85
+ const migrateText =
86
+ "Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:";
87
+ const migrateUrl =
88
+ "https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/";
35
89
  throw new Error(
36
- `Could not resolve "${path.relative(process.cwd(), file)}".`
90
+ `${errorMessage}\n${addScriptName}\n${addScriptNameExamples}\n${migrateText}\n${migrateUrl}`
37
91
  );
38
92
  }
39
- return { file, directory };
93
+
94
+ return { file, directory, format };
95
+ }
96
+
97
+ export async function runCustomBuild(
98
+ expectedEntryAbsolute: string,
99
+ expectedEntryRelative: string,
100
+ build: Config["build"]
101
+ ) {
102
+ if (build?.command) {
103
+ // TODO: add a deprecation message here?
104
+ logger.log("Running custom build:", build.command);
105
+ await execaCommand(build.command, {
106
+ shell: true,
107
+ // we keep these two as "inherit" so that
108
+ // logs are still visible.
109
+ stdout: "inherit",
110
+ stderr: "inherit",
111
+ ...(build.cwd && { cwd: build.cwd }),
112
+ });
113
+
114
+ if (fileExists(expectedEntryAbsolute) === false) {
115
+ throw new Error(
116
+ getMissingEntryPointMessage(
117
+ `The expected output file at "${expectedEntryRelative}" was not found after running custom build: ${build.command}.\n` +
118
+ "The `main` property in wrangler.toml should point to the file generated by the custom build.",
119
+ expectedEntryAbsolute,
120
+ expectedEntryRelative
121
+ )
122
+ );
123
+ }
124
+ }
125
+ }
126
+
127
+ /**
128
+ * A function to "guess" the type of worker.
129
+ * We do this by running a lightweight build of the actual script,
130
+ * and looking at the metafile generated by esbuild. If it has a default
131
+ * export (or really, any exports), that means it's a "modules" worker.
132
+ * Else, it's a "service-worker" worker. This seems hacky, but works remarkably
133
+ * well in practice.
134
+ */
135
+ export default async function guessWorkerFormat(
136
+ entryFile: string,
137
+ entryWorkingDirectory: string,
138
+ hint: CfScriptFormat | undefined,
139
+ tsconfig?: string | undefined
140
+ ): Promise<CfScriptFormat> {
141
+ const result = await esbuild.build({
142
+ entryPoints: [entryFile],
143
+ absWorkingDir: entryWorkingDirectory,
144
+ metafile: true,
145
+ bundle: false,
146
+ format: "esm",
147
+ target: "es2020",
148
+ write: false,
149
+ loader: {
150
+ ".js": "jsx",
151
+ ".mjs": "jsx",
152
+ ".cjs": "jsx",
153
+ },
154
+ ...(tsconfig && { tsconfig }),
155
+ });
156
+ // result.metafile is defined because of the `metafile: true` option above.
157
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
158
+ const metafile = result.metafile!;
159
+ const entryPoints = Object.entries(metafile.outputs).filter(
160
+ ([_path, output]) => output.entryPoint !== undefined
161
+ );
162
+ assert(
163
+ entryPoints.length > 0,
164
+ `Cannot find entry-point "${entryFile}" in generated bundle.` +
165
+ listEntryPoints(entryPoints)
166
+ );
167
+ assert(
168
+ entryPoints.length < 2,
169
+ "More than one entry-point found for generated bundle." +
170
+ listEntryPoints(entryPoints)
171
+ );
172
+
173
+ let guessedWorkerFormat: CfScriptFormat;
174
+ const scriptExports = entryPoints[0][1].exports;
175
+ if (scriptExports.length > 0) {
176
+ if (scriptExports.includes("default")) {
177
+ guessedWorkerFormat = "modules";
178
+ } else {
179
+ logger.warn(
180
+ `The entrypoint ${path.relative(
181
+ process.cwd(),
182
+ entryFile
183
+ )} has exports like an ES Module, but hasn't defined a default export like a module worker normally would. Building the worker using "service-worker" format...`
184
+ );
185
+ guessedWorkerFormat = "service-worker";
186
+ }
187
+ } else {
188
+ guessedWorkerFormat = "service-worker";
189
+ }
190
+
191
+ if (hint) {
192
+ if (hint !== guessedWorkerFormat) {
193
+ if (hint === "service-worker") {
194
+ throw new Error(
195
+ "You configured this worker to be a 'service-worker', but the file you are trying to build appears to have a `default` export like a module worker. Please pass `--format modules`, or simply remove the configuration."
196
+ );
197
+ } else {
198
+ throw new Error(
199
+ "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."
200
+ );
201
+ }
202
+ }
203
+ }
204
+ return guessedWorkerFormat;
205
+ }
206
+
207
+ function listEntryPoints(
208
+ outputs: [string, ValueOf<Metafile["outputs"]>][]
209
+ ): string {
210
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
40
211
  }
41
212
 
213
+ type ValueOf<T> = T[keyof T];
214
+
42
215
  /**
43
216
  * Returns true if the given `filePath` exists as-is,
44
217
  * or if some version of it (by appending a common extension) exists.
@@ -55,3 +228,95 @@ export function fileExists(filePath: string): boolean {
55
228
  }
56
229
  return false;
57
230
  }
231
+
232
+ type DurableObjectBindings = Config["durable_objects"]["bindings"];
233
+
234
+ /**
235
+ * Groups the durable object bindings into two lists:
236
+ * those that are defined locally and those that refer to a durable object defined in another script.
237
+ */
238
+ function partitionDurableObjectBindings(config: Config): {
239
+ localBindings: DurableObjectBindings;
240
+ remoteBindings: DurableObjectBindings;
241
+ } {
242
+ const localBindings: DurableObjectBindings = [];
243
+ const remoteBindings: DurableObjectBindings = [];
244
+ for (const binding of config.durable_objects.bindings) {
245
+ if (binding.script_name === undefined) {
246
+ localBindings.push(binding);
247
+ } else {
248
+ remoteBindings.push(binding);
249
+ }
250
+ }
251
+ return { localBindings, remoteBindings };
252
+ }
253
+
254
+ /**
255
+ * Generates some help text based on the Durable Object bindings in a given
256
+ * config indicating how the user can add a `script_name` field to bind an
257
+ * externally defined Durable Object.
258
+ */
259
+ function generateAddScriptNameExamples(
260
+ localBindings: DurableObjectBindings
261
+ ): string {
262
+ function exampleScriptName(binding_name: string): string {
263
+ return `${binding_name.toLowerCase().replaceAll("_", "-")}-worker`;
264
+ }
265
+
266
+ return localBindings
267
+ .map(({ name, class_name }) => {
268
+ const script_name = exampleScriptName(name);
269
+ const currentBinding = `{ name = ${name}, class_name = ${class_name} }`;
270
+ const fixedBinding = `{ name = ${name}, class_name = ${class_name}, script_name = ${script_name} }`;
271
+
272
+ return `${currentBinding} ==> ${fixedBinding}`;
273
+ })
274
+ .join("\n");
275
+ }
276
+
277
+ /**
278
+ * Generate an appropriate message for when the entry-point is missing.
279
+ *
280
+ * To be more helpful to developers, we check whether there is a suitable file
281
+ * nearby to the expected file path.
282
+ */
283
+ function getMissingEntryPointMessage(
284
+ message: string,
285
+ absoluteEntryPointPath: string,
286
+ relativeEntryPointPath: string
287
+ ): string {
288
+ if (
289
+ existsSync(absoluteEntryPointPath) &&
290
+ statSync(absoluteEntryPointPath).isDirectory()
291
+ ) {
292
+ // The expected entry-point is a directory, so offer further guidance.
293
+ message += `\nThe provided entry-point path, "${relativeEntryPointPath}", points to a directory, rather than a file.\n`;
294
+
295
+ // Perhaps we can even guess what the correct path should be...
296
+ const possiblePaths: string[] = [];
297
+ for (const basenamePath of [
298
+ "worker",
299
+ "dist/worker",
300
+ "index",
301
+ "dist/index",
302
+ ]) {
303
+ for (const extension of [".ts", ".tsx", ".js", ".jsx"]) {
304
+ const filePath = basenamePath + extension;
305
+ if (fileExists(path.resolve(absoluteEntryPointPath, filePath))) {
306
+ possiblePaths.push(path.join(relativeEntryPointPath, filePath));
307
+ }
308
+ }
309
+ }
310
+
311
+ if (possiblePaths.length > 0) {
312
+ message +=
313
+ `\nDid you mean to set the main field to${
314
+ possiblePaths.length > 1 ? " one of" : ""
315
+ }:\n` +
316
+ "```\n" +
317
+ possiblePaths.map((filePath) => `main = "./${filePath}"\n`).join("") +
318
+ "```";
319
+ }
320
+ }
321
+ return message;
322
+ }
@@ -1,3 +1,5 @@
1
+ import { logger } from "./logger";
2
+
1
3
  /**
2
4
  * Create a function used to access an environment variable.
3
5
  *
@@ -21,7 +23,7 @@ export function getEnvironmentVariableFactory({
21
23
  if (!hasWarned) {
22
24
  // Only show the warning once.
23
25
  hasWarned = true;
24
- console.warn(
26
+ logger.warn(
25
27
  `Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
26
28
  );
27
29
  }
package/src/errors.ts ADDED
@@ -0,0 +1,11 @@
1
+ export class DeprecationError extends Error {
2
+ constructor(message: string) {
3
+ super(`Deprecation:\n${message}`);
4
+ }
5
+ }
6
+
7
+ export class FatalError extends Error {
8
+ constructor(message?: string, readonly code?: number) {
9
+ super(message);
10
+ }
11
+ }
@@ -0,0 +1,123 @@
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 { logger } from "./logger";
6
+ import type { Attributes, Options } from "selfsigned";
7
+
8
+ // Most of this file has been borrowed from the implementation in Miniflare.
9
+ // See https://github.com/cloudflare/miniflare/blob/870b401ef5/packages/http-server/src/plugin.ts#L313-L397
10
+ // Thanks @mrbbot.
11
+ const CERT_EXPIRY_DAYS = 30;
12
+ const ONE_DAY_IN_MS = 86400000;
13
+
14
+ /**
15
+ * Get the options (i.e. SSL certificates) for running an HTTPS server.
16
+ *
17
+ * The certificates are self-signed and generated locally, and cached in the `CERT_ROOT` directory.
18
+ */
19
+ export async function getHttpsOptions() {
20
+ const certDirectory = path.join(homedir(), ".wrangler/local-cert");
21
+ const keyPath = path.join(certDirectory, "key.pem");
22
+ const certPath = path.join(certDirectory, "cert.pem");
23
+
24
+ const regenerate =
25
+ !fs.existsSync(keyPath) ||
26
+ !fs.existsSync(certPath) ||
27
+ hasCertificateExpired(keyPath, certPath);
28
+
29
+ if (regenerate) {
30
+ logger.log("Generating new self-signed certificate...");
31
+ const { key, cert } = await generateCertificate();
32
+ try {
33
+ // Write certificate files so we can reuse them later.
34
+ fs.mkdirSync(certDirectory, { recursive: true });
35
+ fs.writeFileSync(keyPath, key, "utf8");
36
+ fs.writeFileSync(certPath, cert, "utf8");
37
+ } catch (e) {
38
+ const message = e instanceof Error ? e.message : `${e}`;
39
+ logger.warn(
40
+ `Unable to cache generated self-signed certificate in ${certDirectory}.\n${message}`
41
+ );
42
+ }
43
+ return { key, cert };
44
+ } else {
45
+ return {
46
+ key: fs.readFileSync(keyPath, "utf8"),
47
+ cert: fs.readFileSync(certPath, "utf8"),
48
+ };
49
+ }
50
+ }
51
+
52
+ /**
53
+ * Determine if the certificate defined in `keyPath` and `certPath` files
54
+ * have expired based on the date when they were last modified.
55
+ */
56
+ function hasCertificateExpired(keyPath: string, certPath: string): boolean {
57
+ const keyStat = fs.statSync(keyPath);
58
+ const certStat = fs.statSync(certPath);
59
+ const created = Math.max(keyStat.mtimeMs, certStat.mtimeMs);
60
+ return Date.now() - created > (CERT_EXPIRY_DAYS - 2) * ONE_DAY_IN_MS;
61
+ }
62
+
63
+ /**
64
+ * Generate a new self-signed certificate and cache it in `CERT_ROOT` directory.
65
+ */
66
+ async function generateCertificate() {
67
+ // `selfsigned` imports `node-forge`, which is a pretty big library.
68
+ // To reduce startup time, only load this dynamically when needed.
69
+ // eslint-disable-next-line @typescript-eslint/consistent-type-imports
70
+ const generate: typeof import("selfsigned").generate = promisify(
71
+ // eslint-disable-next-line @typescript-eslint/no-var-requires
72
+ require("selfsigned").generate
73
+ );
74
+
75
+ const certAttrs: Attributes = [{ name: "commonName", value: "localhost" }];
76
+
77
+ const certOptions: Options = {
78
+ algorithm: "sha256",
79
+ days: CERT_EXPIRY_DAYS,
80
+ keySize: 2048,
81
+ extensions: [
82
+ { name: "basicConstraints", cA: true },
83
+ {
84
+ name: "keyUsage",
85
+ keyCertSign: true,
86
+ digitalSignature: true,
87
+ nonRepudiation: true,
88
+ keyEncipherment: true,
89
+ dataEncipherment: true,
90
+ },
91
+ {
92
+ name: "extKeyUsage",
93
+ serverAuth: true,
94
+ clientAuth: true,
95
+ codeSigning: true,
96
+ timeStamping: true,
97
+ },
98
+ {
99
+ name: "subjectAltName",
100
+ altNames: [
101
+ { type: 2, value: "localhost" },
102
+ ...getAccessibleHosts().map((ip) => ({ type: 7, ip })),
103
+ ],
104
+ },
105
+ ],
106
+ };
107
+
108
+ const { private: key, cert } = await generate(certAttrs, certOptions);
109
+ return { key, cert };
110
+ }
111
+
112
+ /**
113
+ * Ask the OS for the addresses of locally accessible hosts.
114
+ */
115
+ function getAccessibleHosts(ipv4 = false): string[] {
116
+ const hosts: string[] = [];
117
+ Object.values(networkInterfaces()).forEach((net) =>
118
+ net?.forEach(({ family, address }) => {
119
+ if (!ipv4 || family === "IPv4") hosts.push(address);
120
+ })
121
+ );
122
+ return hosts;
123
+ }