wrangler 0.0.0-e492c10 → 0.0.0-e4bb5f36

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 (177) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +30 -12
  3. package/bin/wrangler.js +113 -39
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +194 -149
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +17 -0
  11. package/templates/gitignore +1 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +137 -0
  17. package/templates/middleware/loader-sw.ts +228 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  20. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  21. package/templates/middleware/middleware-multiworker-dev.ts +59 -0
  22. package/templates/middleware/middleware-pretty-error.ts +40 -0
  23. package/templates/middleware/middleware-scheduled.ts +15 -0
  24. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  25. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  26. package/templates/new-worker-scheduled.js +17 -0
  27. package/templates/new-worker-scheduled.ts +32 -0
  28. package/templates/new-worker.js +3 -3
  29. package/templates/new-worker.ts +22 -4
  30. package/templates/no-op-worker.js +10 -0
  31. package/templates/pages-dev-pipeline.ts +31 -0
  32. package/templates/pages-dev-util.ts +55 -0
  33. package/templates/pages-shim.ts +9 -0
  34. package/templates/pages-template-plugin.ts +190 -0
  35. package/templates/pages-template-worker.ts +198 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +105 -0
  38. package/templates/tsconfig.json +6 -103
  39. package/wrangler-dist/cli.d.ts +1732 -0
  40. package/wrangler-dist/cli.js +138795 -97365
  41. package/wrangler-dist/wasm-sync.wasm +0 -0
  42. package/import_meta_url.js +0 -3
  43. package/miniflare-config-stubs/.env.empty +0 -0
  44. package/miniflare-config-stubs/package.empty.json +0 -1
  45. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  46. package/miniflare-dist/index.mjs +0 -4886
  47. package/pages/functions/buildPlugin.ts +0 -92
  48. package/pages/functions/buildWorker.ts +0 -138
  49. package/pages/functions/filepath-routing.test.ts +0 -234
  50. package/pages/functions/filepath-routing.ts +0 -189
  51. package/pages/functions/identifiers.ts +0 -78
  52. package/pages/functions/routes.ts +0 -156
  53. package/pages/functions/template-plugin.ts +0 -146
  54. package/pages/functions/template-worker.ts +0 -143
  55. package/src/__tests__/config-cache.test.ts +0 -36
  56. package/src/__tests__/configuration.test.ts +0 -3125
  57. package/src/__tests__/dev.test.tsx +0 -827
  58. package/src/__tests__/guess-worker-format.test.ts +0 -85
  59. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  60. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  61. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  62. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  63. package/src/__tests__/helpers/mock-bin.ts +0 -36
  64. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  65. package/src/__tests__/helpers/mock-console.ts +0 -87
  66. package/src/__tests__/helpers/mock-dialogs.ts +0 -90
  67. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  68. package/src/__tests__/helpers/mock-istty.ts +0 -27
  69. package/src/__tests__/helpers/mock-kv.ts +0 -33
  70. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  71. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  72. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  73. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  74. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  75. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  76. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  77. package/src/__tests__/https-options.test.ts +0 -130
  78. package/src/__tests__/index.test.ts +0 -242
  79. package/src/__tests__/init.test.ts +0 -1516
  80. package/src/__tests__/jest.setup.ts +0 -77
  81. package/src/__tests__/kv.test.ts +0 -1442
  82. package/src/__tests__/logger.test.ts +0 -115
  83. package/src/__tests__/package-manager.test.ts +0 -206
  84. package/src/__tests__/pages.test.ts +0 -327
  85. package/src/__tests__/parse.test.ts +0 -326
  86. package/src/__tests__/publish.test.ts +0 -4948
  87. package/src/__tests__/r2.test.ts +0 -210
  88. package/src/__tests__/route.test.ts +0 -45
  89. package/src/__tests__/secret.test.ts +0 -446
  90. package/src/__tests__/tail.test.ts +0 -690
  91. package/src/__tests__/user.test.ts +0 -131
  92. package/src/__tests__/whoami.test.tsx +0 -105
  93. package/src/bundle.ts +0 -169
  94. package/src/cfetch/index.ts +0 -104
  95. package/src/cfetch/internal.ts +0 -137
  96. package/src/cli.ts +0 -13
  97. package/src/config/README.md +0 -107
  98. package/src/config/config.ts +0 -234
  99. package/src/config/diagnostics.ts +0 -80
  100. package/src/config/environment.ts +0 -394
  101. package/src/config/index.ts +0 -63
  102. package/src/config/validation-helpers.ts +0 -575
  103. package/src/config/validation.ts +0 -1424
  104. package/src/config-cache.ts +0 -45
  105. package/src/create-worker-preview.ts +0 -175
  106. package/src/create-worker-upload-form.ts +0 -240
  107. package/src/dev/dev-vars.ts +0 -36
  108. package/src/dev/dev.tsx +0 -418
  109. package/src/dev/local.tsx +0 -312
  110. package/src/dev/remote.tsx +0 -213
  111. package/src/dev/use-esbuild.ts +0 -118
  112. package/src/dialogs.tsx +0 -87
  113. package/src/entry.ts +0 -267
  114. package/src/environment-variables.ts +0 -35
  115. package/src/errors.ts +0 -11
  116. package/src/https-options.ts +0 -123
  117. package/src/index.tsx +0 -2698
  118. package/src/inspect.ts +0 -623
  119. package/src/intl-polyfill.d.ts +0 -139
  120. package/src/kv.ts +0 -319
  121. package/src/logger.ts +0 -66
  122. package/src/miniflare-cli/README.md +0 -30
  123. package/src/miniflare-cli/enum-keys.ts +0 -17
  124. package/src/miniflare-cli/index.ts +0 -41
  125. package/src/miniflare-cli/request-context.ts +0 -40
  126. package/src/module-collection.ts +0 -258
  127. package/src/open-in-browser.ts +0 -26
  128. package/src/package-manager.ts +0 -127
  129. package/src/pages.tsx +0 -1875
  130. package/src/parse.ts +0 -185
  131. package/src/paths.ts +0 -26
  132. package/src/proxy.ts +0 -449
  133. package/src/publish.ts +0 -469
  134. package/src/r2.ts +0 -50
  135. package/src/selfsigned.d.ts +0 -29
  136. package/src/sites.tsx +0 -293
  137. package/src/tail/filters.ts +0 -279
  138. package/src/tail/index.ts +0 -299
  139. package/src/tail/printing.ts +0 -67
  140. package/src/update-check.ts +0 -19
  141. package/src/user.tsx +0 -1203
  142. package/src/whoami.tsx +0 -70
  143. package/src/worker.ts +0 -172
  144. package/templates/static-asset-facade.js +0 -47
  145. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  146. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  147. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  148. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  149. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  150. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  151. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  152. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  153. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  154. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  155. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  156. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  157. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  158. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  159. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  160. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  161. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  162. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  163. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  164. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  165. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  166. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  167. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  168. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  169. package/vendor/wrangler-mime/LICENSE +0 -21
  170. package/vendor/wrangler-mime/Mime.js +0 -97
  171. package/vendor/wrangler-mime/README.md +0 -187
  172. package/vendor/wrangler-mime/cli.js +0 -46
  173. package/vendor/wrangler-mime/index.js +0 -4
  174. package/vendor/wrangler-mime/lite.js +0 -4
  175. package/vendor/wrangler-mime/package.json +0 -52
  176. package/vendor/wrangler-mime/types/other.js +0 -1
  177. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/dialogs.tsx DELETED
@@ -1,87 +0,0 @@
1
- import chalk from "chalk";
2
- import { Box, Text, useInput, render } from "ink";
3
- import TextInput from "ink-text-input";
4
- import * as React from "react";
5
- import { useState } from "react";
6
- import { logger } from "./logger";
7
- type ConfirmProps = {
8
- text: string;
9
- onConfirm: (answer: boolean) => void;
10
- };
11
- function Confirm(props: ConfirmProps) {
12
- useInput((input: string, key) => {
13
- if (input === "y" || key.return === true) {
14
- props.onConfirm(true);
15
- } else if (input === "n") {
16
- props.onConfirm(false);
17
- } else {
18
- logger.warn("Unrecognised input:", input);
19
- }
20
- });
21
- return (
22
- <Box>
23
- <Text>
24
- {props.text} ({chalk.bold("y")}/n)
25
- </Text>
26
- </Box>
27
- );
28
- }
29
-
30
- export function confirm(text: string): Promise<boolean> {
31
- return new Promise((resolve) => {
32
- const { unmount } = render(
33
- <Confirm
34
- text={text}
35
- onConfirm={(answer: boolean) => {
36
- unmount();
37
- resolve(answer);
38
- }}
39
- />
40
- );
41
- });
42
- }
43
-
44
- type PromptProps = {
45
- text: string;
46
- defaultValue?: string;
47
- type?: "text" | "password";
48
- onSubmit: (text: string) => void;
49
- };
50
-
51
- function Prompt(props: PromptProps) {
52
- const [value, setValue] = useState(props.defaultValue || "");
53
-
54
- return (
55
- <Box>
56
- <Text>{props.text} </Text>
57
- <Box>
58
- <TextInput
59
- mask={props.type === "password" ? "*" : undefined}
60
- value={value}
61
- onChange={setValue}
62
- onSubmit={props.onSubmit}
63
- />
64
- </Box>
65
- </Box>
66
- );
67
- }
68
-
69
- export async function prompt(
70
- text: string,
71
- type: "text" | "password" = "text",
72
- defaultValue?: string
73
- ): Promise<string> {
74
- return new Promise((resolve) => {
75
- const { unmount } = render(
76
- <Prompt
77
- text={text}
78
- defaultValue={defaultValue}
79
- type={type}
80
- onSubmit={(inputText) => {
81
- unmount();
82
- resolve(inputText);
83
- }}
84
- />
85
- );
86
- });
87
- }
package/src/entry.ts DELETED
@@ -1,267 +0,0 @@
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 { logger } from "./logger";
7
- import type { Config } from "./config";
8
- import type { CfScriptFormat } from "./worker";
9
- import type { Metafile } from "esbuild";
10
-
11
- /**
12
- * An entry point for the Worker.
13
- *
14
- * It consists not just of a `file`, but also of a `directory` that is used to resolve relative paths.
15
- */
16
- export type Entry = { file: string; directory: string; format: CfScriptFormat };
17
-
18
- /**
19
- * Compute the entry-point for the Worker.
20
- */
21
- export async function getEntry(
22
- args: { script?: string; format?: CfScriptFormat | undefined },
23
- config: Config,
24
- command: "dev" | "publish"
25
- ): Promise<Entry> {
26
- let file: string;
27
- let directory = process.cwd();
28
- if (args.script) {
29
- // If the script name comes from the command line it is relative to the current working directory.
30
- file = path.resolve(args.script);
31
- } else if (config.main === undefined) {
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
- }
43
- } else {
44
- directory = path.resolve(path.dirname(config.configPath ?? "."));
45
- file = path.resolve(directory, config.main);
46
- }
47
-
48
- await runCustomBuild(file, config.build);
49
-
50
- if (fileExists(file) === false) {
51
- throw new Error(
52
- `Could not resolve "${path.relative(process.cwd(), file)}".`
53
- );
54
- }
55
- const format = await guessWorkerFormat(
56
- file,
57
- directory,
58
- args.format ?? config.build?.upload?.format,
59
- config.tsconfig
60
- );
61
-
62
- const { localBindings, remoteBindings } =
63
- partitionDurableObjectBindings(config);
64
-
65
- if (command === "dev" && remoteBindings.length > 0) {
66
- logger.warn(
67
- "WARNING: You have Durable Object bindings that are not defined locally in the worker being developed.\n" +
68
- "Be aware that changes to the data stored in these Durable Objects will be permanent and affect the live instances.\n" +
69
- "Remote Durable Objects that are affected:\n" +
70
- remoteBindings.map((b) => `- ${JSON.stringify(b)}`).join("\n")
71
- );
72
- }
73
-
74
- if (format === "service-worker" && localBindings.length > 0) {
75
- const errorMessage =
76
- "You seem to be trying to use Durable Objects in a Worker written as a service-worker.";
77
- const addScriptName =
78
- "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:";
79
- const addScriptNameExamples = generateAddScriptNameExamples(localBindings);
80
- const migrateText =
81
- "Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:";
82
- const migrateUrl =
83
- "https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/";
84
- throw new Error(
85
- `${errorMessage}\n${addScriptName}\n${addScriptNameExamples}\n${migrateText}\n${migrateUrl}`
86
- );
87
- }
88
-
89
- return { file, directory, format };
90
- }
91
-
92
- export async function runCustomBuild(
93
- expectedEntry: string,
94
- build: Config["build"]
95
- ) {
96
- if (build?.command) {
97
- // TODO: add a deprecation message here?
98
- logger.log("Running custom build:", build.command);
99
- await execaCommand(build.command, {
100
- shell: true,
101
- // we keep these two as "inherit" so that
102
- // logs are still visible.
103
- stdout: "inherit",
104
- stderr: "inherit",
105
- ...(build.cwd && { cwd: build.cwd }),
106
- });
107
-
108
- if (fileExists(expectedEntry) === false) {
109
- throw new Error(
110
- `Could not resolve "${path.relative(
111
- process.cwd(),
112
- expectedEntry
113
- )}" after running custom build: ${build.command}`
114
- );
115
- }
116
- }
117
- }
118
-
119
- /**
120
- * A function to "guess" the type of worker.
121
- * We do this by running a lightweight build of the actual script,
122
- * and looking at the metafile generated by esbuild. If it has a default
123
- * export (or really, any exports), that means it's a "modules" worker.
124
- * Else, it's a "service-worker" worker. This seems hacky, but works remarkably
125
- * well in practice.
126
- */
127
- export default async function guessWorkerFormat(
128
- entryFile: string,
129
- entryWorkingDirectory: string,
130
- hint: CfScriptFormat | undefined,
131
- tsconfig?: string | undefined
132
- ): Promise<CfScriptFormat> {
133
- const result = await esbuild.build({
134
- entryPoints: [entryFile],
135
- absWorkingDir: entryWorkingDirectory,
136
- metafile: true,
137
- bundle: false,
138
- format: "esm",
139
- target: "es2020",
140
- write: false,
141
- loader: {
142
- ".js": "jsx",
143
- ".mjs": "jsx",
144
- ".cjs": "jsx",
145
- },
146
- ...(tsconfig && { tsconfig }),
147
- });
148
- // result.metafile is defined because of the `metafile: true` option above.
149
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
150
- const metafile = result.metafile!;
151
- const entryPoints = Object.entries(metafile.outputs).filter(
152
- ([_path, output]) => output.entryPoint !== undefined
153
- );
154
- assert(
155
- entryPoints.length > 0,
156
- `Cannot find entry-point "${entryFile}" in generated bundle.` +
157
- listEntryPoints(entryPoints)
158
- );
159
- assert(
160
- entryPoints.length < 2,
161
- "More than one entry-point found for generated bundle." +
162
- listEntryPoints(entryPoints)
163
- );
164
-
165
- let guessedWorkerFormat: CfScriptFormat;
166
- const scriptExports = entryPoints[0][1].exports;
167
- if (scriptExports.length > 0) {
168
- if (scriptExports.includes("default")) {
169
- guessedWorkerFormat = "modules";
170
- } else {
171
- logger.warn(
172
- `The entrypoint ${path.relative(
173
- process.cwd(),
174
- entryFile
175
- )} 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...`
176
- );
177
- guessedWorkerFormat = "service-worker";
178
- }
179
- } else {
180
- guessedWorkerFormat = "service-worker";
181
- }
182
-
183
- if (hint) {
184
- if (hint !== guessedWorkerFormat) {
185
- if (hint === "service-worker") {
186
- throw new Error(
187
- "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."
188
- );
189
- } else {
190
- throw new Error(
191
- "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."
192
- );
193
- }
194
- }
195
- }
196
- return guessedWorkerFormat;
197
- }
198
-
199
- function listEntryPoints(
200
- outputs: [string, ValueOf<Metafile["outputs"]>][]
201
- ): string {
202
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
203
- }
204
-
205
- type ValueOf<T> = T[keyof T];
206
-
207
- /**
208
- * Returns true if the given `filePath` exists as-is,
209
- * or if some version of it (by appending a common extension) exists.
210
- */
211
- export function fileExists(filePath: string): boolean {
212
- if (path.extname(filePath) !== "") {
213
- return existsSync(filePath);
214
- }
215
- const base = path.join(path.dirname(filePath), path.basename(filePath));
216
- for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
217
- if (existsSync(base + ext)) {
218
- return true;
219
- }
220
- }
221
- return false;
222
- }
223
-
224
- type DurableObjectBindings = Config["durable_objects"]["bindings"];
225
-
226
- /**
227
- * Groups the durable object bindings into two lists:
228
- * those that are defined locally and those that refer to a durable object defined in another script.
229
- */
230
- function partitionDurableObjectBindings(config: Config): {
231
- localBindings: DurableObjectBindings;
232
- remoteBindings: DurableObjectBindings;
233
- } {
234
- const localBindings: DurableObjectBindings = [];
235
- const remoteBindings: DurableObjectBindings = [];
236
- for (const binding of config.durable_objects.bindings) {
237
- if (binding.script_name === undefined) {
238
- localBindings.push(binding);
239
- } else {
240
- remoteBindings.push(binding);
241
- }
242
- }
243
- return { localBindings, remoteBindings };
244
- }
245
-
246
- /**
247
- * Generates some help text based on the Durable Object bindings in a given
248
- * config indicating how the user can add a `script_name` field to bind an
249
- * externally defined Durable Object.
250
- */
251
- function generateAddScriptNameExamples(
252
- localBindings: DurableObjectBindings
253
- ): string {
254
- function exampleScriptName(binding_name: string): string {
255
- return `${binding_name.toLowerCase().replaceAll("_", "-")}-worker`;
256
- }
257
-
258
- return localBindings
259
- .map(({ name, class_name }) => {
260
- const script_name = exampleScriptName(name);
261
- const currentBinding = `{ name = ${name}, class_name = ${class_name} }`;
262
- const fixedBinding = `{ name = ${name}, class_name = ${class_name}, script_name = ${script_name} }`;
263
-
264
- return `${currentBinding} ==> ${fixedBinding}`;
265
- })
266
- .join("\n");
267
- }
@@ -1,35 +0,0 @@
1
- import { logger } from "./logger";
2
-
3
- /**
4
- * Create a function used to access an environment variable.
5
- *
6
- * This is not memoized to allow us to change the value at runtime, such as in testing.
7
- * A warning is shown if the client is using a deprecated version - but only once.
8
- */
9
- export function getEnvironmentVariableFactory({
10
- variableName,
11
- deprecatedName,
12
- defaultValue,
13
- }: {
14
- variableName: string;
15
- deprecatedName?: string;
16
- defaultValue?: string;
17
- }) {
18
- let hasWarned = false;
19
- return () => {
20
- if (process.env[variableName]) {
21
- return process.env[variableName];
22
- } else if (deprecatedName && process.env[deprecatedName]) {
23
- if (!hasWarned) {
24
- // Only show the warning once.
25
- hasWarned = true;
26
- logger.warn(
27
- `Using "${deprecatedName}" environment variable. This is deprecated. Please use "${variableName}", instead.`
28
- );
29
- }
30
- return process.env[deprecatedName];
31
- } else {
32
- return defaultValue;
33
- }
34
- };
35
- }
package/src/errors.ts DELETED
@@ -1,11 +0,0 @@
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
- }
@@ -1,123 +0,0 @@
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
- }