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/logger.ts ADDED
@@ -0,0 +1,66 @@
1
+ import { format } from "node:util";
2
+ import { formatMessagesSync } from "esbuild";
3
+
4
+ const LOGGER_LEVELS = {
5
+ error: 0,
6
+ warn: 1,
7
+ log: 2,
8
+ debug: 3,
9
+ } as const;
10
+
11
+ type LoggerLevel = keyof typeof LOGGER_LEVELS;
12
+
13
+ /** A map from LOGGER_LEVEL to the error `kind` needed by `formatMessagesSync()`. */
14
+ const LOGGER_LEVEL_FORMAT_TYPE_MAP = {
15
+ error: "error",
16
+ warn: "warning",
17
+ log: undefined,
18
+ debug: undefined,
19
+ } as const;
20
+
21
+ class Logger {
22
+ constructor(public loggerLevel: LoggerLevel = "log") {}
23
+
24
+ columns = process.stdout.columns;
25
+
26
+ debug = (...args: unknown[]) => this.doLog("debug", args);
27
+ log = (...args: unknown[]) => this.doLog("log", args);
28
+ warn = (...args: unknown[]) => this.doLog("warn", args);
29
+ error = (...args: unknown[]) => this.doLog("error", args);
30
+
31
+ private doLog(messageLevel: LoggerLevel, args: unknown[]) {
32
+ if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[messageLevel]) {
33
+ console[messageLevel](this.formatMessage(messageLevel, format(...args)));
34
+ }
35
+ }
36
+
37
+ private formatMessage(level: LoggerLevel, message: string): string {
38
+ const kind = LOGGER_LEVEL_FORMAT_TYPE_MAP[level];
39
+ if (kind) {
40
+ // Format the message using the esbuild formatter.
41
+ // The first line of the message is the main `text`,
42
+ // subsequent lines are put into the `notes`.
43
+ const [firstLine, ...otherLines] = message.split("\n");
44
+ const notes =
45
+ otherLines.length > 0
46
+ ? otherLines.map((text) => ({ text }))
47
+ : undefined;
48
+ return formatMessagesSync([{ text: firstLine, notes }], {
49
+ color: true,
50
+ kind,
51
+ terminalWidth: this.columns,
52
+ })[0];
53
+ } else {
54
+ return message;
55
+ }
56
+ }
57
+ }
58
+
59
+ /**
60
+ * A drop-in replacement for `console` for outputting logging messages.
61
+ *
62
+ * Errors and Warnings will get additional formatting to highlight them to the user.
63
+ * You can also set a `logger.loggerLevel` value to one of "debug", "log", "warn" or "error",
64
+ * to filter out logging messages.
65
+ */
66
+ export const logger = new Logger();
@@ -0,0 +1,30 @@
1
+ # Custom Miniflare CLI
2
+
3
+ This directory contains a simple wrapper around the programmatic Miniflare API,
4
+ which Wrangler spawns when running `wrangler dev` in local mode.
5
+
6
+ ## Building
7
+
8
+ This CLI is built at the same time as Wrangler by running
9
+
10
+ ```
11
+ npm run -w wrangler build
12
+ ```
13
+
14
+ The output of the build is `miniflare-dist/index.mjs`.
15
+
16
+ ## Running
17
+
18
+ The CLI expects a single command line argument which is the Miniflare options formatted as a string of JSON.
19
+
20
+ ```bash
21
+ node --no-warnings ./packages/wrangler/miniflare-dist/index.mjs '{"watch": true, "script": ""}' --log VERBOSE
22
+ ```
23
+
24
+ The `--log` argument is optional and takes one of Miniflare's LogLevels: "NONE", "ERROR", "WARN", "INFO", "DEBUG", "VERBOSE".
25
+ It defaults to `INFO`.
26
+
27
+ ## Debugging
28
+
29
+ Simply place a breakpoint in the code and run the above command in the VS Code "JavaScript Debug Terminal".
30
+ The code will stop at the breakpoint as expected.
@@ -0,0 +1,17 @@
1
+ export type EnumKeys<Enum> = Exclude<keyof Enum, number>;
2
+
3
+ export const enumObject = <Enum extends Record<string, number | string>>(
4
+ e: Enum
5
+ ) => {
6
+ const copy = { ...e } as { [K in EnumKeys<Enum>]: Enum[K] };
7
+ Object.values(e).forEach(
8
+ (value) => typeof value === "number" && delete copy[value]
9
+ );
10
+ return copy;
11
+ };
12
+
13
+ export const enumKeys = <Enum extends Record<string, number | string>>(
14
+ e: Enum
15
+ ) => {
16
+ return Object.keys(enumObject(e)) as EnumKeys<Enum>[];
17
+ };
@@ -0,0 +1,41 @@
1
+ import { Log, LogLevel, Miniflare } from "miniflare";
2
+ import yargs from "yargs";
3
+ import { hideBin } from "yargs/helpers";
4
+ import { enumKeys } from "./enum-keys";
5
+ import { getRequestContextCheckOptions } from "./request-context";
6
+
7
+ async function main() {
8
+ const args = await yargs(hideBin(process.argv))
9
+ .help(false)
10
+ .version(false)
11
+ .option("log", {
12
+ choices: enumKeys(LogLevel),
13
+ }).argv;
14
+
15
+ const logLevel = LogLevel[args.log ?? "INFO"];
16
+ const requestContextCheckOptions = await getRequestContextCheckOptions();
17
+ const config = {
18
+ ...JSON.parse((args._[0] as string) ?? "{}"),
19
+ ...requestContextCheckOptions,
20
+ log: new Log(logLevel),
21
+ };
22
+
23
+ if (logLevel > LogLevel.INFO) {
24
+ console.log("OPTIONS:\n", JSON.stringify(config, null, 2));
25
+ }
26
+
27
+ const mf = new Miniflare(config);
28
+
29
+ try {
30
+ // Start Miniflare development server
31
+ await mf.startServer();
32
+ await mf.startScheduler();
33
+ } catch (e) {
34
+ mf.log.error(e as Error);
35
+ process.exitCode = 1;
36
+ // Unmount any mounted workers
37
+ await mf.dispose();
38
+ }
39
+ }
40
+
41
+ await main();
@@ -0,0 +1,40 @@
1
+ import type { MiniflareOptions } from "miniflare";
2
+
3
+ /**
4
+ * Certain runtime APIs are only available to workers during the "request context",
5
+ * which is any code that returns after receiving a request and before returning
6
+ * a response.
7
+ *
8
+ * Miniflare emulates this behavior by using an [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) and
9
+ * [checking at runtime](https://github.com/cloudflare/miniflare/blob/master/packages/shared/src/context.ts#L21-L36)
10
+ * to see if you're using those APIs during the request context.
11
+ *
12
+ * In certain environments `AsyncLocalStorage` is unavailable, such as in a
13
+ * [webcontainer](https://github.com/stackblitz/webcontainer-core).
14
+ * This function figures out if we're able to run those "request context" checks
15
+ * and returns [a set of options](https://miniflare.dev/core/standards#global-functionality-limits)
16
+ * that indicate to miniflare whether to run the checks or not.
17
+ */
18
+ export const getRequestContextCheckOptions = async (): Promise<
19
+ Pick<MiniflareOptions, "globalAsyncIO" | "globalTimers" | "globalRandom">
20
+ > => {
21
+ // check that there's an implementation of AsyncLocalStorage
22
+ let hasAsyncLocalStorage = true;
23
+ try {
24
+ // ripped from the example here https://nodejs.org/api/async_context.html#class-asynclocalstorage
25
+ const { AsyncLocalStorage } = await import("node:async_hooks");
26
+ const storage = new AsyncLocalStorage<string>();
27
+
28
+ hasAsyncLocalStorage = storage.run("some-value", () => {
29
+ return storage.getStore() === "some-value";
30
+ });
31
+ } catch (e) {
32
+ hasAsyncLocalStorage = false;
33
+ }
34
+
35
+ return {
36
+ globalAsyncIO: hasAsyncLocalStorage,
37
+ globalRandom: hasAsyncLocalStorage,
38
+ globalTimers: hasAsyncLocalStorage,
39
+ };
40
+ };
@@ -2,8 +2,9 @@ import crypto from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
4
  import globToRegExp from "glob-to-regexp";
5
- import type { CfModule, CfModuleType, CfScriptFormat } from "./api/worker";
5
+ import { logger } from "./logger";
6
6
  import type { Config, ConfigModuleRuleType } from "./config";
7
+ import type { CfModule, CfModuleType, CfScriptFormat } from "./worker";
7
8
  import type esbuild from "esbuild";
8
9
 
9
10
  const RuleTypeToModuleType: Record<ConfigModuleRuleType, CfModuleType> = {
@@ -28,9 +29,15 @@ export const DEFAULT_MODULE_RULES: Config["rules"] = [
28
29
  { type: "CompiledWasm", globs: ["**/*.wasm"] },
29
30
  ];
30
31
 
31
- export default function makeModuleCollector(props: {
32
+ export default function createModuleCollector(props: {
32
33
  format: CfScriptFormat;
33
34
  rules?: Config["rules"];
35
+ // a collection of "legacy" style module references, which are just file names
36
+ // we will eventually deprecate this functionality, hence the verbose greppable name
37
+ wrangler1xlegacyModuleReferences: {
38
+ rootDirectory: string;
39
+ fileNames: Set<string>;
40
+ };
34
41
  }): {
35
42
  modules: CfModule[];
36
43
  plugin: esbuild.Plugin;
@@ -41,6 +48,10 @@ export default function makeModuleCollector(props: {
41
48
  ...DEFAULT_MODULE_RULES!,
42
49
  ];
43
50
 
51
+ // First, we want to add some validations to the module rules
52
+ // We want to warn if rules are accidentally configured in such a way that
53
+ // subsequent rules will never match because `fallthrough` hasn't been set
54
+
44
55
  const completedRuleLocations: Record<string, number> = {};
45
56
  let index = 0;
46
57
  const rulesToRemove: Config["rules"] = [];
@@ -48,7 +59,7 @@ export default function makeModuleCollector(props: {
48
59
  if (rule.type in completedRuleLocations) {
49
60
  if (rules[completedRuleLocations[rule.type]].fallthrough !== false) {
50
61
  if (index < (props.rules || []).length) {
51
- console.warn(
62
+ logger.warn(
52
63
  `The module rule at position ${index} (${JSON.stringify(
53
64
  rule
54
65
  )}) has the same type as a previous rule (at position ${
@@ -58,7 +69,7 @@ export default function makeModuleCollector(props: {
58
69
  )}). This rule will be ignored. To the previous rule, add \`fallthrough = true\` to allow this one to also be used, or \`fallthrough = false\` to silence this warning.`
59
70
  );
60
71
  } else {
61
- console.warn(
72
+ logger.warn(
62
73
  `The default module rule ${JSON.stringify(
63
74
  rule
64
75
  )} has the same type as a previous rule (at position ${
@@ -92,6 +103,84 @@ export default function makeModuleCollector(props: {
92
103
  modules.splice(0);
93
104
  });
94
105
 
106
+ // ~ start legacy module specifier support ~
107
+
108
+ // This section detects usage of "legacy" 1.x style module specifiers
109
+ // and modifies them so they "work" in wrangler v2, but with a warning
110
+
111
+ const rulesMatchers = rules.flatMap((rule) => {
112
+ return rule.globs.map((glob) => {
113
+ const regex = globToRegExp(glob);
114
+ return {
115
+ regex,
116
+ rule,
117
+ };
118
+ });
119
+ });
120
+
121
+ if (props.wrangler1xlegacyModuleReferences.fileNames.size > 0) {
122
+ build.onResolve(
123
+ {
124
+ filter: new RegExp(
125
+ "^(" +
126
+ [...props.wrangler1xlegacyModuleReferences.fileNames].join(
127
+ "|"
128
+ ) +
129
+ ")$"
130
+ ),
131
+ },
132
+ async (args: esbuild.OnResolveArgs) => {
133
+ if (
134
+ args.kind !== "import-statement" &&
135
+ args.kind !== "require-call"
136
+ ) {
137
+ return;
138
+ }
139
+ // In the future, this will simply throw an error
140
+ logger.warn(
141
+ `Deprecation: detected a legacy module import in "./${path.relative(
142
+ process.cwd(),
143
+ args.importer
144
+ )}". This will stop working in the future. Replace references to "${
145
+ args.path
146
+ }" with "./${args.path}";`
147
+ );
148
+
149
+ // take the file and massage it to a
150
+ // transportable/manageable format
151
+ const filePath = path.join(
152
+ props.wrangler1xlegacyModuleReferences.rootDirectory,
153
+ args.path
154
+ );
155
+ const fileContent = await readFile(filePath);
156
+ const fileHash = crypto
157
+ .createHash("sha1")
158
+ .update(fileContent)
159
+ .digest("hex");
160
+ const fileName = `./${fileHash}-${path.basename(args.path)}`;
161
+
162
+ const { rule } =
163
+ rulesMatchers.find(({ regex }) => regex.test(fileName)) || {};
164
+ if (rule) {
165
+ // add the module to the array
166
+ modules.push({
167
+ name: fileName,
168
+ content: fileContent,
169
+ type: RuleTypeToModuleType[rule.type],
170
+ });
171
+ return {
172
+ path: fileName, // change the reference to the changed module
173
+ external: props.format === "modules", // mark it as external in the bundle
174
+ namespace: `wrangler-module-${rule.type}`, // just a tag, this isn't strictly necessary
175
+ watchFiles: [filePath], // we also add the file to esbuild's watch list
176
+ };
177
+ }
178
+ }
179
+ );
180
+ }
181
+
182
+ // ~ end legacy module specifier support ~
183
+
95
184
  rules?.forEach((rule) => {
96
185
  if (rule.type === "ESModule" || rule.type === "CommonJS") return; // TODO: we should treat these as js files, and use the jsx loader
97
186
 
@@ -133,10 +222,9 @@ export default function makeModuleCollector(props: {
133
222
  return {
134
223
  // We replace the the module with an identifier
135
224
  // that we'll separately add to the form upload
136
- // as part of [wasm_modules]/[text_blobs]. This identifier has to be a valid
225
+ // as part of [wasm_modules]/[text_blobs]/[data_blobs]. This identifier has to be a valid
137
226
  // JS identifier, so we replace all non alphanumeric characters
138
227
  // with an underscore.
139
- // TODO: what of "Data"?
140
228
  contents: `export default ${args.path.replace(
141
229
  /[^a-zA-Z0-9_$]/g,
142
230
  "_"
@@ -1,13 +1,19 @@
1
1
  import open from "open";
2
+ import { logger } from "./logger";
3
+
2
4
  /**
3
5
  * An extremely simple wrapper around the open command.
4
6
  * Specifically, it adds an 'error' event handler so that when this function
5
- * is called in environments where we can't open the browser (e.g. github codespaces,
6
- * stackblitz, remote servers), it doesn't just crash the process.
7
+ * is called in environments where we can't open the browser (e.g. GitHub Codespaces,
8
+ * StackBlitz, remote servers), it doesn't just crash the process.
9
+ *
10
+ * @param url the URL to point the browser at
7
11
  */
8
12
  export default async function openInBrowser(url: string): Promise<void> {
13
+ const errorMessage = `Failed to open ${url} in a browser`;
14
+
9
15
  const childProcess = await open(url);
10
16
  childProcess.on("error", () => {
11
- console.warn(`Failed to open ${url} in a browser`);
17
+ logger.warn(errorMessage);
12
18
  });
13
19
  }
@@ -1,6 +1,7 @@
1
1
  import { existsSync } from "node:fs";
2
2
  import { join } from "node:path";
3
3
  import { execa, execaCommandSync } from "execa";
4
+ import { logger } from "./logger";
4
5
 
5
6
  export interface PackageManager {
6
7
  cwd: string;
@@ -16,26 +17,26 @@ export async function getPackageManager(cwd: string): Promise<PackageManager> {
16
17
 
17
18
  if (hasNpmLock) {
18
19
  if (hasNpm) {
19
- console.log(
20
+ logger.log(
20
21
  "Using npm as package manager, as there is already a package-lock.json file."
21
22
  );
22
23
  return { ...NpmPackageManager, cwd };
23
24
  } else if (hasYarn) {
24
- console.log("Using yarn as package manager.");
25
- console.warn(
25
+ logger.log("Using yarn as package manager.");
26
+ logger.warn(
26
27
  "There is already a package-lock.json file but could not find npm on the PATH."
27
28
  );
28
29
  return { ...YarnPackageManager, cwd };
29
30
  }
30
31
  } else if (hasYarnLock) {
31
32
  if (hasYarn) {
32
- console.log(
33
+ logger.log(
33
34
  "Using yarn as package manager, as there is already a yarn.lock file."
34
35
  );
35
36
  return { ...YarnPackageManager, cwd };
36
37
  } else if (hasNpm) {
37
- console.log("Using npm as package manager.");
38
- console.warn(
38
+ logger.log("Using npm as package manager.");
39
+ logger.warn(
39
40
  "There is already a yarn.lock file but could not find yarn on the PATH."
40
41
  );
41
42
  return { ...NpmPackageManager, cwd };
@@ -43,10 +44,10 @@ export async function getPackageManager(cwd: string): Promise<PackageManager> {
43
44
  }
44
45
 
45
46
  if (hasNpm) {
46
- console.log("Using npm as package manager.");
47
+ logger.log("Using npm as package manager.");
47
48
  return { ...NpmPackageManager, cwd };
48
49
  } else if (hasYarn) {
49
- console.log("Using yarn as package manager.");
50
+ logger.log("Using yarn as package manager.");
50
51
  return { ...YarnPackageManager, cwd };
51
52
  } else {
52
53
  throw new Error(