wrangler 0.0.0-e2a26a0 → 0.0.0-e2b7352

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 (91) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +10 -1
  3. package/miniflare-dist/index.mjs +79 -0
  4. package/miniflare-dist/index.mjs.map +7 -0
  5. package/package.json +24 -12
  6. package/pages/functions/filepath-routing.test.ts +212 -36
  7. package/pages/functions/filepath-routing.ts +69 -119
  8. package/pages/functions/routes.ts +8 -17
  9. package/pages/functions/template-worker.ts +3 -9
  10. package/src/__tests__/configuration.test.ts +2820 -0
  11. package/src/__tests__/dev.test.tsx +535 -65
  12. package/src/__tests__/guess-worker-format.test.ts +68 -0
  13. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  14. package/src/__tests__/helpers/mock-account-id.ts +26 -8
  15. package/src/__tests__/helpers/mock-bin.ts +4 -1
  16. package/src/__tests__/helpers/mock-cfetch.ts +5 -5
  17. package/src/__tests__/helpers/mock-console.ts +21 -7
  18. package/src/__tests__/helpers/mock-kv.ts +9 -16
  19. package/src/__tests__/helpers/mock-stdin.ts +103 -0
  20. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  21. package/src/__tests__/helpers/run-in-tmp.ts +3 -0
  22. package/src/__tests__/helpers/run-wrangler.ts +5 -3
  23. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  24. package/src/__tests__/https-options.test.ts +127 -0
  25. package/src/__tests__/index.test.ts +467 -27
  26. package/src/__tests__/jest.setup.ts +37 -5
  27. package/src/__tests__/kv.test.ts +442 -201
  28. package/src/__tests__/logout.test.ts +15 -13
  29. package/src/__tests__/package-manager.test.ts +2 -2
  30. package/src/__tests__/pages.test.ts +82 -0
  31. package/src/__tests__/parse.test.ts +322 -0
  32. package/src/__tests__/publish.test.ts +2717 -430
  33. package/src/__tests__/r2.test.ts +198 -0
  34. package/src/__tests__/route.test.ts +45 -0
  35. package/src/__tests__/secret.test.ts +301 -86
  36. package/src/__tests__/sentry.test.ts +146 -0
  37. package/src/__tests__/tail.test.ts +638 -0
  38. package/src/__tests__/whoami.test.tsx +21 -7
  39. package/src/bundle.ts +155 -0
  40. package/src/cfetch/index.ts +8 -6
  41. package/src/cfetch/internal.ts +60 -22
  42. package/src/cli.ts +10 -0
  43. package/src/config/README.md +107 -0
  44. package/src/config/config.ts +218 -0
  45. package/src/config/diagnostics.ts +80 -0
  46. package/src/config/environment.ts +371 -0
  47. package/src/config/index.ts +62 -0
  48. package/src/config/validation-helpers.ts +554 -0
  49. package/src/config/validation.ts +1232 -0
  50. package/src/{api/preview.ts → create-worker-preview.ts} +59 -21
  51. package/src/create-worker-upload-form.ts +217 -0
  52. package/src/dev/dev.tsx +392 -0
  53. package/src/dev/local.tsx +232 -0
  54. package/src/dev/remote.tsx +203 -0
  55. package/src/dev/use-esbuild.ts +104 -0
  56. package/src/entry.ts +240 -0
  57. package/src/environment-variables.ts +33 -0
  58. package/src/https-options.ts +122 -0
  59. package/src/index.tsx +1068 -780
  60. package/src/inspect.ts +25 -4
  61. package/src/intl-polyfill.d.ts +139 -0
  62. package/src/{kv.tsx → kv.ts} +95 -60
  63. package/src/miniflare-cli/README.md +30 -0
  64. package/src/miniflare-cli/enum-keys.ts +17 -0
  65. package/src/miniflare-cli/index.ts +37 -0
  66. package/src/module-collection.ts +226 -31
  67. package/src/open-in-browser.ts +25 -0
  68. package/src/package-manager.ts +21 -15
  69. package/src/pages.tsx +35 -20
  70. package/src/parse.ts +183 -0
  71. package/src/proxy.ts +115 -45
  72. package/src/publish.ts +268 -328
  73. package/src/r2.ts +50 -0
  74. package/src/reporting.ts +131 -0
  75. package/src/selfsigned.d.ts +29 -0
  76. package/src/sites.tsx +83 -43
  77. package/src/tail/filters.ts +279 -0
  78. package/src/tail/index.ts +299 -0
  79. package/src/tail/printing.ts +62 -0
  80. package/src/user.tsx +234 -126
  81. package/src/{api/worker.ts → worker.ts} +44 -36
  82. package/templates/new-worker.js +1 -1
  83. package/templates/new-worker.ts +1 -1
  84. package/templates/tsconfig.json +105 -0
  85. package/wrangler-dist/cli.js +131202 -114243
  86. package/wrangler-dist/cli.js.map +3 -3
  87. package/src/__tests__/helpers/mock-user.ts +0 -27
  88. package/src/api/form_data.ts +0 -134
  89. package/src/config.ts +0 -641
  90. package/src/dev.tsx +0 -834
  91. package/src/tail.tsx +0 -73
@@ -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,104 @@
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
+ tsconfig,
27
+ }: {
28
+ entry: Entry;
29
+ destination: string | undefined;
30
+ staticRoot: undefined | string;
31
+ jsxFactory: string | undefined;
32
+ jsxFragment: string | undefined;
33
+ rules: Config["rules"];
34
+ serveAssetsFromWorker: boolean;
35
+ tsconfig: string | undefined;
36
+ }): EsbuildBundle | undefined {
37
+ const [bundle, setBundle] = useState<EsbuildBundle>();
38
+ useEffect(() => {
39
+ let stopWatching: (() => void) | undefined = undefined;
40
+
41
+ const watchMode: WatchMode = {
42
+ async onRebuild(error) {
43
+ if (error) console.error("watch build failed:", error);
44
+ else {
45
+ // nothing really changes here, so let's increment the id
46
+ // to change the return object's identity
47
+ setBundle((previousBundle) => {
48
+ assert(
49
+ previousBundle,
50
+ "Rebuild triggered with no previous build available"
51
+ );
52
+ return { ...previousBundle, id: previousBundle.id + 1 };
53
+ });
54
+ }
55
+ },
56
+ };
57
+
58
+ async function build() {
59
+ if (!destination) return;
60
+
61
+ const { resolvedEntryPointPath, bundleType, modules, stop } =
62
+ await bundleWorker(entry, destination, {
63
+ // In dev, we serve assets from the local proxy before we send the request to the worker.
64
+ serveAssetsFromWorker: false,
65
+ jsxFactory,
66
+ jsxFragment,
67
+ rules,
68
+ watch: watchMode,
69
+ tsconfig,
70
+ });
71
+
72
+ // Capture the `stop()` method to use as the `useEffect()` destructor.
73
+ stopWatching = stop;
74
+
75
+ setBundle({
76
+ id: 0,
77
+ entry,
78
+ path: resolvedEntryPointPath,
79
+ type: bundleType,
80
+ modules,
81
+ serveAssetsFromWorker,
82
+ });
83
+ }
84
+
85
+ build().catch(() => {
86
+ // esbuild already logs errors to stderr and we don't want to end the process
87
+ // on build errors anyway so this is a no-op error handler
88
+ });
89
+
90
+ return () => {
91
+ stopWatching?.();
92
+ };
93
+ }, [
94
+ entry,
95
+ destination,
96
+ staticRoot,
97
+ jsxFactory,
98
+ jsxFragment,
99
+ serveAssetsFromWorker,
100
+ rules,
101
+ tsconfig,
102
+ ]);
103
+ return bundle;
104
+ }
package/src/entry.ts ADDED
@@ -0,0 +1,240 @@
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: "dev" | "publish"
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
+ config.tsconfig
51
+ );
52
+
53
+ const { localBindings, remoteBindings } =
54
+ partitionDurableObjectBindings(config);
55
+
56
+ if (command === "dev" && remoteBindings.length > 0) {
57
+ console.warn(
58
+ "WARNING: You have Durable Object bindings, which are not defined locally in the worker being developed.\n" +
59
+ "Be aware that changes to the data stored in these Durable Objects will be permanent and affect the live instances.\n" +
60
+ "Remote Durable Objects that are affected:\n" +
61
+ remoteBindings.map((b) => `- ${JSON.stringify(b)}`).join("\n")
62
+ );
63
+ }
64
+
65
+ if (format === "service-worker" && localBindings.length > 0) {
66
+ const errorMessage =
67
+ "You seem to be trying to use Durable Objects in a Worker written with Service Worker syntax.";
68
+ const addScriptName =
69
+ "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:";
70
+ const addScriptNameExamples = generateAddScriptNameExamples(localBindings);
71
+ const migrateText =
72
+ "Alternatively, migrate your worker to ES Module syntax to implement a Durable Object in this Worker:";
73
+ const migrateUrl =
74
+ "https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/";
75
+ throw new Error(
76
+ `${errorMessage}\n${addScriptName}\n${addScriptNameExamples}\n${migrateText}\n${migrateUrl}`
77
+ );
78
+ }
79
+
80
+ return { file, directory, format };
81
+ }
82
+
83
+ export async function runCustomBuild(
84
+ expectedEntry: string,
85
+ build: Config["build"]
86
+ ) {
87
+ if (build?.command) {
88
+ // TODO: add a deprecation message here?
89
+ console.log("running:", build.command);
90
+ await execaCommand(build.command, {
91
+ shell: true,
92
+ stdout: "inherit",
93
+ stderr: "inherit",
94
+ timeout: 1000 * 30,
95
+ ...(build.cwd && { cwd: build.cwd }),
96
+ });
97
+
98
+ if (fileExists(expectedEntry) === false) {
99
+ throw new Error(
100
+ `Could not resolve "${path.relative(
101
+ process.cwd(),
102
+ expectedEntry
103
+ )}" after running custom build: ${build.command}`
104
+ );
105
+ }
106
+ }
107
+ }
108
+
109
+ /**
110
+ * A function to "guess" the type of worker.
111
+ * We do this by running a lightweight build of the actual script,
112
+ * and looking at the metafile generated by esbuild. If it has a default
113
+ * export (or really, any exports), that means it's a "modules" worker.
114
+ * Else, it's a "service-worker" worker. This seems hacky, but works remarkably
115
+ * well in practice.
116
+ */
117
+ export default async function guessWorkerFormat(
118
+ entryFile: string,
119
+ entryWorkingDirectory: string,
120
+ hint: CfScriptFormat | undefined,
121
+ tsconfig?: string | undefined
122
+ ): Promise<CfScriptFormat> {
123
+ const result = await esbuild.build({
124
+ entryPoints: [entryFile],
125
+ absWorkingDir: entryWorkingDirectory,
126
+ metafile: true,
127
+ bundle: false,
128
+ format: "esm",
129
+ write: false,
130
+ loader: {
131
+ ".js": "jsx",
132
+ ".mjs": "jsx",
133
+ ".cjs": "jsx",
134
+ },
135
+ ...(tsconfig && { tsconfig }),
136
+ });
137
+ // result.metafile is defined because of the `metafile: true` option above.
138
+ // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
139
+ const metafile = result.metafile!;
140
+ const entryPoints = Object.entries(metafile.outputs).filter(
141
+ ([_path, output]) => output.entryPoint !== undefined
142
+ );
143
+ assert(
144
+ entryPoints.length > 0,
145
+ `Cannot find entry-point "${entryFile}" in generated bundle.` +
146
+ listEntryPoints(entryPoints)
147
+ );
148
+ assert(
149
+ entryPoints.length < 2,
150
+ "More than one entry-point found for generated bundle." +
151
+ listEntryPoints(entryPoints)
152
+ );
153
+ const guessedWorkerFormat =
154
+ entryPoints[0][1].exports.length > 0 ? "modules" : "service-worker";
155
+
156
+ if (hint) {
157
+ if (hint !== guessedWorkerFormat) {
158
+ if (hint === "service-worker") {
159
+ throw new Error(
160
+ "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."
161
+ );
162
+ } else {
163
+ throw new Error(
164
+ "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."
165
+ );
166
+ }
167
+ }
168
+ }
169
+ return guessedWorkerFormat;
170
+ }
171
+
172
+ function listEntryPoints(
173
+ outputs: [string, ValueOf<Metafile["outputs"]>][]
174
+ ): string {
175
+ return outputs.map(([_input, output]) => output.entryPoint).join("\n");
176
+ }
177
+
178
+ type ValueOf<T> = T[keyof T];
179
+
180
+ /**
181
+ * Returns true if the given `filePath` exists as-is,
182
+ * or if some version of it (by appending a common extension) exists.
183
+ */
184
+ export function fileExists(filePath: string): boolean {
185
+ if (path.extname(filePath) !== "") {
186
+ return existsSync(filePath);
187
+ }
188
+ const base = path.join(path.dirname(filePath), path.basename(filePath));
189
+ for (const ext of [".ts", ".tsx", ".js", ".jsx"]) {
190
+ if (existsSync(base + ext)) {
191
+ return true;
192
+ }
193
+ }
194
+ return false;
195
+ }
196
+
197
+ type DurableObjectBindings = Config["durable_objects"]["bindings"];
198
+
199
+ /**
200
+ * Groups the durable object bindings into two lists:
201
+ * those that are defined locally and those that refer to a durable object defined in another script.
202
+ */
203
+ function partitionDurableObjectBindings(config: Config): {
204
+ localBindings: DurableObjectBindings;
205
+ remoteBindings: DurableObjectBindings;
206
+ } {
207
+ const localBindings: DurableObjectBindings = [];
208
+ const remoteBindings: DurableObjectBindings = [];
209
+ for (const binding of config.durable_objects.bindings) {
210
+ if (binding.script_name === undefined) {
211
+ localBindings.push(binding);
212
+ } else {
213
+ remoteBindings.push(binding);
214
+ }
215
+ }
216
+ return { localBindings, remoteBindings };
217
+ }
218
+
219
+ /**
220
+ * Generates some help text based on the Durable Object bindings in a given
221
+ * config indicating how the user can add a `script_name` field to bind an
222
+ * externally defined Durable Object.
223
+ */
224
+ function generateAddScriptNameExamples(
225
+ localBindings: DurableObjectBindings
226
+ ): string {
227
+ function exampleScriptName(binding_name: string): string {
228
+ return `${binding_name.toLowerCase().replaceAll("_", "-")}-worker`;
229
+ }
230
+
231
+ return localBindings
232
+ .map(({ name, class_name }) => {
233
+ const script_name = exampleScriptName(name);
234
+ const currentBinding = `{ name = ${name}, class_name = ${class_name} }`;
235
+ const fixedBinding = `{ name = ${name}, class_name = ${class_name}, script_name = ${script_name} }`;
236
+
237
+ return `${currentBinding} ==> ${fixedBinding}`;
238
+ })
239
+ .join("\n");
240
+ }
@@ -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
+ }