wrangler 0.0.0-e7a0cd5b → 0.0.0-e7cf0caa

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 (237) hide show
  1. package/README.md +3 -3
  2. package/bin/wrangler.js +30 -10
  3. package/miniflare-dist/index.mjs +126 -74
  4. package/package.json +27 -19
  5. package/src/__tests__/api-dev.test.ts +65 -36
  6. package/src/__tests__/api-devregistry.test.ts +121 -0
  7. package/src/__tests__/api.test.ts +27 -5
  8. package/src/__tests__/configuration.test.ts +567 -86
  9. package/src/__tests__/d1/d1.test.ts +82 -0
  10. package/src/__tests__/d1/execute.test.ts +66 -0
  11. package/src/__tests__/d1/migrate.test.ts +157 -0
  12. package/src/__tests__/d1/splitter.test.ts +255 -0
  13. package/src/__tests__/delete.test.ts +91 -49
  14. package/src/__tests__/deployments.test.ts +330 -56
  15. package/src/__tests__/dev.test.tsx +198 -90
  16. package/src/__tests__/generate.test.ts +12 -10
  17. package/src/__tests__/guess-worker-format.test.ts +35 -0
  18. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  19. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  20. package/src/__tests__/helpers/mock-console.ts +6 -0
  21. package/src/__tests__/helpers/mock-dialogs.ts +71 -85
  22. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  23. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -5
  24. package/src/__tests__/helpers/mock-known-routes.ts +7 -2
  25. package/src/__tests__/helpers/mock-kv.ts +29 -16
  26. package/src/__tests__/helpers/mock-oauth-flow.ts +103 -92
  27. package/src/__tests__/helpers/mock-process.ts +8 -13
  28. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  29. package/src/__tests__/helpers/msw/blob-worker.cjs +19 -0
  30. package/src/__tests__/helpers/msw/handlers/deployments.ts +128 -27
  31. package/src/__tests__/helpers/msw/handlers/namespaces.ts +18 -41
  32. package/src/__tests__/helpers/msw/handlers/oauth.ts +13 -18
  33. package/src/__tests__/helpers/msw/handlers/r2.ts +14 -34
  34. package/src/__tests__/helpers/msw/handlers/script.ts +9 -28
  35. package/src/__tests__/helpers/msw/handlers/user.ts +13 -24
  36. package/src/__tests__/helpers/msw/handlers/zones.ts +6 -8
  37. package/src/__tests__/helpers/msw/index.ts +32 -1
  38. package/src/__tests__/helpers/msw/read-file-sync.js +61 -0
  39. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  40. package/src/__tests__/helpers/worker-scripts/parent-worker.js +4 -1
  41. package/src/__tests__/index.test.ts +90 -72
  42. package/src/__tests__/init.test.ts +927 -631
  43. package/src/__tests__/jest.setup.ts +19 -42
  44. package/src/__tests__/kv.test.ts +355 -231
  45. package/src/__tests__/logger.test.ts +68 -2
  46. package/src/__tests__/logout.test.ts +47 -0
  47. package/src/__tests__/metrics.test.ts +94 -51
  48. package/src/__tests__/middleware.scheduled.test.ts +42 -32
  49. package/src/__tests__/middleware.test.ts +212 -122
  50. package/src/__tests__/mtls-certificates.test.ts +588 -0
  51. package/src/__tests__/pages/deployment-list.test.ts +80 -0
  52. package/src/__tests__/pages/functions-build.test.ts +452 -0
  53. package/src/__tests__/pages/pages.test.ts +81 -0
  54. package/src/__tests__/pages/project-create.test.ts +63 -0
  55. package/src/__tests__/pages/project-list.test.ts +110 -0
  56. package/src/__tests__/pages/project-upload.test.ts +500 -0
  57. package/src/__tests__/pages/publish.test.ts +2864 -0
  58. package/src/__tests__/pages-deployment-tail.test.ts +955 -0
  59. package/src/__tests__/parse.test.ts +106 -0
  60. package/src/__tests__/publish.test.ts +1615 -852
  61. package/src/__tests__/pubsub.test.ts +226 -100
  62. package/src/__tests__/queues.test.ts +238 -77
  63. package/src/__tests__/r2.test.ts +55 -57
  64. package/src/__tests__/secret.test.ts +179 -130
  65. package/src/__tests__/tail.test.ts +267 -109
  66. package/src/__tests__/test-old-node-version.js +3 -3
  67. package/src/__tests__/traverse-module-graph.test.ts +220 -0
  68. package/src/__tests__/tsconfig-sanity.ts +12 -0
  69. package/src/__tests__/tsconfig.json +8 -0
  70. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  71. package/src/__tests__/type-generation.test.ts +43 -26
  72. package/src/__tests__/user.test.ts +35 -72
  73. package/src/__tests__/whoami.test.tsx +8 -114
  74. package/src/__tests__/worker-namespace.test.ts +83 -69
  75. package/src/api/dev.ts +168 -60
  76. package/src/api/index.ts +10 -1
  77. package/src/api/mtls-certificate.ts +148 -0
  78. package/src/api/pages/create-worker-bundle-contents.ts +76 -0
  79. package/src/api/pages/index.ts +5 -0
  80. package/src/api/pages/publish.tsx +355 -0
  81. package/src/bundle.ts +263 -140
  82. package/src/cfetch/index.ts +0 -2
  83. package/src/cfetch/internal.ts +16 -21
  84. package/src/cli.ts +4 -4
  85. package/src/config/config.ts +14 -7
  86. package/src/config/environment.ts +79 -24
  87. package/src/config/index.ts +99 -38
  88. package/src/config/validation-helpers.ts +1 -1
  89. package/src/config/validation.ts +248 -19
  90. package/src/create-worker-preview.ts +19 -8
  91. package/src/create-worker-upload-form.ts +60 -22
  92. package/src/d1/backups.tsx +43 -42
  93. package/src/d1/constants.ts +2 -0
  94. package/src/d1/create.tsx +44 -30
  95. package/src/d1/{delete.tsx → delete.ts} +11 -14
  96. package/src/d1/execute.tsx +209 -151
  97. package/src/d1/index.ts +31 -7
  98. package/src/d1/list.tsx +22 -10
  99. package/src/d1/migrations/apply.tsx +212 -0
  100. package/src/d1/migrations/create.tsx +79 -0
  101. package/src/d1/migrations/helpers.ts +172 -0
  102. package/src/d1/migrations/index.ts +3 -0
  103. package/src/d1/migrations/list.tsx +95 -0
  104. package/src/d1/migrations/options.ts +23 -0
  105. package/src/d1/options.ts +12 -2
  106. package/src/d1/splitter.ts +161 -0
  107. package/src/d1/{types.tsx → types.ts} +11 -0
  108. package/src/d1/utils.ts +12 -2
  109. package/src/delete.ts +8 -16
  110. package/src/deployments.ts +340 -46
  111. package/src/deprecated/index.ts +8 -302
  112. package/src/dev/dev.tsx +57 -44
  113. package/src/dev/local.tsx +294 -91
  114. package/src/dev/remote.tsx +32 -3
  115. package/src/dev/start-server.ts +89 -68
  116. package/src/dev/use-esbuild.ts +17 -18
  117. package/src/dev/validate-dev-props.ts +9 -0
  118. package/src/{dev-registry.tsx → dev-registry.ts} +2 -1
  119. package/src/dev.tsx +178 -118
  120. package/src/dialogs.ts +136 -0
  121. package/src/dispatch-namespace.ts +21 -17
  122. package/src/docs/index.ts +97 -0
  123. package/src/entry.ts +19 -11
  124. package/src/environment-variables/factory.ts +88 -0
  125. package/src/environment-variables/misc-variables.ts +30 -0
  126. package/src/generate/index.ts +298 -0
  127. package/src/git-client.ts +15 -4
  128. package/src/{index.tsx → index.ts} +137 -63
  129. package/src/init.ts +249 -187
  130. package/src/inspect.ts +16 -1
  131. package/src/jest.d.ts +4 -0
  132. package/src/kv/index.ts +15 -17
  133. package/src/logger.ts +32 -5
  134. package/src/metrics/metrics-config.ts +3 -3
  135. package/src/metrics/send-event.ts +6 -1
  136. package/src/miniflare-cli/assets.ts +64 -28
  137. package/src/miniflare-cli/index.ts +4 -7
  138. package/src/miniflare-cli/tsconfig.json +9 -0
  139. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  140. package/src/miniflare-cli/types.ts +11 -0
  141. package/src/module-collection.ts +91 -25
  142. package/src/mtls-certificate/cli.ts +155 -0
  143. package/src/pages/build.ts +410 -0
  144. package/src/pages/buildFunctions.ts +140 -0
  145. package/src/pages/deployment-tails.ts +281 -0
  146. package/src/pages/deployments.tsx +11 -33
  147. package/src/pages/{dev.tsx → dev.ts} +147 -124
  148. package/src/pages/errors.ts +1 -0
  149. package/src/pages/functions/buildPlugin.ts +72 -69
  150. package/src/pages/functions/buildWorker.ts +249 -114
  151. package/src/pages/functions/tsconfig.json +8 -0
  152. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  153. package/src/pages/{functions.tsx → functions.ts} +8 -4
  154. package/src/pages/{index.tsx → index.ts} +11 -3
  155. package/src/pages/projects.tsx +12 -22
  156. package/src/pages/prompt-select-project.tsx +31 -0
  157. package/src/pages/publish.tsx +45 -214
  158. package/src/pages/types.ts +6 -9
  159. package/src/pages/upload.tsx +58 -14
  160. package/src/pages/utils.ts +14 -3
  161. package/src/parse.ts +23 -1
  162. package/src/paths.ts +1 -1
  163. package/src/proxy.ts +5 -0
  164. package/src/publish/index.ts +20 -16
  165. package/src/publish/publish.ts +72 -47
  166. package/src/pubsub/{pubsub-commands.tsx → pubsub-commands.ts} +19 -20
  167. package/src/queues/cli/commands/consumer/add.ts +24 -24
  168. package/src/queues/cli/commands/consumer/index.ts +3 -6
  169. package/src/queues/cli/commands/consumer/remove.ts +11 -18
  170. package/src/queues/cli/commands/create.ts +8 -8
  171. package/src/queues/cli/commands/delete.ts +8 -8
  172. package/src/queues/cli/commands/index.ts +6 -4
  173. package/src/queues/cli/commands/list.ts +8 -8
  174. package/src/queues/client.ts +1 -0
  175. package/src/queues/utils.ts +18 -0
  176. package/src/r2/constants.ts +4 -0
  177. package/src/r2/helpers.ts +1 -0
  178. package/src/r2/index.ts +40 -28
  179. package/src/secret/index.ts +14 -17
  180. package/src/{sites.tsx → sites.ts} +1 -1
  181. package/src/tail/createTail.ts +94 -3
  182. package/src/tail/filters.ts +1 -1
  183. package/src/tail/index.ts +8 -11
  184. package/src/tail/printing.ts +15 -0
  185. package/src/traverse-module-graph.ts +53 -0
  186. package/src/tsconfig-sanity.ts +16 -0
  187. package/src/type-generation.ts +79 -57
  188. package/src/user/access.ts +0 -1
  189. package/src/user/auth-variables.ts +113 -0
  190. package/src/user/choose-account.tsx +1 -31
  191. package/src/user/index.ts +0 -1
  192. package/src/user/{user.tsx → user.ts} +123 -82
  193. package/src/utils/render.ts +93 -0
  194. package/src/{whoami.tsx → whoami.ts} +37 -71
  195. package/src/worker.ts +35 -3
  196. package/src/yargs-types.ts +22 -5
  197. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  198. package/templates/__tests__/tsconfig.json +8 -0
  199. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  200. package/templates/checked-fetch.js +9 -3
  201. package/templates/d1-beta-facade.js +95 -25
  202. package/templates/facade.d.ts +14 -0
  203. package/templates/first-party-worker-module-facade.ts +4 -3
  204. package/templates/format-dev-errors.ts +8 -6
  205. package/templates/gitignore +1 -0
  206. package/templates/init-tests/test-jest-new-worker.js +3 -5
  207. package/templates/init-tests/test-vitest-new-worker.js +3 -5
  208. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  209. package/templates/middleware/loader-modules.ts +2 -2
  210. package/templates/middleware/loader-sw.ts +51 -31
  211. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  212. package/templates/new-worker.ts +3 -0
  213. package/templates/pages-dev-pipeline.ts +4 -1
  214. package/templates/pages-shim.ts +4 -1
  215. package/templates/pages-template-plugin.ts +19 -10
  216. package/templates/serve-static-assets.ts +17 -14
  217. package/templates/service-bindings-module-facade.js +1 -0
  218. package/templates/tsconfig-sanity.ts +11 -0
  219. package/templates/tsconfig.init.json +105 -0
  220. package/templates/tsconfig.json +5 -103
  221. package/templates/tsconfig.tsbuildinfo +1 -0
  222. package/wrangler-dist/cli.d.ts +826 -77
  223. package/wrangler-dist/cli.js +130734 -140838
  224. package/wrangler-dist/wasm-sync.wasm +0 -0
  225. package/src/__tests__/api-devregistry.test.js +0 -57
  226. package/src/__tests__/d1.test.ts +0 -72
  227. package/src/__tests__/dialogs.test.tsx +0 -40
  228. package/src/__tests__/helpers/mock-cfetch.ts +0 -333
  229. package/src/__tests__/pages.test.ts +0 -2223
  230. package/src/dialogs.tsx +0 -163
  231. package/src/environment-variables.ts +0 -50
  232. package/src/pages/build.tsx +0 -238
  233. package/src/user/env-vars.ts +0 -46
  234. package/templates/experimental-local-cache-stubs.js +0 -27
  235. /package/src/{bundle-reporter.tsx → bundle-reporter.ts} +0 -0
  236. /package/src/dev/{get-local-persistence-path.tsx → get-local-persistence-path.ts} +0 -0
  237. /package/src/pages/{hash.tsx → hash.ts} +0 -0
@@ -1,6 +1,7 @@
1
1
  import crypto from "node:crypto";
2
2
  import { readFile } from "node:fs/promises";
3
3
  import path from "node:path";
4
+ import chalk from "chalk";
4
5
  import globToRegExp from "glob-to-regexp";
5
6
  import { logger } from "./logger";
6
7
  import type { Config, ConfigModuleRuleType } from "./config";
@@ -38,28 +39,8 @@ export const DEFAULT_MODULE_RULES: Config["rules"] = [
38
39
  { type: "CompiledWasm", globs: ["**/*.wasm"] },
39
40
  ];
40
41
 
41
- export default function createModuleCollector(props: {
42
- format: CfScriptFormat;
43
- rules?: Config["rules"];
44
- // a collection of "legacy" style module references, which are just file names
45
- // we will eventually deprecate this functionality, hence the verbose greppable name
46
- wrangler1xlegacyModuleReferences: {
47
- rootDirectory: string;
48
- fileNames: Set<string>;
49
- };
50
- }): {
51
- modules: CfModule[];
52
- plugin: esbuild.Plugin;
53
- } {
54
- const rules: Config["rules"] = [
55
- ...(props.rules || []),
56
- // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
57
- ...DEFAULT_MODULE_RULES!,
58
- ];
59
-
60
- // First, we want to add some validations to the module rules
61
- // We want to warn if rules are accidentally configured in such a way that
62
- // subsequent rules will never match because `fallthrough` hasn't been set
42
+ export function parseRules(userRules: Config["rules"] = []) {
43
+ const rules: Config["rules"] = [...userRules, ...DEFAULT_MODULE_RULES];
63
44
 
64
45
  const completedRuleLocations: Record<string, number> = {};
65
46
  let index = 0;
@@ -67,7 +48,7 @@ export default function createModuleCollector(props: {
67
48
  for (const rule of rules) {
68
49
  if (rule.type in completedRuleLocations) {
69
50
  if (rules[completedRuleLocations[rule.type]].fallthrough !== false) {
70
- if (index < (props.rules || []).length) {
51
+ if (index < userRules.length) {
71
52
  logger.warn(
72
53
  `The module rule at position ${index} (${JSON.stringify(
73
54
  rule
@@ -101,6 +82,89 @@ export default function createModuleCollector(props: {
101
82
  // eslint-disable-next-line @typescript-eslint/no-non-null-assertion
102
83
  rulesToRemove.forEach((rule) => rules!.splice(rules!.indexOf(rule), 1));
103
84
 
85
+ return { rules, removedRules: rulesToRemove };
86
+ }
87
+
88
+ export async function matchFiles(
89
+ files: string[],
90
+ relativeTo: string,
91
+ {
92
+ rules,
93
+ removedRules,
94
+ }: { rules: Config["rules"]; removedRules: Config["rules"] }
95
+ ) {
96
+ const modules: CfModule[] = [];
97
+
98
+ // Deduplicate modules. This is usually a poorly specified `wrangler.toml` configuration, but duplicate modules will cause a crash at runtime
99
+ const moduleNames = new Set<string>();
100
+ for (const rule of rules) {
101
+ for (const glob of rule.globs) {
102
+ const regexp = globToRegExp(glob, {
103
+ globstar: true,
104
+ });
105
+ const newModules = await Promise.all(
106
+ files
107
+ .filter((f) => regexp.test(f))
108
+ .map(async (name) => {
109
+ const filePath = name;
110
+ const fileContent = await readFile(path.join(relativeTo, filePath));
111
+
112
+ return {
113
+ name: filePath,
114
+ content: fileContent,
115
+ type: RuleTypeToModuleType[rule.type],
116
+ };
117
+ })
118
+ );
119
+ for (const module of newModules) {
120
+ if (!moduleNames.has(module.name)) {
121
+ moduleNames.add(module.name);
122
+ modules.push(module);
123
+ } else {
124
+ logger.warn(
125
+ `Ignoring duplicate module: ${chalk.blue(
126
+ module.name
127
+ )} (${chalk.green(module.type ?? "")})`
128
+ );
129
+ }
130
+ }
131
+ }
132
+ }
133
+
134
+ // This is just a sanity check verifying that no files match rules that were removed
135
+ for (const rule of removedRules) {
136
+ for (const glob of rule.globs) {
137
+ const regexp = globToRegExp(glob);
138
+ for (const file of files) {
139
+ if (regexp.test(file)) {
140
+ throw new Error(
141
+ `The file ${file} matched a module rule in your configuration (${JSON.stringify(
142
+ rule
143
+ )}), but was ignored because a previous rule with the same type was not marked as \`fallthrough = true\`.`
144
+ );
145
+ }
146
+ }
147
+ }
148
+ }
149
+ return modules;
150
+ }
151
+
152
+ export default function createModuleCollector(props: {
153
+ format: CfScriptFormat;
154
+ rules?: Config["rules"];
155
+ // a collection of "legacy" style module references, which are just file names
156
+ // we will eventually deprecate this functionality, hence the verbose greppable name
157
+ wrangler1xlegacyModuleReferences: {
158
+ rootDirectory: string;
159
+ fileNames: Set<string>;
160
+ };
161
+ preserveFileNames?: boolean;
162
+ }): {
163
+ modules: CfModule[];
164
+ plugin: esbuild.Plugin;
165
+ } {
166
+ const { rules, removedRules } = parseRules(props.rules);
167
+
104
168
  const modules: CfModule[] = [];
105
169
  return {
106
170
  modules,
@@ -206,7 +270,9 @@ export default function createModuleCollector(props: {
206
270
  .createHash("sha1")
207
271
  .update(fileContent)
208
272
  .digest("hex");
209
- const fileName = `./${fileHash}-${path.basename(args.path)}`;
273
+ const fileName = props.preserveFileNames
274
+ ? filePath
275
+ : `./${fileHash}-${path.basename(args.path)}`;
210
276
 
211
277
  // add the module to the array
212
278
  modules.push({
@@ -245,7 +311,7 @@ export default function createModuleCollector(props: {
245
311
  });
246
312
  });
247
313
 
248
- rulesToRemove.forEach((rule) => {
314
+ removedRules.forEach((rule) => {
249
315
  rule.globs.forEach((glob) => {
250
316
  build.onResolve(
251
317
  { filter: globToRegExp(glob) },
@@ -0,0 +1,155 @@
1
+ import {
2
+ uploadMTlsCertificateFromFs,
3
+ listMTlsCertificates,
4
+ deleteMTlsCertificate,
5
+ getMTlsCertificate,
6
+ getMTlsCertificateByName,
7
+ type MTlsCertificateResponse,
8
+ } from "../api/mtls-certificate";
9
+ import { withConfig } from "../config";
10
+ import { confirm } from "../dialogs";
11
+ import { logger } from "../logger";
12
+ import { requireAuth } from "../user";
13
+ import type {
14
+ CommonYargsOptions,
15
+ CommonYargsArgv,
16
+ StrictYargsOptionsToInterface,
17
+ } from "../yargs-types";
18
+ import type { BuilderCallback } from "yargs";
19
+
20
+ function uploadMTlsCertificateOptions(yargs: CommonYargsArgv) {
21
+ return yargs
22
+ .option("cert", {
23
+ describe:
24
+ "The path to a certificate file (.pem) containing a chain of certificates to upload",
25
+ type: "string",
26
+ demandOption: true,
27
+ })
28
+ .option("key", {
29
+ describe:
30
+ "The path to a file containing the private key for your leaf certificate",
31
+ type: "string",
32
+ demandOption: true,
33
+ })
34
+ .option("name", {
35
+ describe: "The name for the certificate",
36
+ type: "string",
37
+ });
38
+ }
39
+
40
+ const uploadMTlsCertificateHandler = withConfig<
41
+ StrictYargsOptionsToInterface<typeof uploadMTlsCertificateOptions>
42
+ >(async ({ config, cert, key, name }) => {
43
+ const accountId = await requireAuth(config);
44
+ logger.log(
45
+ name
46
+ ? `Uploading mTLS Certificate ${name}...`
47
+ : `Uploading mTLS Certificate...`
48
+ );
49
+ const certResponse = await uploadMTlsCertificateFromFs(accountId, {
50
+ certificateChainFilename: cert,
51
+ privateKeyFilename: key,
52
+ name: name,
53
+ });
54
+ const expiresOn = new Date(certResponse.expires_on).toLocaleDateString();
55
+ logger.log(
56
+ name
57
+ ? `Success! Uploaded mTLS Certificate ${name}`
58
+ : `Success! Uploaded mTLS Certificate`
59
+ );
60
+ logger.log(`ID: ${certResponse.id}`);
61
+ logger.log(`Issuer: ${certResponse.issuer}`);
62
+ logger.log(`Expires on ${expiresOn}`);
63
+ });
64
+
65
+ const listMTlsCertificatesHandler = withConfig(async ({ config }) => {
66
+ const accountId = await requireAuth(config);
67
+ const certificates = await listMTlsCertificates(accountId, {});
68
+ for (const certificate of certificates) {
69
+ logger.log(`ID: ${certificate.id}`);
70
+ if (certificate.name) {
71
+ logger.log(`Name: ${certificate.name}`);
72
+ }
73
+ logger.log(`Issuer: ${certificate.issuer}`);
74
+ logger.log(
75
+ `Created on: ${new Date(certificate.uploaded_on).toLocaleDateString()}`
76
+ );
77
+ logger.log(
78
+ `Expires on: ${new Date(certificate.expires_on).toLocaleDateString()}`
79
+ );
80
+ logger.log("\n");
81
+ }
82
+ });
83
+
84
+ function deleteMTlsCertificateOptions(yargs: CommonYargsArgv) {
85
+ return yargs
86
+ .option("id", {
87
+ describe: "The id of the mTLS certificate to delete",
88
+ type: "string",
89
+ })
90
+ .option("name", {
91
+ describe: "The name of the mTLS certificate record to delete",
92
+ type: "string",
93
+ });
94
+ }
95
+
96
+ const deleteMTlsCertificateHandler = withConfig<
97
+ StrictYargsOptionsToInterface<typeof deleteMTlsCertificateOptions>
98
+ >(async ({ config, id, name }) => {
99
+ const accountId = await requireAuth(config);
100
+ if (id && name) {
101
+ return logger.error(`Error: can't provide both --id and --name.`);
102
+ } else if (!id && !name) {
103
+ return logger.error(`Error: must provide --id or --name.`);
104
+ }
105
+ let certificate: MTlsCertificateResponse;
106
+ if (id) {
107
+ certificate = await getMTlsCertificate(accountId, id);
108
+ } else {
109
+ certificate = await getMTlsCertificateByName(accountId, name as string);
110
+ }
111
+
112
+ const response = await confirm(
113
+ certificate.name
114
+ ? `Are you sure you want to delete certificate ${certificate.id} (${certificate.name})?`
115
+ : `Are you sure you want to delete certificate ${certificate.id}?`
116
+ );
117
+ if (!response) {
118
+ logger.log("Not deleting");
119
+ return;
120
+ }
121
+
122
+ await deleteMTlsCertificate(accountId, certificate.id);
123
+
124
+ logger.log(
125
+ certificate.name
126
+ ? `Deleted certificate ${certificate.id} (${certificate.name}) successfully`
127
+ : `Deleted certificate ${certificate.id} successfully`
128
+ );
129
+ });
130
+
131
+ export const mTlsCertificateCommands: BuilderCallback<
132
+ CommonYargsOptions,
133
+ unknown
134
+ > = (yargs) => {
135
+ yargs.command(
136
+ "upload",
137
+ "Upload an mTLS certificate",
138
+ uploadMTlsCertificateOptions,
139
+ uploadMTlsCertificateHandler
140
+ );
141
+
142
+ yargs.command(
143
+ "list",
144
+ "List uploaded mTLS certificates",
145
+ (a) => a,
146
+ listMTlsCertificatesHandler
147
+ );
148
+
149
+ yargs.command(
150
+ "delete",
151
+ "Delete an mTLS certificate",
152
+ deleteMTlsCertificateOptions,
153
+ deleteMTlsCertificateHandler
154
+ );
155
+ };
@@ -0,0 +1,410 @@
1
+ import { existsSync, mkdirSync, writeFileSync } from "node:fs";
2
+ import { basename, dirname, relative, resolve as resolvePath } from "node:path";
3
+ import { createUploadWorkerBundleContents } from "../api/pages/create-worker-bundle-contents";
4
+ import { FatalError } from "../errors";
5
+ import { logger } from "../logger";
6
+ import * as metrics from "../metrics";
7
+ import { buildFunctions } from "./buildFunctions";
8
+ import { isInPagesCI } from "./constants";
9
+ import {
10
+ EXIT_CODE_FUNCTIONS_NOTHING_TO_BUILD_ERROR,
11
+ EXIT_CODE_FUNCTIONS_NO_ROUTES_ERROR,
12
+ FunctionsNoRoutesError,
13
+ getFunctionsNoRoutesWarning,
14
+ } from "./errors";
15
+ import { buildRawWorker } from "./functions/buildWorker";
16
+ import { pagesBetaWarning } from "./utils";
17
+ import type { BundleResult } from "../bundle";
18
+ import type {
19
+ CommonYargsArgv,
20
+ StrictYargsOptionsToInterface,
21
+ } from "../yargs-types";
22
+
23
+ export type PagesBuildArgs = StrictYargsOptionsToInterface<typeof Options>;
24
+
25
+ export function Options(yargs: CommonYargsArgv) {
26
+ return yargs
27
+ .positional("directory", {
28
+ type: "string",
29
+ default: "functions",
30
+ description: "The directory of Pages Functions",
31
+ })
32
+ .options({
33
+ outfile: {
34
+ type: "string",
35
+ description: "The location of the output Worker script",
36
+ },
37
+ outdir: {
38
+ type: "string",
39
+ description: "Output directory for the bundled Worker",
40
+ },
41
+ "output-config-path": {
42
+ type: "string",
43
+ description: "The location for the output config file",
44
+ },
45
+ "output-routes-path": {
46
+ type: "string",
47
+ description: "The location for the output _routes.json file",
48
+ },
49
+ minify: {
50
+ type: "boolean",
51
+ default: false,
52
+ description: "Minify the output Worker script",
53
+ },
54
+ sourcemap: {
55
+ type: "boolean",
56
+ default: false,
57
+ description: "Generate a sourcemap for the output Worker script",
58
+ },
59
+ "fallback-service": {
60
+ type: "string",
61
+ default: "ASSETS",
62
+ description:
63
+ "The service to fallback to at the end of the `next` chain. Setting to '' will fallback to the global `fetch`.",
64
+ },
65
+ watch: {
66
+ type: "boolean",
67
+ default: false,
68
+ description:
69
+ "Watch for changes to the functions and automatically rebuild the Worker script",
70
+ },
71
+ plugin: {
72
+ type: "boolean",
73
+ default: false,
74
+ description: "Build a plugin rather than a Worker script",
75
+ },
76
+ "build-output-directory": {
77
+ type: "string",
78
+ description: "The directory to output static assets to",
79
+ },
80
+ "node-compat": {
81
+ describe: "Enable Node.js compatibility",
82
+ default: false,
83
+ type: "boolean",
84
+ hidden: true,
85
+ },
86
+ "compatibility-date": {
87
+ describe: "Date to use for compatibility checks",
88
+ type: "string",
89
+ requiresArg: true,
90
+ },
91
+ "compatibility-flags": {
92
+ describe: "Flags to use for compatibility checks",
93
+ alias: "compatibility-flag",
94
+ type: "string",
95
+ requiresArg: true,
96
+ array: true,
97
+ },
98
+ bindings: {
99
+ type: "string",
100
+ describe:
101
+ "Bindings used in Functions (used to register beta product shims)",
102
+ deprecated: true,
103
+ hidden: true,
104
+ },
105
+ })
106
+ .epilogue(pagesBetaWarning);
107
+ }
108
+
109
+ export const Handler = async (args: PagesBuildArgs) => {
110
+ if (!isInPagesCI) {
111
+ // Beta message for `wrangler pages <commands>` usage
112
+ logger.log(pagesBetaWarning);
113
+ }
114
+
115
+ const validatedArgs = validateArgs(args);
116
+
117
+ let bundle: BundleResult | undefined = undefined;
118
+
119
+ if (validatedArgs.plugin) {
120
+ const {
121
+ directory,
122
+ outfile,
123
+ outdir,
124
+ outputConfigPath,
125
+ outputRoutesPath: routesOutputPath,
126
+ minify,
127
+ sourcemap,
128
+ fallbackService,
129
+ watch,
130
+ plugin,
131
+ nodejsCompat,
132
+ legacyNodeCompat,
133
+ } = validatedArgs;
134
+
135
+ try {
136
+ /**
137
+ * `buildFunctions` builds `/functions`, but doesn't give us the bundle
138
+ * we want to return, which includes the external dependencies (like wasm,
139
+ * binary, text). Let's output that build result to memory and only write
140
+ * to disk once we have the final bundle
141
+ */
142
+ bundle = await buildFunctions({
143
+ outfile,
144
+ outdir,
145
+ outputConfigPath,
146
+ functionsDirectory: directory,
147
+ minify,
148
+ sourcemap,
149
+ fallbackService,
150
+ watch,
151
+ plugin,
152
+ legacyNodeCompat,
153
+ nodejsCompat,
154
+ routesOutputPath,
155
+ local: false,
156
+ });
157
+ } catch (e) {
158
+ if (e instanceof FunctionsNoRoutesError) {
159
+ throw new FatalError(
160
+ getFunctionsNoRoutesWarning(directory),
161
+ EXIT_CODE_FUNCTIONS_NO_ROUTES_ERROR
162
+ );
163
+ } else {
164
+ throw e;
165
+ }
166
+ }
167
+
168
+ if (outfile && outfile !== bundle.resolvedEntryPointPath) {
169
+ writeFileSync(
170
+ outfile,
171
+ `export { default } from './${relative(
172
+ dirname(outfile),
173
+ bundle.resolvedEntryPointPath
174
+ )}'`
175
+ );
176
+ }
177
+ } else {
178
+ const {
179
+ directory,
180
+ outfile,
181
+ outdir,
182
+ outputConfigPath,
183
+ outputRoutesPath: routesOutputPath,
184
+ minify,
185
+ sourcemap,
186
+ fallbackService,
187
+ watch,
188
+ plugin,
189
+ buildOutputDirectory,
190
+ nodejsCompat,
191
+ legacyNodeCompat,
192
+ bindings,
193
+ workerScriptPath,
194
+ } = validatedArgs;
195
+
196
+ let d1Databases: string[] | undefined = undefined;
197
+ if (bindings) {
198
+ try {
199
+ const decodedBindings = JSON.parse(bindings);
200
+ d1Databases = Object.keys(decodedBindings?.d1_databases || {});
201
+ } catch {
202
+ throw new FatalError("Could not parse a valid set of 'bindings'.", 1);
203
+ }
204
+ }
205
+
206
+ /**
207
+ * prioritize building `_worker.js` over Pages Functions, if both exist
208
+ * and if we were able to resolve _worker.js
209
+ */
210
+ if (workerScriptPath) {
211
+ /**
212
+ * `buildRawWorker` builds `_worker.js`, but doesn't give us the bundle
213
+ * we want to return, which includes the external dependencies (like wasm,
214
+ * binary, text). Let's output that build result to memory and only write
215
+ * to disk once we have the final bundle
216
+ */
217
+ bundle = await buildRawWorker({
218
+ workerScriptPath,
219
+ outdir,
220
+ directory: buildOutputDirectory,
221
+ local: false,
222
+ sourcemap,
223
+ watch,
224
+ betaD1Shims: d1Databases,
225
+ });
226
+ } else {
227
+ try {
228
+ /**
229
+ * `buildFunctions` builds `/functions`, but doesn't give us the bundle
230
+ * we want to return, which includes the external dependencies (like wasm,
231
+ * binary, text). Let's output that build result to memory and only write
232
+ * to disk once we have the final bundle
233
+ */
234
+ bundle = await buildFunctions({
235
+ outdir,
236
+ outputConfigPath,
237
+ functionsDirectory: directory,
238
+ minify,
239
+ sourcemap,
240
+ fallbackService,
241
+ watch,
242
+ plugin,
243
+ buildOutputDirectory,
244
+ legacyNodeCompat,
245
+ nodejsCompat,
246
+ routesOutputPath,
247
+ local: false,
248
+ d1Databases,
249
+ });
250
+ } catch (e) {
251
+ if (e instanceof FunctionsNoRoutesError) {
252
+ throw new FatalError(
253
+ getFunctionsNoRoutesWarning(directory),
254
+ EXIT_CODE_FUNCTIONS_NO_ROUTES_ERROR
255
+ );
256
+ } else {
257
+ throw e;
258
+ }
259
+ }
260
+ }
261
+
262
+ if (outfile) {
263
+ const workerBundleContents = await createUploadWorkerBundleContents(
264
+ bundle as BundleResult
265
+ );
266
+
267
+ mkdirSync(dirname(outfile), { recursive: true });
268
+ writeFileSync(
269
+ outfile,
270
+ Buffer.from(await workerBundleContents.arrayBuffer())
271
+ );
272
+ }
273
+ }
274
+
275
+ await metrics.sendMetricsEvent("build pages functions");
276
+ };
277
+
278
+ type WorkerBundleArgs = Omit<PagesBuildArgs, "nodeCompat"> & {
279
+ plugin: false;
280
+ buildOutputDirectory: string;
281
+ legacyNodeCompat: boolean;
282
+ nodejsCompat: boolean;
283
+
284
+ workerScriptPath: string;
285
+ };
286
+ type PluginArgs = Omit<
287
+ PagesBuildArgs,
288
+ "buildOutputDirectory" | "bindings" | "nodeCompat"
289
+ > & {
290
+ plugin: true;
291
+ outdir: string;
292
+ legacyNodeCompat: boolean;
293
+ nodejsCompat: boolean;
294
+ };
295
+
296
+ type ValidatedArgs = WorkerBundleArgs | PluginArgs;
297
+
298
+ const validateArgs = (args: PagesBuildArgs): ValidatedArgs => {
299
+ if (args.outdir && args.outfile) {
300
+ throw new FatalError(
301
+ "Cannot specify both an `--outdir` and an `--outfile`.",
302
+ 1
303
+ );
304
+ }
305
+
306
+ if (args.plugin) {
307
+ if (args.outfile) {
308
+ // Explicit old behavior. Encourage to migrate to `--outdir` instead.
309
+ logger.warn(
310
+ "Creating a Pages Plugin with `--outfile` is now deprecated. Please use `--outdir` instead."
311
+ );
312
+
313
+ args.outdir = dirname(resolvePath(args.outfile));
314
+ } else if (!args.outfile && !args.outdir) {
315
+ // Didn't specify `--outfile`, but didn't specify `--outdir` either. Implicit old behavior defaults. Encourage to migrate to `--outdir`.
316
+ args.outfile ??= "_worker.js";
317
+ args.outdir = ".";
318
+
319
+ logger.warn(
320
+ "Creating a Pages Plugin without `--outdir` is now deprecated. Please add an `--outdir` argument."
321
+ );
322
+ }
323
+
324
+ if (args.bindings) {
325
+ throw new FatalError(
326
+ "The `--bindings` flag cannot be used when creating a Pages Plugin with `--plugin`.",
327
+ 1
328
+ );
329
+ }
330
+
331
+ if (args.buildOutputDirectory) {
332
+ throw new FatalError(
333
+ "The `--build-output-directory` flag cannot be used when creating a Pages Plugin with `--plugin`.",
334
+ 1
335
+ );
336
+ }
337
+ } else {
338
+ if (!args.outdir) {
339
+ args.outfile ??= "_worker.bundle";
340
+ }
341
+
342
+ args.buildOutputDirectory ??= args.outfile ? dirname(args.outfile) : ".";
343
+ }
344
+
345
+ if (args.buildOutputDirectory) {
346
+ args.buildOutputDirectory = resolvePath(args.buildOutputDirectory);
347
+ }
348
+ if (args.outdir) {
349
+ args.outdir = resolvePath(args.outdir);
350
+ }
351
+ if (args.outfile) {
352
+ args.outfile = resolvePath(args.outfile);
353
+ }
354
+
355
+ const { nodeCompat: legacyNodeCompat, ...argsExceptNodeCompat } = args;
356
+ if (legacyNodeCompat) {
357
+ console.warn(
358
+ "Enabling Node.js compatibility mode for builtins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
359
+ );
360
+ }
361
+ const nodejsCompat = !!args.compatibilityFlags?.includes("nodejs_compat");
362
+ if (legacyNodeCompat && nodejsCompat) {
363
+ throw new Error(
364
+ "The `nodejs_compat` compatibility flag cannot be used in conjunction with the legacy `--node-compat` flag. If you want to use the Workers runtime Node.js compatibility features, please remove the `--node-compat` argument from your CLI command."
365
+ );
366
+ }
367
+
368
+ let workerScriptPath: string | undefined;
369
+
370
+ if (args.buildOutputDirectory) {
371
+ const prospectiveWorkerScriptPath = resolvePath(
372
+ args.buildOutputDirectory,
373
+ "_worker.js"
374
+ );
375
+
376
+ const foundWorkerScript = existsSync(prospectiveWorkerScriptPath);
377
+
378
+ if (foundWorkerScript) {
379
+ workerScriptPath = prospectiveWorkerScriptPath;
380
+ } else if (!foundWorkerScript && !existsSync(args.directory)) {
381
+ throw new FatalError(
382
+ `Could not find anything to build.
383
+ We first looked inside the build output directory (${basename(
384
+ resolvePath(args.buildOutputDirectory)
385
+ )}), then looked for the Functions directory (${basename(
386
+ args.directory
387
+ )}) but couldn't find anything to build.
388
+ ➤ If you are trying to build _worker.js, please make sure you provide the [--build-output-directory] containing your static files.
389
+ ➤ If you are trying to build Pages Functions, please make sure [directory] points to the location of your Functions files.`,
390
+ EXIT_CODE_FUNCTIONS_NOTHING_TO_BUILD_ERROR
391
+ );
392
+ }
393
+ } else if (!existsSync(args.directory)) {
394
+ throw new FatalError(
395
+ `Could not find anything to build.
396
+ We looked for the Functions directory (${basename(
397
+ args.directory
398
+ )}) but couldn't find anything to build.
399
+ ➤ Please make sure [directory] points to the location of your Functions files.`,
400
+ EXIT_CODE_FUNCTIONS_NOTHING_TO_BUILD_ERROR
401
+ );
402
+ }
403
+
404
+ return {
405
+ ...argsExceptNodeCompat,
406
+ workerScriptPath,
407
+ nodejsCompat,
408
+ legacyNodeCompat,
409
+ } as ValidatedArgs;
410
+ };