wrangler 0.0.0-e6c9c5c0 → 0.0.0-e6e1daba

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 (126) hide show
  1. package/README.md +3 -3
  2. package/miniflare-dist/index.mjs +22 -18
  3. package/package.json +12 -12
  4. package/src/__tests__/configuration.test.ts +70 -0
  5. package/src/__tests__/d1/d1.test.ts +13 -58
  6. package/src/__tests__/d1/execute.test.ts +64 -0
  7. package/src/__tests__/d1/migrate.test.ts +155 -0
  8. package/src/__tests__/deployments.test.ts +40 -16
  9. package/src/__tests__/dev.test.tsx +8 -7
  10. package/src/__tests__/generate.test.ts +1 -1
  11. package/src/__tests__/guess-worker-format.test.ts +35 -0
  12. package/src/__tests__/helpers/end-event-loop.ts +6 -0
  13. package/src/__tests__/helpers/mock-get-pages-upload-token.ts +25 -0
  14. package/src/__tests__/helpers/mock-set-timeout.ts +16 -0
  15. package/src/__tests__/helpers/msw/handlers/deployments.ts +40 -16
  16. package/src/__tests__/helpers/string-dynamic-values-matcher.ts +28 -0
  17. package/src/__tests__/index.test.ts +38 -32
  18. package/src/__tests__/init.test.ts +1 -1
  19. package/src/__tests__/kv.test.ts +63 -52
  20. package/src/__tests__/middleware.test.ts +65 -0
  21. package/src/__tests__/mtls-certificates.test.ts +585 -0
  22. package/src/__tests__/pages/deployment-list.test.ts +78 -0
  23. package/src/__tests__/pages/functions-build.test.ts +402 -0
  24. package/src/__tests__/pages/pages.test.ts +81 -0
  25. package/src/__tests__/pages/project-create.test.ts +63 -0
  26. package/src/__tests__/pages/project-list.test.ts +108 -0
  27. package/src/__tests__/pages/project-upload.test.ts +481 -0
  28. package/src/__tests__/pages/publish.test.ts +2745 -0
  29. package/src/__tests__/parse.test.ts +106 -0
  30. package/src/__tests__/publish.test.ts +80 -30
  31. package/src/__tests__/pubsub.test.ts +15 -12
  32. package/src/__tests__/queues.test.ts +37 -30
  33. package/src/__tests__/r2.test.ts +25 -20
  34. package/src/__tests__/secret.test.ts +4 -4
  35. package/src/__tests__/tsconfig.tsbuildinfo +1 -1
  36. package/src/__tests__/user.test.ts +1 -1
  37. package/src/__tests__/whoami.test.tsx +1 -1
  38. package/src/__tests__/worker-namespace.test.ts +26 -21
  39. package/src/api/dev.ts +80 -11
  40. package/src/api/index.ts +8 -0
  41. package/src/api/mtls-certificate.ts +148 -0
  42. package/src/api/pages/create-worker-bundle-contents.ts +75 -0
  43. package/src/api/pages/publish.tsx +59 -12
  44. package/src/bundle.ts +9 -7
  45. package/src/config/config.ts +14 -7
  46. package/src/config/environment.ts +9 -2
  47. package/src/config/index.ts +37 -20
  48. package/src/config/validation.ts +50 -3
  49. package/src/create-worker-preview.ts +19 -8
  50. package/src/create-worker-upload-form.ts +9 -0
  51. package/src/d1/backups.tsx +20 -24
  52. package/src/d1/create.tsx +6 -5
  53. package/src/d1/delete.ts +7 -10
  54. package/src/d1/execute.tsx +174 -143
  55. package/src/d1/index.ts +5 -6
  56. package/src/d1/list.tsx +21 -9
  57. package/src/d1/migrations/apply.tsx +42 -33
  58. package/src/d1/migrations/create.tsx +16 -17
  59. package/src/d1/migrations/helpers.ts +63 -38
  60. package/src/d1/migrations/list.tsx +37 -24
  61. package/src/d1/migrations/options.ts +7 -2
  62. package/src/d1/options.ts +3 -3
  63. package/src/d1/types.ts +1 -0
  64. package/src/d1/utils.ts +2 -1
  65. package/src/delete.ts +5 -8
  66. package/src/deployments.ts +62 -39
  67. package/src/deprecated/index.ts +7 -8
  68. package/src/dev/dev.tsx +1 -15
  69. package/src/dev/local.tsx +5 -6
  70. package/src/dev/remote.tsx +2 -2
  71. package/src/dev.tsx +51 -86
  72. package/src/dispatch-namespace.ts +20 -16
  73. package/src/docs/index.ts +7 -8
  74. package/src/entry.ts +1 -2
  75. package/src/generate/index.ts +6 -8
  76. package/src/index.ts +37 -26
  77. package/src/init.ts +5 -7
  78. package/src/inspect.ts +16 -1
  79. package/src/kv/index.ts +15 -17
  80. package/src/miniflare-cli/assets.ts +9 -8
  81. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -1
  82. package/src/mtls-certificate/cli.ts +155 -0
  83. package/src/pages/build.ts +109 -27
  84. package/src/pages/buildFunctions.ts +32 -31
  85. package/src/pages/deployment-tails.ts +7 -10
  86. package/src/pages/deployments.tsx +6 -4
  87. package/src/pages/dev.ts +19 -19
  88. package/src/pages/functions/tsconfig.tsbuildinfo +1 -1
  89. package/src/pages/functions.ts +8 -4
  90. package/src/pages/index.ts +3 -3
  91. package/src/pages/projects.tsx +7 -12
  92. package/src/pages/publish.tsx +18 -5
  93. package/src/pages/types.ts +5 -0
  94. package/src/pages/upload.tsx +6 -4
  95. package/src/pages/utils.ts +1 -1
  96. package/src/parse.ts +23 -1
  97. package/src/publish/index.ts +19 -15
  98. package/src/publish/publish.ts +5 -4
  99. package/src/pubsub/pubsub-commands.ts +18 -19
  100. package/src/queues/cli/commands/consumer/add.ts +18 -24
  101. package/src/queues/cli/commands/consumer/index.ts +3 -6
  102. package/src/queues/cli/commands/consumer/remove.ts +11 -18
  103. package/src/queues/cli/commands/create.ts +8 -8
  104. package/src/queues/cli/commands/delete.ts +8 -8
  105. package/src/queues/cli/commands/index.ts +3 -4
  106. package/src/queues/cli/commands/list.ts +8 -8
  107. package/src/r2/helpers.ts +1 -0
  108. package/src/r2/index.ts +28 -28
  109. package/src/secret/index.ts +10 -14
  110. package/src/sites.ts +1 -1
  111. package/src/tail/filters.ts +1 -1
  112. package/src/tail/index.ts +6 -8
  113. package/src/user/user.ts +4 -3
  114. package/src/worker.ts +6 -0
  115. package/src/yargs-types.ts +18 -5
  116. package/templates/checked-fetch.js +9 -1
  117. package/templates/format-dev-errors.ts +1 -0
  118. package/templates/new-worker.ts +3 -0
  119. package/templates/pages-template-plugin.ts +7 -3
  120. package/templates/serve-static-assets.ts +1 -0
  121. package/templates/service-bindings-module-facade.js +1 -0
  122. package/templates/tsconfig.init.json +1 -1
  123. package/templates/tsconfig.tsbuildinfo +1 -1
  124. package/wrangler-dist/cli.d.ts +596 -3
  125. package/wrangler-dist/cli.js +14276 -6748
  126. package/src/__tests__/pages.test.ts +0 -2898
@@ -60,7 +60,7 @@ describe("User", () => {
60
60
  expect(counter).toBe(1);
61
61
  expect(std.out).toMatchInlineSnapshot(`
62
62
  "Attempting to login via OAuth...
63
- Opening a link in your default browser: https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=54d11594-84e4-41aa-b438-e81b8fa78ee7&redirect_uri=http%3A%2F%2Flocalhost%3A8976%2Foauth%2Fcallback&scope=account%3Aread%20user%3Aread%20workers%3Awrite%20workers_kv%3Awrite%20workers_routes%3Awrite%20workers_scripts%3Awrite%20workers_tail%3Aread%20d1%3Awrite%20pages%3Awrite%20zone%3Aread%20offline_access&state=MOCK_STATE_PARAM&code_challenge=MOCK_CODE_CHALLENGE&code_challenge_method=S256
63
+ Opening a link in your default browser: https://dash.cloudflare.com/oauth2/auth?response_type=code&client_id=54d11594-84e4-41aa-b438-e81b8fa78ee7&redirect_uri=http%3A%2F%2Flocalhost%3A8976%2Foauth%2Fcallback&scope=account%3Aread%20user%3Aread%20workers%3Awrite%20workers_kv%3Awrite%20workers_routes%3Awrite%20workers_scripts%3Awrite%20workers_tail%3Aread%20d1%3Awrite%20pages%3Awrite%20zone%3Aread%20ssl_certs%3Awrite%20offline_access&state=MOCK_STATE_PARAM&code_challenge=MOCK_CODE_CHALLENGE&code_challenge_method=S256
64
64
  Successfully logged in."
65
65
  `);
66
66
  expect(readAuthConfigFile()).toEqual<UserAuthConfig>({
@@ -160,7 +160,7 @@ describe("getUserInfo()", () => {
160
160
  await getUserInfo();
161
161
 
162
162
  expect(std.warn).toMatchInlineSnapshot(`
163
- "▲ [WARNING] It looks like you have used Wrangler 1's \`config\` command to login with an API token.
163
+ "▲ [WARNING] It looks like you have used Wrangler v1's \`config\` command to login with an API token.
164
164
 
165
165
  This is no longer supported in the current version of Wrangler.
166
166
  If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\`
@@ -17,7 +17,7 @@ describe("dispatch-namespace", () => {
17
17
  mockAccountId();
18
18
  mockApiToken();
19
19
 
20
- it("should should display a list of available subcommands, for dispatch-namespace with no subcommand", async () => {
20
+ it("should display a list of available subcommands, for dispatch-namespace with no subcommand", async () => {
21
21
  await runWrangler("dispatch-namespace");
22
22
 
23
23
  // wait a tick for the help menu to be printed
@@ -39,10 +39,11 @@ describe("dispatch-namespace", () => {
39
39
  wrangler dispatch-namespace rename <old-name> <new-name> Rename a dispatch namespace
40
40
 
41
41
  Flags:
42
- -c, --config Path to .toml configuration file [string]
43
- -e, --env Environment to use for operations and .env files [string]
44
- -h, --help Show help [boolean]
45
- -v, --version Show version number [boolean]",
42
+ -j, --experimental-json-config Experimental: Support wrangler.json [boolean]
43
+ -c, --config Path to .toml configuration file [string]
44
+ -e, --env Environment to use for operations and .env files [string]
45
+ -h, --help Show help [boolean]
46
+ -v, --version Show version number [boolean]",
46
47
  "warn": "",
47
48
  }
48
49
  `);
@@ -92,10 +93,11 @@ describe("dispatch-namespace", () => {
92
93
  name Name of the dispatch namespace [string] [required]
93
94
 
94
95
  Flags:
95
- -c, --config Path to .toml configuration file [string]
96
- -e, --env Environment to use for operations and .env files [string]
97
- -h, --help Show help [boolean]
98
- -v, --version Show version number [boolean]"
96
+ -j, --experimental-json-config Experimental: Support wrangler.json [boolean]
97
+ -c, --config Path to .toml configuration file [string]
98
+ -e, --env Environment to use for operations and .env files [string]
99
+ -h, --help Show help [boolean]
100
+ -v, --version Show version number [boolean]"
99
101
  `);
100
102
  });
101
103
 
@@ -141,10 +143,11 @@ describe("dispatch-namespace", () => {
141
143
  name Name of the dispatch namespace [string] [required]
142
144
 
143
145
  Flags:
144
- -c, --config Path to .toml configuration file [string]
145
- -e, --env Environment to use for operations and .env files [string]
146
- -h, --help Show help [boolean]
147
- -v, --version Show version number [boolean]"
146
+ -j, --experimental-json-config Experimental: Support wrangler.json [boolean]
147
+ -c, --config Path to .toml configuration file [string]
148
+ -e, --env Environment to use for operations and .env files [string]
149
+ -h, --help Show help [boolean]
150
+ -v, --version Show version number [boolean]"
148
151
  `);
149
152
  });
150
153
 
@@ -201,10 +204,11 @@ describe("dispatch-namespace", () => {
201
204
  name Name of the dispatch namespace [string] [required]
202
205
 
203
206
  Flags:
204
- -c, --config Path to .toml configuration file [string]
205
- -e, --env Environment to use for operations and .env files [string]
206
- -h, --help Show help [boolean]
207
- -v, --version Show version number [boolean]"
207
+ -j, --experimental-json-config Experimental: Support wrangler.json [boolean]
208
+ -c, --config Path to .toml configuration file [string]
209
+ -e, --env Environment to use for operations and .env files [string]
210
+ -h, --help Show help [boolean]
211
+ -v, --version Show version number [boolean]"
208
212
  `);
209
213
  });
210
214
 
@@ -313,10 +317,11 @@ describe("dispatch-namespace", () => {
313
317
  new-name New name of the dispatch namespace [string] [required]
314
318
 
315
319
  Flags:
316
- -c, --config Path to .toml configuration file [string]
317
- -e, --env Environment to use for operations and .env files [string]
318
- -h, --help Show help [boolean]
319
- -v, --version Show version number [boolean]"
320
+ -j, --experimental-json-config Experimental: Support wrangler.json [boolean]
321
+ -c, --config Path to .toml configuration file [string]
322
+ -e, --env Environment to use for operations and .env files [string]
323
+ -h, --help Show help [boolean]
324
+ -v, --version Show version number [boolean]"
320
325
  `);
321
326
  });
322
327
 
package/src/api/dev.ts CHANGED
@@ -100,7 +100,6 @@ export async function unstable_dev(
100
100
  showInteractiveDevSession,
101
101
  testMode,
102
102
  testScheduled,
103
- watch,
104
103
  // 2. options for alpha/beta products/libs
105
104
  d1Databases,
106
105
  experimentalLocal,
@@ -139,20 +138,54 @@ export async function unstable_dev(
139
138
  local: true,
140
139
  d1Databases,
141
140
  disableDevRegistry,
142
- testScheduled,
143
- experimentalLocal,
144
- experimentalLocalRemoteKv,
141
+ testScheduled: testScheduled ?? false,
142
+ experimentalLocal: experimentalLocal ?? false,
143
+ experimentalLocalRemoteKv: experimentalLocalRemoteKv ?? false,
145
144
  enablePagesAssetsServiceBinding,
146
145
  liveReload,
147
146
  showInteractiveDevSession,
148
147
  forceLocal,
149
- watch,
150
- ...options,
151
148
  onReady: (address, port) => {
152
149
  readyPort = port;
153
150
  readyAddress = address;
154
151
  ready(devServer);
155
152
  },
153
+ config: options?.config,
154
+ env: options?.env,
155
+ bundle: options?.bundle,
156
+ compatibilityDate: options?.compatibilityDate,
157
+ compatibilityFlags: options?.compatibilityFlags,
158
+ ip: options?.ip,
159
+ inspectorPort: options?.inspectorPort,
160
+ v: undefined,
161
+ localProtocol: options?.localProtocol,
162
+ assets: options?.assets,
163
+ site: options?.site, // Root folder of static assets for Workers Sites
164
+ siteInclude: options?.siteInclude, // Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.
165
+ siteExclude: options?.siteExclude, // Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.
166
+ nodeCompat: options?.nodeCompat, // Enable node.js compatibility
167
+ persist: options?.persist, // Enable persistence for local mode, using default path: .wrangler/state
168
+ persistTo: options?.persistTo, // Specify directory to use for local persistence (implies --persist)
169
+ experimentalJsonConfig: undefined,
170
+ name: undefined,
171
+ noBundle: false,
172
+ format: undefined,
173
+ latest: false,
174
+ routes: undefined,
175
+ host: undefined,
176
+ localUpstream: undefined,
177
+ experimentalPublic: undefined,
178
+ upstreamProtocol: undefined,
179
+ var: undefined,
180
+ define: undefined,
181
+ jsxFactory: undefined,
182
+ jsxFragment: undefined,
183
+ tsconfig: undefined,
184
+ minify: undefined,
185
+ experimentalEnableLocalPersistence: undefined,
186
+ legacyEnv: undefined,
187
+ public: undefined,
188
+ ...options,
156
189
  });
157
190
  }).then((devServer) => {
158
191
  // now that the inner promise has resolved, we can resolve the outer promise
@@ -190,22 +223,58 @@ export async function unstable_dev(
190
223
  inspect: false,
191
224
  _: [],
192
225
  $0: "",
226
+ logLevel: options?.logLevel ?? "log",
227
+ port: options?.port ?? 0,
193
228
  local: true,
194
229
  showInteractiveDevSession,
195
230
  d1Databases,
196
231
  disableDevRegistry,
197
- testScheduled,
198
- experimentalLocal,
199
- experimentalLocalRemoteKv,
232
+ testScheduled: testScheduled ?? false,
233
+ experimentalLocal: experimentalLocal ?? false,
234
+ experimentalLocalRemoteKv: experimentalLocalRemoteKv ?? false,
200
235
  enablePagesAssetsServiceBinding,
201
236
  liveReload,
202
- watch,
203
- ...options,
204
237
  onReady: (address, port) => {
205
238
  readyPort = port;
206
239
  readyAddress = address;
207
240
  ready(devServer);
208
241
  },
242
+ config: options?.config,
243
+ env: options?.env,
244
+ bundle: options?.bundle,
245
+ compatibilityDate: options?.compatibilityDate,
246
+ compatibilityFlags: options?.compatibilityFlags,
247
+ ip: options?.ip,
248
+ inspectorPort: options?.inspectorPort,
249
+ v: undefined,
250
+ localProtocol: options?.localProtocol,
251
+ assets: options?.assets,
252
+ site: options?.site, // Root folder of static assets for Workers Sites
253
+ siteInclude: options?.siteInclude, // Array of .gitignore-style patterns that match file or directory names from the sites directory. Only matched items will be uploaded.
254
+ siteExclude: options?.siteExclude, // Array of .gitignore-style patterns that match file or directory names from the sites directory. Matched items will not be uploaded.
255
+ nodeCompat: options?.nodeCompat, // Enable node.js compatibility
256
+ persist: options?.persist, // Enable persistence for local mode, using default path: .wrangler/state
257
+ persistTo: options?.persistTo, // Specify directory to use for local persistence (implies --persist)
258
+ experimentalJsonConfig: undefined,
259
+ name: undefined,
260
+ noBundle: false,
261
+ format: undefined,
262
+ latest: false,
263
+ routes: undefined,
264
+ host: undefined,
265
+ localUpstream: undefined,
266
+ experimentalPublic: undefined,
267
+ upstreamProtocol: undefined,
268
+ var: undefined,
269
+ define: undefined,
270
+ jsxFactory: undefined,
271
+ jsxFragment: undefined,
272
+ tsconfig: undefined,
273
+ minify: undefined,
274
+ experimentalEnableLocalPersistence: undefined,
275
+ legacyEnv: undefined,
276
+ public: undefined,
277
+ ...options,
209
278
  });
210
279
  }).then((devServer) => {
211
280
  resolve({
package/src/api/index.ts CHANGED
@@ -1,3 +1,11 @@
1
1
  export { unstable_dev } from "./dev";
2
2
  export type { UnstableDevWorker, UnstableDevOptions } from "./dev";
3
3
  export { unstable_pages } from "./pages";
4
+ export {
5
+ uploadMTlsCertificate,
6
+ uploadMTlsCertificateFromFs,
7
+ listMTlsCertificates,
8
+ getMTlsCertificate,
9
+ getMTlsCertificateByName,
10
+ deleteMTlsCertificate,
11
+ } from "./mtls-certificate";
@@ -0,0 +1,148 @@
1
+ import { fetchResult } from "../cfetch";
2
+ import { readFileSync } from "../parse";
3
+
4
+ /**
5
+ * the representation of an mTLS certificate in the account certificate store
6
+ */
7
+ export interface MTlsCertificateResponse {
8
+ id: string;
9
+ name?: string;
10
+ ca: boolean;
11
+ certificates: string;
12
+ expires_on: string;
13
+ issuer: string;
14
+ serial_number: string;
15
+ signature: string;
16
+ uploaded_on: string;
17
+ }
18
+
19
+ /**
20
+ * details for uploading an mTLS certificate from disk
21
+ */
22
+ export interface MTlsCertificateUploadDetails {
23
+ certificateChainFilename: string;
24
+ privateKeyFilename: string;
25
+ name?: string;
26
+ }
27
+
28
+ /**
29
+ * details for uploading an mTLS certificate via the ssl api
30
+ */
31
+ export interface MTlsCertificateBody {
32
+ certificateChain: string;
33
+ privateKey: string;
34
+ name?: string;
35
+ }
36
+
37
+ /**
38
+ * supported filters for listing mTLS certificates via the ssl api
39
+ */
40
+ export interface MTlsCertificateListFilter {
41
+ name?: string;
42
+ }
43
+
44
+ /**
45
+ * indicates that looking up a certificate by name failed due to zero matching results
46
+ */
47
+ export class ErrorMTlsCertificateNameNotFound extends Error {}
48
+
49
+ /**
50
+ * indicates that looking up a certificate by name failed due to more than one matching results
51
+ */
52
+ export class ErrorMTlsCertificateManyNamesMatch extends Error {}
53
+
54
+ /**
55
+ * reads an mTLS certificate and private key pair from disk and uploads it to the account mTLS certificate store
56
+ */
57
+ export async function uploadMTlsCertificateFromFs(
58
+ accountId: string,
59
+ details: MTlsCertificateUploadDetails
60
+ ): Promise<MTlsCertificateResponse> {
61
+ return await uploadMTlsCertificate(accountId, {
62
+ certificateChain: readFileSync(details.certificateChainFilename),
63
+ privateKey: readFileSync(details.privateKeyFilename),
64
+ name: details.name,
65
+ });
66
+ }
67
+
68
+ /**
69
+ * uploads an mTLS certificate and private key pair to the account mTLS certificate store
70
+ */
71
+ export async function uploadMTlsCertificate(
72
+ accountId: string,
73
+ body: MTlsCertificateBody
74
+ ): Promise<MTlsCertificateResponse> {
75
+ return await fetchResult(`/accounts/${accountId}/mtls_certificates`, {
76
+ method: "POST",
77
+ body: JSON.stringify({
78
+ name: body.name,
79
+ certificates: body.certificateChain,
80
+ private_key: body.privateKey,
81
+ ca: false,
82
+ }),
83
+ });
84
+ }
85
+
86
+ /**
87
+ * fetches an mTLS certificate from the account mTLS certificate store by ID
88
+ */
89
+ export async function getMTlsCertificate(
90
+ accountId: string,
91
+ id: string
92
+ ): Promise<MTlsCertificateResponse> {
93
+ return await fetchResult(
94
+ `/accounts/${accountId}/mtls_certificates/${id}`,
95
+ {}
96
+ );
97
+ }
98
+
99
+ /**
100
+ * lists mTLS certificates for an account. filtering by name is supported
101
+ */
102
+ export async function listMTlsCertificates(
103
+ accountId: string,
104
+ filter: MTlsCertificateListFilter
105
+ ): Promise<MTlsCertificateResponse[]> {
106
+ const params = new URLSearchParams();
107
+ params.append("ca", "false");
108
+ if (filter.name) {
109
+ params.append("name", filter.name);
110
+ }
111
+ return await fetchResult(
112
+ `/accounts/${accountId}/mtls_certificates`,
113
+ {},
114
+ params
115
+ );
116
+ }
117
+
118
+ /**
119
+ * fetches an mTLS certificate from the account mTLS certificate store by name. will throw an error if no certificates are found, or multiple are found with that name
120
+ */
121
+ export async function getMTlsCertificateByName(
122
+ accountId: string,
123
+ name: string
124
+ ): Promise<MTlsCertificateResponse> {
125
+ const certificates = await listMTlsCertificates(accountId, { name });
126
+ if (certificates.length === 0) {
127
+ throw new ErrorMTlsCertificateNameNotFound(
128
+ `certificate not found with name "${name}"`
129
+ );
130
+ }
131
+ if (certificates.length > 1) {
132
+ throw new ErrorMTlsCertificateManyNamesMatch(
133
+ `multiple certificates found with name "${name}"`
134
+ );
135
+ }
136
+ const certificate = certificates[0];
137
+ return certificate;
138
+ }
139
+
140
+ export async function deleteMTlsCertificate(
141
+ accountId: string,
142
+ certificateId: string
143
+ ) {
144
+ return await fetchResult(
145
+ `/accounts/${accountId}/mtls_certificates/${certificateId}`,
146
+ { method: "DELETE" }
147
+ );
148
+ }
@@ -0,0 +1,75 @@
1
+ import { readFileSync } from "node:fs";
2
+ import path from "node:path";
3
+ import { Response } from "undici";
4
+ import { createWorkerUploadForm } from "../../create-worker-upload-form";
5
+ import type { BundleResult } from "../../bundle";
6
+ import type { CfWorkerInit } from "../../worker";
7
+ import type { Blob } from "node:buffer";
8
+ import type { FormData } from "undici";
9
+
10
+ /**
11
+ * Takes a Worker bundle - `BundleResult` - and generates the _worker.bundle
12
+ * contents
13
+ */
14
+ export async function createUploadWorkerBundleContents(
15
+ workerBundle: BundleResult
16
+ ): Promise<Blob> {
17
+ const workerBundleFormData = createWorkerBundleFormData(workerBundle);
18
+ const metadata = JSON.parse(workerBundleFormData.get("metadata") as string);
19
+
20
+ /**
21
+ * Pages doesn't need the metadata bindings returned by
22
+ * `createWorkerBundleFormData`. Let's strip them out and return only
23
+ * the contents we need
24
+ */
25
+ workerBundleFormData.set(
26
+ "metadata",
27
+ JSON.stringify({ main_module: metadata.main_module })
28
+ );
29
+
30
+ return await new Response(workerBundleFormData).blob();
31
+ }
32
+
33
+ /**
34
+ * Creates a `FormData` upload from a `BundleResult`
35
+ */
36
+ function createWorkerBundleFormData(workerBundle: BundleResult): FormData {
37
+ const mainModule = {
38
+ name: path.basename(workerBundle.resolvedEntryPointPath),
39
+ content: readFileSync(workerBundle.resolvedEntryPointPath, {
40
+ encoding: "utf-8",
41
+ }),
42
+ type: workerBundle.bundleType || "esm",
43
+ };
44
+
45
+ const worker: CfWorkerInit = {
46
+ name: mainModule.name,
47
+ main: mainModule,
48
+ modules: workerBundle.modules,
49
+ bindings: {
50
+ vars: undefined,
51
+ kv_namespaces: undefined,
52
+ wasm_modules: undefined,
53
+ text_blobs: undefined,
54
+ data_blobs: undefined,
55
+ durable_objects: undefined,
56
+ queues: undefined,
57
+ r2_buckets: undefined,
58
+ d1_databases: undefined,
59
+ services: undefined,
60
+ analytics_engine_datasets: undefined,
61
+ dispatch_namespaces: undefined,
62
+ mtls_certificates: undefined,
63
+ logfwdr: undefined,
64
+ unsafe: undefined,
65
+ },
66
+ migrations: undefined,
67
+ compatibility_date: undefined,
68
+ compatibility_flags: undefined,
69
+ usage_model: undefined,
70
+ keepVars: undefined,
71
+ logpush: undefined,
72
+ };
73
+
74
+ return createWorkerUploadForm(worker);
75
+ }
@@ -17,6 +17,8 @@ import {
17
17
  } from "../../pages/functions/buildWorker";
18
18
  import { validateRoutes } from "../../pages/functions/routes-validation";
19
19
  import { upload } from "../../pages/upload";
20
+ import { createUploadWorkerBundleContents } from "./create-worker-bundle-contents";
21
+ import type { BundleResult } from "../../bundle";
20
22
  import type { Project, Deployment } from "@cloudflare/types";
21
23
 
22
24
  interface PagesPublishOptions {
@@ -67,6 +69,14 @@ interface PagesPublishOptions {
67
69
  */
68
70
  bundle?: boolean;
69
71
 
72
+ /**
73
+ * Whether to process non-JS module imports or not, such as
74
+ * wasm/text/binary, when we run bundling on `functions` or
75
+ * `_worker.js`
76
+ * Default: false
77
+ */
78
+ experimentalWorkerBundle?: boolean;
79
+
70
80
  // TODO: Allow passing in the API key and plumb it through
71
81
  // to the API calls so that the publish function does not
72
82
  // rely on the `CLOUDFLARE_API_KEY` environment variable
@@ -88,6 +98,7 @@ export async function publish({
88
98
  commitDirty,
89
99
  functionsDirectory: customFunctionsDirectory,
90
100
  bundle,
101
+ experimentalWorkerBundle,
91
102
  }: PagesPublishOptions) {
92
103
  let _headers: string | undefined,
93
104
  _redirects: string | undefined,
@@ -132,6 +143,8 @@ export async function publish({
132
143
  * Functions first and exit if it failed
133
144
  */
134
145
  let builtFunctions: string | undefined = undefined;
146
+ let workerBundle: BundleResult | undefined = undefined;
147
+
135
148
  const functionsDirectory =
136
149
  customFunctionsDirectory || join(cwd(), "functions");
137
150
  const routesOutputPath = !existsSync(join(directory, "_routes.json"))
@@ -141,6 +154,11 @@ export async function publish({
141
154
  // Routing configuration displayed in the Functions tab of a deployment in Dash
142
155
  let filepathRoutingConfig: string | undefined;
143
156
 
157
+ const d1Databases = Object.keys(
158
+ project.deployment_configs[isProduction ? "production" : "preview"]
159
+ .d1_databases ?? {}
160
+ );
161
+
144
162
  if (!_workerJS && existsSync(functionsDirectory)) {
145
163
  const outfile = join(tmpdir(), `./functionsWorker-${Math.random()}.js`);
146
164
  const outputConfigPath = join(
@@ -149,7 +167,7 @@ export async function publish({
149
167
  );
150
168
 
151
169
  try {
152
- await buildFunctions({
170
+ workerBundle = await buildFunctions({
153
171
  outfile,
154
172
  outputConfigPath,
155
173
  functionsDirectory,
@@ -157,10 +175,8 @@ export async function publish({
157
175
  buildOutputDirectory: dirname(outfile),
158
176
  routesOutputPath,
159
177
  local: false,
160
- d1Databases: Object.keys(
161
- project.deployment_configs[isProduction ? "production" : "preview"]
162
- .d1_databases ?? {}
163
- ),
178
+ d1Databases,
179
+ experimentalWorkerBundle,
164
180
  });
165
181
 
166
182
  builtFunctions = readFileSync(outfile, "utf-8");
@@ -232,9 +248,11 @@ export async function publish({
232
248
  */
233
249
  if (_workerJS) {
234
250
  let workerFileContents = _workerJS;
235
- if (bundle) {
251
+ const enableBundling = bundle || experimentalWorkerBundle;
252
+
253
+ if (enableBundling) {
236
254
  const outfile = join(tmpdir(), `./bundledWorker-${Math.random()}.mjs`);
237
- await buildRawWorker({
255
+ workerBundle = await buildRawWorker({
238
256
  workerScriptPath,
239
257
  outfile,
240
258
  directory: directory ?? ".",
@@ -242,14 +260,31 @@ export async function publish({
242
260
  sourcemap: true,
243
261
  watch: false,
244
262
  onEnd: () => {},
263
+ betaD1Shims: d1Databases,
264
+ experimentalWorkerBundle,
245
265
  });
246
266
  workerFileContents = readFileSync(outfile, "utf8");
247
267
  } else {
248
268
  await checkRawWorker(workerScriptPath, () => {});
249
269
  }
250
270
 
251
- formData.append("_worker.js", new File([workerFileContents], "_worker.js"));
252
- logger.log(`✨ Uploading _worker.js`);
271
+ if (experimentalWorkerBundle) {
272
+ const workerBundleContents = await createUploadWorkerBundleContents(
273
+ workerBundle as BundleResult
274
+ );
275
+
276
+ formData.append(
277
+ "_worker.bundle",
278
+ new File([workerBundleContents], "_worker.bundle")
279
+ );
280
+ logger.log(`✨ Uploading Worker bundle`);
281
+ } else {
282
+ formData.append(
283
+ "_worker.js",
284
+ new File([workerFileContents], "_worker.js")
285
+ );
286
+ logger.log(`✨ Uploading _worker.js`);
287
+ }
253
288
 
254
289
  if (_routesCustom) {
255
290
  // user provided a custom _routes.json file
@@ -275,9 +310,21 @@ export async function publish({
275
310
  * https://developers.cloudflare.com/pages/platform/functions/
276
311
  */
277
312
  if (builtFunctions && !_workerJS) {
278
- // if Functions were build successfully, proceed to uploading the build file
279
- formData.append("_worker.js", new File([builtFunctions], "_worker.js"));
280
- logger.log(`✨ Uploading Functions`);
313
+ if (experimentalWorkerBundle) {
314
+ const workerBundleContents = await createUploadWorkerBundleContents(
315
+ workerBundle as BundleResult
316
+ );
317
+
318
+ formData.append(
319
+ "_worker.bundle",
320
+ new File([workerBundleContents], "_worker.bundle")
321
+ );
322
+ logger.log(`✨ Uploading Functions bundle`);
323
+ } else {
324
+ // if Functions were build successfully, proceed to uploading the build file
325
+ formData.append("_worker.js", new File([builtFunctions], "_worker.js"));
326
+ logger.log(`✨ Uploading Functions`);
327
+ }
281
328
 
282
329
  if (_routesCustom) {
283
330
  // user provided a custom _routes.json file
package/src/bundle.ts CHANGED
@@ -116,7 +116,7 @@ export async function bundleWorker(
116
116
  loader?: Record<string, string>;
117
117
  sourcemap?: esbuild.CommonOptions["sourcemap"];
118
118
  plugins?: esbuild.Plugin[];
119
- // TODO: Rip these out https://github.com/cloudflare/wrangler2/issues/2153
119
+ // TODO: Rip these out https://github.com/cloudflare/workers-sdk/issues/2153
120
120
  disableModuleCollection?: boolean;
121
121
  isOutfile?: boolean;
122
122
  }
@@ -333,18 +333,19 @@ export async function bundleWorker(
333
333
  inject,
334
334
  external: ["__STATIC_CONTENT_MANIFEST"],
335
335
  format: entry.format === "modules" ? "esm" : "iife",
336
- target: "es2020",
336
+ // Our workerd runtime uses the same V8 version as recent Chrome, which is highly ES2022 compliant: https://kangax.github.io/compat-table/es2016plus/
337
+ target: "es2022",
337
338
  sourcemap: sourcemap ?? true, // this needs to use ?? to accept false
338
339
  // Include a reference to the output folder in the sourcemap.
339
340
  // This is omitted by default, but we need it to properly resolve source paths in error output.
340
341
  sourceRoot: destination,
341
342
  minify,
342
343
  metafile: true,
343
- conditions: ["worker", "browser"],
344
+ conditions: ["workerd", "worker", "browser"],
344
345
  ...(process.env.NODE_ENV && {
345
346
  define: {
346
347
  // use process.env["NODE_ENV" + ""] so that esbuild doesn't replace it
347
- // when we do a build of wrangler. (re: https://github.com/cloudflare/wrangler2/issues/1477)
348
+ // when we do a build of wrangler. (re: https://github.com/cloudflare/workers-sdk/issues/1477)
348
349
  "process.env.NODE_ENV": `"${process.env["NODE_ENV" + ""]}"`,
349
350
  ...(nodeCompat ? { global: "globalThis" } : {}),
350
351
  ...(checkFetch ? { fetch: "checkedFetch" } : {}),
@@ -574,9 +575,10 @@ async function applyMiddlewareLoaderFacade(
574
575
  ],
575
576
  outfile: targetPathInsertion,
576
577
  });
577
-
578
- let targetPathLoader = path.join(tmpDirPath, path.basename(entry.file));
579
- if (path.extname(entry.file) === "") targetPathLoader += ".js";
578
+ const targetPathLoader = path.join(
579
+ tmpDirPath,
580
+ "middleware-loader.entry.js"
581
+ );
580
582
  const loaderPath = path.resolve(
581
583
  getBasePath(),
582
584
  "templates/middleware/loader-modules.ts"