wrangler 0.0.0-e22f9d7 → 0.0.0-e2472f152

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 (121) hide show
  1. package/README.md +49 -26
  2. package/bin/wrangler.js +88 -31
  3. package/config-schema.json +2290 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +146 -89
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +170 -0
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +15 -0
  30. package/templates/new-worker.ts +33 -0
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +33 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +22 -0
  41. package/templates/tsconfig.json +15 -0
  42. package/templates/tsconfig.tsbuildinfo +1 -0
  43. package/wrangler-dist/InspectorProxyWorker.js +460 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +238 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +26699 -0
  48. package/wrangler-dist/cli.js +147915 -118486
  49. package/import_meta_url.js +0 -3
  50. package/miniflare-config-stubs/.env.empty +0 -0
  51. package/miniflare-config-stubs/package.empty.json +0 -1
  52. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  53. package/pages/functions/buildWorker.ts +0 -62
  54. package/pages/functions/filepath-routing.test.ts +0 -39
  55. package/pages/functions/filepath-routing.ts +0 -221
  56. package/pages/functions/identifiers.ts +0 -78
  57. package/pages/functions/routes.ts +0 -158
  58. package/pages/functions/template-worker.ts +0 -144
  59. package/src/__tests__/clipboardy-mock.js +0 -4
  60. package/src/__tests__/dev.test.tsx +0 -67
  61. package/src/__tests__/index.test.ts +0 -287
  62. package/src/__tests__/jest.setup.ts +0 -22
  63. package/src/__tests__/kv.test.ts +0 -1111
  64. package/src/__tests__/mock-cfetch.ts +0 -171
  65. package/src/__tests__/mock-dialogs.ts +0 -65
  66. package/src/__tests__/run-in-tmp.ts +0 -19
  67. package/src/__tests__/run-wrangler.ts +0 -32
  68. package/src/api/form_data.ts +0 -131
  69. package/src/api/preview.ts +0 -128
  70. package/src/api/worker.ts +0 -155
  71. package/src/cfetch/index.ts +0 -102
  72. package/src/cfetch/internal.ts +0 -69
  73. package/src/cli.ts +0 -9
  74. package/src/config.ts +0 -487
  75. package/src/dev.tsx +0 -784
  76. package/src/dialogs.tsx +0 -77
  77. package/src/index.tsx +0 -1974
  78. package/src/inspect.ts +0 -539
  79. package/src/kv.tsx +0 -276
  80. package/src/module-collection.ts +0 -64
  81. package/src/pages.tsx +0 -1031
  82. package/src/proxy.ts +0 -302
  83. package/src/publish.ts +0 -364
  84. package/src/sites.tsx +0 -118
  85. package/src/tail.tsx +0 -73
  86. package/src/user.tsx +0 -1027
  87. package/static-asset-facade.js +0 -47
  88. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  89. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  90. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  91. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  92. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  93. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  94. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  95. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  96. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  97. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  98. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  99. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  100. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  101. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  102. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  103. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  104. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  105. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  106. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  107. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  108. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  109. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  110. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  111. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  112. package/vendor/wrangler-mime/LICENSE +0 -21
  113. package/vendor/wrangler-mime/Mime.js +0 -97
  114. package/vendor/wrangler-mime/README.md +0 -187
  115. package/vendor/wrangler-mime/cli.js +0 -46
  116. package/vendor/wrangler-mime/index.js +0 -4
  117. package/vendor/wrangler-mime/lite.js +0 -4
  118. package/vendor/wrangler-mime/package.json +0 -52
  119. package/vendor/wrangler-mime/types/other.js +0 -1
  120. package/vendor/wrangler-mime/types/standard.js +0 -1
  121. package/wrangler-dist/cli.js.map +0 -7
package/src/proxy.ts DELETED
@@ -1,302 +0,0 @@
1
- import { connect } from "node:http2";
2
- import type { ClientHttp2Session, ServerHttp2Stream } from "node:http2";
3
- import { createServer } from "node:http";
4
- import type {
5
- IncomingHttpHeaders,
6
- RequestListener,
7
- IncomingMessage,
8
- ServerResponse,
9
- Server,
10
- } from "node:http";
11
- import WebSocket from "faye-websocket";
12
- import serveStatic from "serve-static";
13
- import type { CfPreviewToken } from "./api/preview";
14
- import { useEffect, useRef } from "react";
15
-
16
- /**
17
- * `usePreviewServer` is a React hook that creates a local development
18
- * server that can be used to develop a Worker.
19
- *
20
- * When we run `wrangler dev`, we start by uploading the compiled worker
21
- * to the preview service, which responds with a preview token.
22
- * (see `useWorker`/`createWorker` for details.)
23
- * We can then use that token to connect to the preview server for a
24
- * great local development experience. Further, as we change the worker,
25
- * we can update the preview token transparently without having to restart
26
- * the development server.
27
- */
28
-
29
- /** Rewrite request headers to add the preview token. */
30
- function addCfPreviewTokenHeader(
31
- headers: IncomingHttpHeaders,
32
- previewTokenValue: string
33
- ) {
34
- headers["cf-workers-preview-token"] = previewTokenValue;
35
- }
36
-
37
- /**
38
- * Rewrite references in request headers
39
- * from the preview host to the local host.
40
- */
41
- function rewriteRemoteHostToLocalHostInHeaders(
42
- headers: IncomingHttpHeaders,
43
- remoteHost: string,
44
- localPort: number
45
- ) {
46
- for (const [name, value] of Object.entries(headers)) {
47
- // Rewrite the remote host to the local host.
48
- if (typeof value === "string" && value.includes(remoteHost)) {
49
- headers[name] = value
50
- .replaceAll(`https://${remoteHost}`, `http://localhost:${localPort}`)
51
- .replaceAll(remoteHost, `localhost:${localPort}`);
52
- }
53
- }
54
- }
55
-
56
- export function usePreviewServer({
57
- previewToken,
58
- publicRoot,
59
- port,
60
- }: {
61
- previewToken: CfPreviewToken | undefined;
62
- publicRoot: undefined | string;
63
- port: number;
64
- }) {
65
- /** Creates an HTTP/1 proxy that sends requests over HTTP/2. */
66
- const proxyServer = useRef<Server>();
67
- const proxy = (proxyServer.current ??= createProxyServer());
68
-
69
- /**
70
- * When we're not connected / getting a fresh token on changes,
71
- * we'd like to buffer streams/requests until we're connected.
72
- * Once connected, we can flush the buffered streams/requests.
73
- * streamBufferRef is used to buffer http/2 streams, while
74
- * requestResponseBufferRef is used to buffer http/1 requests.
75
- */
76
- const streamBufferRef = useRef<
77
- { stream: ServerHttp2Stream; headers: IncomingHttpHeaders }[]
78
- >([]);
79
- const requestResponseBufferRef = useRef<
80
- { request: IncomingMessage; response: ServerResponse }[]
81
- >([]);
82
-
83
- useEffect(() => {
84
- // If we don't have a token, that means either we're just starting up,
85
- // or we're refreshing the token.
86
- if (!previewToken) {
87
- const cleanupListeners: (() => void)[] = [];
88
- const bufferStream = (
89
- stream: ServerHttp2Stream,
90
- headers: IncomingHttpHeaders
91
- ) => {
92
- // store the stream in a buffer so we can replay it later
93
- streamBufferRef.current.push({ stream, headers });
94
- };
95
- proxy.on("stream", bufferStream);
96
- cleanupListeners.push(() => proxy.off("stream", bufferStream));
97
-
98
- const bufferRequestResponse = (
99
- request: IncomingMessage,
100
- response: ServerResponse
101
- ) => {
102
- // store the request and response in a buffer so we can replay it later
103
- requestResponseBufferRef.current.push({ request, response });
104
- };
105
-
106
- proxy.on("request", bufferRequestResponse);
107
- cleanupListeners.push(() => proxy.off("request", bufferRequestResponse));
108
- return () => {
109
- cleanupListeners.forEach((cleanup) => cleanup());
110
- };
111
- }
112
-
113
- // We have a token. Let's proxy requests to the preview end point.
114
- const cleanupListeners: (() => void)[] = [];
115
-
116
- const assetPath = typeof publicRoot === "string" ? publicRoot : null;
117
-
118
- // create a ClientHttp2Session
119
- const remote = connect(`https://${previewToken.host}`);
120
- cleanupListeners.push(() => remote.destroy());
121
-
122
- /** HTTP/2 -> HTTP/2 */
123
- const handleStream = createStreamHandler(previewToken, remote, port);
124
- proxy.on("stream", handleStream);
125
- cleanupListeners.push(() => proxy.off("stream", handleStream));
126
-
127
- // flush and replay buffered streams
128
- streamBufferRef.current.forEach((buffer) =>
129
- handleStream(buffer.stream, buffer.headers)
130
- );
131
- streamBufferRef.current = [];
132
-
133
- /** HTTP/1 -> HTTP/2 */
134
- const handleRequest: RequestListener = (
135
- message: IncomingMessage,
136
- response: ServerResponse
137
- ) => {
138
- const { httpVersionMajor, headers, method, url } = message;
139
- if (httpVersionMajor >= 2) {
140
- return; // Already handled by the "stream" event.
141
- }
142
- addCfPreviewTokenHeader(headers, previewToken.value);
143
- headers[":method"] = method;
144
- headers[":path"] = url;
145
- headers[":authority"] = previewToken.host;
146
- headers[":scheme"] = "https";
147
- for (const name of Object.keys(headers)) {
148
- if (HTTP1_HEADERS.has(name.toLowerCase())) {
149
- delete headers[name];
150
- }
151
- }
152
- const request = message.pipe(remote.request(headers));
153
- request.on("response", (responseHeaders) => {
154
- const status = responseHeaders[":status"] ?? 500;
155
- rewriteRemoteHostToLocalHostInHeaders(
156
- responseHeaders,
157
- previewToken.host,
158
- port
159
- );
160
- for (const name of Object.keys(responseHeaders)) {
161
- if (name.startsWith(":")) {
162
- delete responseHeaders[name];
163
- }
164
- }
165
- response.writeHead(status, responseHeaders);
166
- request.pipe(response, { end: true });
167
- });
168
- };
169
-
170
- // If an asset path is defined, check the file system
171
- // for a file first and serve if it exists.
172
- const actualHandleRequest = assetPath
173
- ? createHandleAssetsRequest(assetPath, handleRequest)
174
- : handleRequest;
175
-
176
- proxy.on("request", actualHandleRequest);
177
- cleanupListeners.push(() => proxy.off("request", actualHandleRequest));
178
-
179
- // flush and replay buffered requests
180
- requestResponseBufferRef.current.forEach(({ request, response }) =>
181
- actualHandleRequest(request, response)
182
- );
183
- requestResponseBufferRef.current = [];
184
-
185
- /** HTTP/1 -> WebSocket (over HTTP/1) */
186
- const handleUpgrade = (
187
- message: IncomingMessage,
188
- socket: WebSocket,
189
- body: Buffer
190
- ) => {
191
- const { headers, url } = message;
192
- addCfPreviewTokenHeader(headers, previewToken.value);
193
- headers["host"] = previewToken.host;
194
- const localWebsocket = new WebSocket(message, socket, body);
195
- // TODO(soon): Custom WebSocket protocol is not working?
196
- const remoteWebsocketClient = new WebSocket.Client(
197
- `wss://${previewToken.host}${url}`,
198
- [],
199
- { headers }
200
- );
201
- localWebsocket.pipe(remoteWebsocketClient).pipe(localWebsocket);
202
- // We close down websockets whenever we refresh the token.
203
- cleanupListeners.push(() => {
204
- localWebsocket.destroy();
205
- remoteWebsocketClient.destroy();
206
- });
207
- };
208
- proxy.on("upgrade", handleUpgrade);
209
- cleanupListeners.push(() => proxy.off("upgrade", handleUpgrade));
210
-
211
- return () => {
212
- cleanupListeners.forEach((d) => d());
213
- };
214
- }, [previewToken, publicRoot, port, proxy]);
215
-
216
- // Start/stop the server whenever the
217
- // containing component is mounted/unmounted.
218
- useEffect(() => {
219
- proxy.listen(port);
220
- console.log(`⬣ Listening at http://localhost:${port}`);
221
-
222
- return () => {
223
- proxy.close();
224
- };
225
- }, [port, proxy]);
226
- }
227
-
228
- function createHandleAssetsRequest(
229
- assetPath: string,
230
- handleRequest: RequestListener
231
- ) {
232
- const handleAsset = serveStatic(assetPath, {
233
- cacheControl: false,
234
- });
235
- return (request: IncomingMessage, response: ServerResponse) => {
236
- handleAsset(request, response, () => {
237
- handleRequest(request, response);
238
- });
239
- };
240
- }
241
-
242
- /** A Set of headers we want to remove from HTTP/1 requests. */
243
- const HTTP1_HEADERS = new Set([
244
- "host",
245
- "connection",
246
- "upgrade",
247
- "keep-alive",
248
- "proxy-connection",
249
- "transfer-encoding",
250
- "http2-settings",
251
- ]);
252
-
253
- function createProxyServer() {
254
- return createServer()
255
- .on("request", function (req, res) {
256
- // log all requests
257
- console.log(
258
- new Date().toLocaleTimeString(),
259
- req.method,
260
- req.url,
261
- res.statusCode
262
- );
263
- })
264
- .on("upgrade", (req) => {
265
- // log all websocket connections
266
- console.log(
267
- new Date().toLocaleTimeString(),
268
- req.method,
269
- req.url,
270
- 101,
271
- "(WebSocket)"
272
- );
273
- })
274
- .on("error", (err) => {
275
- // log all connection errors
276
- console.error(new Date().toLocaleTimeString(), err);
277
- });
278
- }
279
-
280
- function createStreamHandler(
281
- previewToken: CfPreviewToken,
282
- remote: ClientHttp2Session,
283
- port: number
284
- ) {
285
- return function handleStream(
286
- stream: ServerHttp2Stream,
287
- headers: IncomingHttpHeaders
288
- ) {
289
- addCfPreviewTokenHeader(headers, previewToken.value);
290
- headers[":authority"] = previewToken.host;
291
- const request = stream.pipe(remote.request(headers));
292
- request.on("response", (responseHeaders: IncomingHttpHeaders) => {
293
- rewriteRemoteHostToLocalHostInHeaders(
294
- responseHeaders,
295
- previewToken.host,
296
- port
297
- );
298
- stream.respond(responseHeaders);
299
- request.pipe(stream, { end: true });
300
- });
301
- };
302
- }
package/src/publish.ts DELETED
@@ -1,364 +0,0 @@
1
- import assert from "node:assert";
2
- import path from "node:path";
3
- import { readFile } from "node:fs/promises";
4
- import esbuild from "esbuild";
5
- import { execa } from "execa";
6
- import tmp from "tmp-promise";
7
- import type { CfWorkerInit } from "./api/worker";
8
- import { toFormData } from "./api/form_data";
9
- import { fetchResult } from "./cfetch";
10
- import type { Config } from "./config";
11
- import makeModuleCollector from "./module-collection";
12
- import { syncAssets } from "./sites";
13
-
14
- type CfScriptFormat = undefined | "modules" | "service-worker";
15
-
16
- type Props = {
17
- config: Config;
18
- format?: CfScriptFormat;
19
- script?: string;
20
- name?: string;
21
- env?: string;
22
- compatibilityDate?: string;
23
- compatibilityFlags?: string[];
24
- public?: string;
25
- site?: string;
26
- triggers?: (string | number)[];
27
- routes?: (string | number)[];
28
- legacyEnv?: boolean;
29
- jsxFactory: undefined | string;
30
- jsxFragment: undefined | string;
31
- };
32
-
33
- function sleep(ms: number) {
34
- return new Promise((resolve) => setTimeout(resolve, ms));
35
- }
36
-
37
- export default async function publish(props: Props): Promise<void> {
38
- if (props.public && props.format === "service-worker") {
39
- // TODO: check config too
40
- throw new Error(
41
- "You cannot use the service worker format with a public directory."
42
- );
43
- }
44
- // TODO: warn if git/hg has uncommitted changes
45
- const { config } = props;
46
- const {
47
- account_id: accountId,
48
- build,
49
- // @ts-expect-error hidden
50
- __path__,
51
- } = config;
52
-
53
- const envRootObj =
54
- props.env && config.env ? config.env[props.env] || {} : config;
55
-
56
- assert(
57
- envRootObj.compatibility_date || props.compatibilityDate,
58
- "A compatibility_date is required when publishing. Add one to your wrangler.toml file, or pass it in your terminal as --compatibility_date. See https://developers.cloudflare.com/workers/platform/compatibility-dates for more information."
59
- );
60
-
61
- if (accountId === undefined) {
62
- throw new Error("No account_id provided.");
63
- }
64
-
65
- const triggers = props.triggers || config.triggers?.crons;
66
- const routes = props.routes || config.routes;
67
-
68
- const jsxFactory = props.jsxFactory || config.jsx_factory;
69
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
70
-
71
- assert(config.account_id, "missing account id");
72
-
73
- let scriptName = props.name || config.name;
74
- assert(
75
- scriptName,
76
- 'You need to provide a name when publishing a worker. Either pass it as a cli arg with `--name <name>` or in your config file as `name = "<name>"`'
77
- );
78
-
79
- let file: string;
80
- if (props.script) {
81
- file = props.script;
82
- } else {
83
- assert(build?.upload?.main, "missing main file");
84
- file = path.join(path.dirname(__path__), build.upload.main);
85
- }
86
-
87
- if (props.legacyEnv) {
88
- scriptName += props.env ? `-${props.env}` : "";
89
- }
90
- const envName = props.env ?? "production";
91
-
92
- const destination = await tmp.dir({ unsafeCleanup: true });
93
-
94
- if (props.config.build?.command) {
95
- // TODO: add a deprecation message here?
96
- console.log("running:", props.config.build.command);
97
- const buildCommandPieces = props.config.build.command.split(" ");
98
- await execa(buildCommandPieces[0], buildCommandPieces.slice(1), {
99
- stdout: "inherit",
100
- stderr: "inherit",
101
- ...(props.config.build?.cwd && { cwd: props.config.build.cwd }),
102
- });
103
- }
104
-
105
- const moduleCollector = makeModuleCollector();
106
- const result = await esbuild.build({
107
- ...(props.public
108
- ? {
109
- stdin: {
110
- contents: (
111
- await readFile(
112
- path.join(__dirname, "../static-asset-facade.js"),
113
- "utf8"
114
- )
115
- ).replace("__ENTRY_POINT__", path.join(process.cwd(), file)),
116
- sourcefile: "static-asset-facade.js",
117
- resolveDir: path.dirname(file),
118
- },
119
- }
120
- : { entryPoints: [file] }),
121
- bundle: true,
122
- nodePaths: props.public ? [path.join(__dirname, "../vendor")] : undefined,
123
- outdir: destination.path,
124
- external: ["__STATIC_CONTENT_MANIFEST"],
125
- format: "esm",
126
- sourcemap: true,
127
- metafile: true,
128
- conditions: ["worker", "browser"],
129
- loader: {
130
- ".js": "jsx",
131
- },
132
- plugins: [moduleCollector.plugin],
133
- ...(jsxFactory && { jsxFactory }),
134
- ...(jsxFragment && { jsxFragment }),
135
- });
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 expectedEntryPoint = props.public
141
- ? path.join(path.dirname(file), "static-asset-facade.js")
142
- : file;
143
- const outputEntry = Object.entries(metafile.outputs).find(
144
- ([, { entryPoint }]) => entryPoint === expectedEntryPoint
145
- );
146
- if (outputEntry === undefined) {
147
- throw new Error(
148
- `Cannot find entry-point "${expectedEntryPoint}" in generated bundle.`
149
- );
150
- }
151
- const { format } = props;
152
- const bundle = {
153
- type: outputEntry[1].exports.length > 0 ? "esm" : "commonjs",
154
- exports: outputEntry[1].exports,
155
- };
156
-
157
- // TODO: instead of bundling the facade with the worker, we should just bundle the worker and expose it as a module.
158
- // That way we'll be able to accurately tell if this is a service worker or not.
159
-
160
- if (format === "modules" && bundle.type === "commonjs") {
161
- console.error("⎔ Cannot use modules with a commonjs bundle.");
162
- // TODO: a much better error message here, with what to do next
163
- return;
164
- }
165
- if (format === "service-worker" && bundle.type !== "esm") {
166
- console.error("⎔ Cannot use service-worker with a esm bundle.");
167
- // TODO: a much better error message here, with what to do next
168
- return;
169
- }
170
-
171
- const content = await readFile(outputEntry[0], { encoding: "utf-8" });
172
- await destination.cleanup();
173
-
174
- // if config.migrations
175
- // get current migration tag
176
- let migrations;
177
- if (config.migrations !== undefined) {
178
- const scripts = await fetchResult<{ id: string; migration_tag: string }[]>(
179
- `/accounts/${accountId}/workers/scripts`
180
- );
181
- const script = scripts.find(({ id }) => id === scriptName);
182
- if (script?.migration_tag) {
183
- // was already published once
184
- const foundIndex = config.migrations.findIndex(
185
- (migration) => migration.tag === script.migration_tag
186
- );
187
- if (foundIndex === -1) {
188
- console.warn(
189
- `The published script ${scriptName} has a migration tag "${script.migration_tag}, which was not found in wrangler.toml. You may have already deleted it. Applying all available migrations to the script...`
190
- );
191
- migrations = {
192
- old_tag: script.migration_tag,
193
- new_tag: config.migrations[config.migrations.length - 1].tag,
194
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
195
- };
196
- } else {
197
- migrations = {
198
- old_tag: script.migration_tag,
199
- new_tag: config.migrations[config.migrations.length - 1].tag,
200
- steps: config.migrations
201
- .slice(foundIndex + 1)
202
- .map(({ tag: _tag, ...rest }) => rest),
203
- };
204
- }
205
- } else {
206
- migrations = {
207
- new_tag: config.migrations[config.migrations.length - 1].tag,
208
- steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
209
- };
210
- }
211
- }
212
-
213
- const assetPath = props.public || props.site || props.config.site?.bucket; // TODO: allow both
214
- const assets = assetPath
215
- ? await syncAssets(accountId, scriptName, assetPath, false)
216
- : { manifest: undefined, namespace: undefined };
217
-
218
- const bindings: CfWorkerInit["bindings"] = {
219
- kv_namespaces: envRootObj.kv_namespaces?.concat(
220
- assets.namespace
221
- ? { binding: "__STATIC_CONTENT", id: assets.namespace }
222
- : []
223
- ),
224
- vars: envRootObj.vars,
225
- durable_objects: envRootObj.durable_objects,
226
- services: envRootObj.experimental_services,
227
- };
228
-
229
- const worker: CfWorkerInit = {
230
- name: scriptName,
231
- main: {
232
- name: path.basename(outputEntry[0]),
233
- content: content,
234
- type: bundle.type === "esm" ? "esm" : "commonjs",
235
- },
236
- bindings,
237
- ...(migrations && { migrations }),
238
- modules: moduleCollector.modules.concat(
239
- assets.manifest
240
- ? {
241
- name: "__STATIC_CONTENT_MANIFEST",
242
- content: JSON.stringify(assets.manifest),
243
- type: "text",
244
- }
245
- : []
246
- ),
247
- compatibility_date: config.compatibility_date,
248
- compatibility_flags: config.compatibility_flags,
249
- usage_model: config.usage_model,
250
- };
251
-
252
- const start = Date.now();
253
- function formatTime(duration: number) {
254
- return `(${(duration / 1000).toFixed(2)} sec)`;
255
- }
256
-
257
- const notProd = !props.legacyEnv && props.env;
258
- const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
259
- const workerUrl = notProd
260
- ? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
261
- : `/accounts/${accountId}/workers/scripts/${scriptName}`;
262
-
263
- // Upload the script so it has time to propagate.
264
- const { available_on_subdomain } = await fetchResult(
265
- `${workerUrl}?available_on_subdomain=true`,
266
- {
267
- method: "PUT",
268
- // @ts-expect-error: TODO: fix this type error!
269
- body: toFormData(worker),
270
- }
271
- );
272
-
273
- const uploadMs = Date.now() - start;
274
- console.log("Uploaded", workerName, formatTime(uploadMs));
275
- const deployments: Promise<string[]>[] = [];
276
-
277
- const userSubdomain = (
278
- await fetchResult<{ subdomain: string }>(
279
- `/accounts/${accountId}/workers/subdomain`
280
- )
281
- ).subdomain;
282
-
283
- const scriptURL =
284
- props.legacyEnv || !props.env
285
- ? `${scriptName}.${userSubdomain}.workers.dev`
286
- : `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
287
-
288
- // Enable the `workers.dev` subdomain.
289
- // TODO: Make this configurable.
290
- if (!available_on_subdomain) {
291
- deployments.push(
292
- fetchResult(`${workerUrl}/subdomain`, {
293
- method: "POST",
294
- body: JSON.stringify({ enabled: true }),
295
- headers: {
296
- "Content-Type": "application/json",
297
- },
298
- })
299
- .then(() => [scriptURL])
300
- // Add a delay when the subdomain is first created.
301
- // This is to prevent an issue where a negative cache-hit
302
- // causes the subdomain to be unavailable for 30 seconds.
303
- // This is a temporary measure until we fix this on the edge.
304
- .then(async (url) => {
305
- await sleep(3000);
306
- return url;
307
- })
308
- );
309
- } else {
310
- deployments.push(Promise.resolve([scriptURL]));
311
- }
312
-
313
- // Update routing table for the script.
314
- if (routes && routes.length) {
315
- deployments.push(
316
- fetchResult(`${workerUrl}/routes`, {
317
- // TODO: PATCH will not delete previous routes on this script,
318
- // whereas PUT will. We need to decide on the default behaviour
319
- // and how to configure it.
320
- method: "PUT",
321
- body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
322
- headers: {
323
- "Content-Type": "application/json",
324
- },
325
- }).then(() => {
326
- if (routes.length > 10) {
327
- return routes
328
- .slice(0, 9)
329
- .map(String)
330
- .concat([`...and ${routes.length - 10} more routes`]);
331
- }
332
- return routes.map(String);
333
- })
334
- );
335
- }
336
-
337
- // Configure any schedules for the script.
338
- // TODO: rename this to `schedules`?
339
- if (triggers && triggers.length) {
340
- deployments.push(
341
- fetchResult(`${workerUrl}/schedules`, {
342
- // TODO: Unlike routes, this endpoint does not support PATCH.
343
- // So technically, this will override any previous schedules.
344
- // We should change the endpoint to support PATCH.
345
- method: "PUT",
346
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
347
- headers: {
348
- "Content-Type": "application/json",
349
- },
350
- }).then(() => triggers.map(String))
351
- );
352
- }
353
-
354
- if (!deployments.length) {
355
- return;
356
- }
357
-
358
- const targets = await Promise.all(deployments);
359
- const deployMs = Date.now() - start - uploadMs;
360
- console.log("Deployed", workerName, formatTime(deployMs));
361
- for (const target of targets.flat()) {
362
- console.log(" ", target);
363
- }
364
- }