wrangler 0.0.0-e151223 → 0.0.0-e1b8ac4
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.
- package/Cloudflare_CA.pem +18 -0
- package/README.md +27 -14
- package/bin/wrangler.js +49 -5
- package/kv-asset-handler.js +1 -0
- package/miniflare-dist/index.mjs +4886 -0
- package/package.json +57 -28
- package/pages/functions/buildPlugin.ts +105 -0
- package/pages/functions/buildWorker.ts +93 -4
- package/pages/functions/filepath-routing.test.ts +223 -36
- package/pages/functions/filepath-routing.ts +78 -120
- package/pages/functions/routes.ts +13 -17
- package/pages/functions/template-plugin.ts +147 -0
- package/pages/functions/template-worker.ts +24 -17
- package/src/__tests__/config-cache.test.ts +36 -0
- package/src/__tests__/configuration.test.ts +3548 -0
- package/src/__tests__/dev.test.tsx +1049 -65
- package/src/__tests__/guess-worker-format.test.ts +85 -0
- package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
- package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
- package/src/__tests__/helpers/mock-account-id.ts +26 -8
- package/src/__tests__/helpers/mock-bin.ts +36 -0
- package/src/__tests__/helpers/mock-cfetch.ts +48 -10
- package/src/__tests__/helpers/mock-console.ts +39 -8
- package/src/__tests__/helpers/mock-dialogs.ts +99 -11
- package/src/__tests__/helpers/mock-http-server.ts +46 -0
- package/src/__tests__/helpers/mock-istty.ts +27 -0
- package/src/__tests__/helpers/mock-kv.ts +9 -16
- package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
- package/src/__tests__/helpers/mock-process.ts +24 -0
- package/src/__tests__/helpers/mock-stdin.ts +103 -0
- package/src/__tests__/helpers/mock-web-socket.ts +29 -0
- package/src/__tests__/helpers/run-in-tmp.ts +10 -0
- package/src/__tests__/helpers/run-wrangler.ts +5 -3
- package/src/__tests__/helpers/write-worker-source.ts +31 -0
- package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
- package/src/__tests__/https-options.test.ts +130 -0
- package/src/__tests__/index.test.ts +160 -309
- package/src/__tests__/init.test.ts +1992 -0
- package/src/__tests__/jest.setup.ts +79 -6
- package/src/__tests__/kv.test.ts +651 -280
- package/src/__tests__/logger.test.ts +141 -0
- package/src/__tests__/package-manager.test.ts +353 -0
- package/src/__tests__/pages.test.ts +754 -0
- package/src/__tests__/parse.test.ts +330 -0
- package/src/__tests__/publish.test.ts +5671 -959
- package/src/__tests__/r2.test.ts +233 -0
- package/src/__tests__/route.test.ts +45 -0
- package/src/__tests__/secret.test.ts +362 -91
- package/src/__tests__/tail.test.ts +690 -0
- package/src/__tests__/user.test.ts +132 -0
- package/src/__tests__/whoami.test.tsx +60 -7
- package/src/abort.d.ts +3 -0
- package/src/bundle.ts +204 -0
- package/src/cfetch/index.ts +28 -18
- package/src/cfetch/internal.ts +99 -29
- package/src/cli.ts +6 -2
- package/src/config/README.md +107 -0
- package/src/config/config.ts +243 -0
- package/src/config/diagnostics.ts +80 -0
- package/src/config/environment.ts +420 -0
- package/src/config/index.ts +225 -0
- package/src/config/validation-helpers.ts +584 -0
- package/src/config/validation.ts +1580 -0
- package/src/config-cache.ts +45 -0
- package/src/create-worker-preview.ts +185 -0
- package/src/create-worker-upload-form.ts +254 -0
- package/src/dev/dev-vars.ts +36 -0
- package/src/dev/dev.tsx +399 -0
- package/src/dev/local.tsx +321 -0
- package/src/dev/remote.tsx +242 -0
- package/src/dev/use-esbuild.ts +112 -0
- package/src/dialogs.tsx +64 -6
- package/src/durable.ts +102 -0
- package/src/entry.ts +322 -0
- package/src/environment-variables.ts +35 -0
- package/src/errors.ts +11 -0
- package/src/generate-auth-url.ts +33 -0
- package/src/generate-random-state.ts +16 -0
- package/src/https-options.ts +123 -0
- package/src/index.tsx +1835 -988
- package/src/inspect.ts +80 -14
- package/src/intl-polyfill.d.ts +139 -0
- package/src/{kv.tsx → kv.ts} +199 -67
- package/src/logger.ts +73 -0
- package/src/miniflare-cli/README.md +30 -0
- package/src/miniflare-cli/enum-keys.ts +17 -0
- package/src/miniflare-cli/index.ts +41 -0
- package/src/miniflare-cli/request-context.ts +40 -0
- package/src/module-collection.ts +226 -31
- package/src/open-in-browser.ts +17 -0
- package/src/package-manager.ts +174 -0
- package/src/pages.tsx +1132 -84
- package/src/parse.ts +222 -0
- package/src/proxy.ts +176 -70
- package/src/publish.ts +624 -308
- package/src/r2.ts +50 -0
- package/src/selfsigned.d.ts +29 -0
- package/src/sites.tsx +185 -57
- package/src/tail/filters.ts +279 -0
- package/src/tail/index.ts +299 -0
- package/src/tail/printing.ts +67 -0
- package/src/update-check.ts +19 -0
- package/src/user.tsx +349 -166
- package/src/whoami.tsx +5 -3
- package/src/{api/worker.ts → worker.ts} +65 -39
- package/src/zones.ts +73 -0
- package/templates/gitignore +171 -0
- package/templates/new-worker-scheduled.js +17 -0
- package/templates/new-worker-scheduled.ts +32 -0
- package/templates/new-worker.js +15 -0
- package/templates/new-worker.ts +30 -0
- package/{static-asset-facade.js → templates/static-asset-facade.js} +3 -7
- package/templates/tsconfig.json +105 -0
- package/wrangler-dist/cli.js +76649 -75066
- package/src/__tests__/helpers/mock-user.ts +0 -27
- package/src/__tests__/logout.test.ts +0 -50
- package/src/api/form_data.ts +0 -134
- package/src/api/preview.ts +0 -128
- package/src/config.ts +0 -641
- package/src/dev.tsx +0 -834
- package/src/npm-installer.ts +0 -20
- package/src/tail.tsx +0 -73
- package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
- package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
- package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
- package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
- package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
- package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
- package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
- package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
- package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
- package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
- package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
- package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
- package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
- package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
- package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
- package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
- package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
- package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
- package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
- package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
- package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
- package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
- package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
- package/vendor/wrangler-mime/CHANGELOG.md +0 -289
- package/vendor/wrangler-mime/LICENSE +0 -21
- package/vendor/wrangler-mime/Mime.js +0 -97
- package/vendor/wrangler-mime/README.md +0 -187
- package/vendor/wrangler-mime/cli.js +0 -46
- package/vendor/wrangler-mime/index.js +0 -4
- package/vendor/wrangler-mime/lite.js +0 -4
- package/vendor/wrangler-mime/package.json +0 -52
- package/vendor/wrangler-mime/types/other.js +0 -1
- package/vendor/wrangler-mime/types/standard.js +0 -1
- package/wrangler-dist/cli.js.map +0 -7
package/src/publish.ts
CHANGED
|
@@ -1,410 +1,726 @@
|
|
|
1
1
|
import assert from "node:assert";
|
|
2
|
-
import {
|
|
2
|
+
import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
|
|
3
3
|
import path from "node:path";
|
|
4
4
|
import { URLSearchParams } from "node:url";
|
|
5
|
-
import * as esbuild from "esbuild";
|
|
6
|
-
import { execaCommand } from "execa";
|
|
7
5
|
import tmp from "tmp-promise";
|
|
8
|
-
import {
|
|
9
|
-
import { fetchResult } from "./cfetch";
|
|
10
|
-
import
|
|
6
|
+
import { bundleWorker } from "./bundle";
|
|
7
|
+
import { fetchListResult, fetchResult } from "./cfetch";
|
|
8
|
+
import { printBindings } from "./config";
|
|
9
|
+
import { createWorkerUploadForm } from "./create-worker-upload-form";
|
|
10
|
+
import { confirm } from "./dialogs";
|
|
11
|
+
import { getMigrationsToUpload } from "./durable";
|
|
12
|
+
import { logger } from "./logger";
|
|
13
|
+
import { ParseError } from "./parse";
|
|
11
14
|
import { syncAssets } from "./sites";
|
|
12
|
-
import
|
|
15
|
+
import { getZoneForRoute } from "./zones";
|
|
13
16
|
import type { Config } from "./config";
|
|
17
|
+
import type {
|
|
18
|
+
Route,
|
|
19
|
+
ZoneIdRoute,
|
|
20
|
+
ZoneNameRoute,
|
|
21
|
+
CustomDomainRoute,
|
|
22
|
+
} from "./config/environment";
|
|
23
|
+
import type { Entry } from "./entry";
|
|
14
24
|
import type { AssetPaths } from "./sites";
|
|
15
|
-
import type {
|
|
16
|
-
|
|
17
|
-
type CfScriptFormat = undefined | "modules" | "service-worker";
|
|
25
|
+
import type { CfWorkerInit } from "./worker";
|
|
18
26
|
|
|
19
27
|
type Props = {
|
|
20
28
|
config: Config;
|
|
21
|
-
|
|
22
|
-
|
|
29
|
+
accountId: string | undefined;
|
|
30
|
+
entry: Entry;
|
|
31
|
+
rules: Config["rules"];
|
|
23
32
|
name: string | undefined;
|
|
24
33
|
env: string | undefined;
|
|
25
34
|
compatibilityDate: string | undefined;
|
|
26
35
|
compatibilityFlags: string[] | undefined;
|
|
27
36
|
assetPaths: AssetPaths | undefined;
|
|
28
|
-
triggers:
|
|
29
|
-
routes:
|
|
37
|
+
triggers: string[] | undefined;
|
|
38
|
+
routes: string[] | undefined;
|
|
30
39
|
legacyEnv: boolean | undefined;
|
|
31
|
-
jsxFactory:
|
|
32
|
-
jsxFragment:
|
|
33
|
-
|
|
40
|
+
jsxFactory: string | undefined;
|
|
41
|
+
jsxFragment: string | undefined;
|
|
42
|
+
tsconfig: string | undefined;
|
|
43
|
+
isWorkersSite: boolean;
|
|
44
|
+
minify: boolean | undefined;
|
|
45
|
+
nodeCompat: boolean | undefined;
|
|
46
|
+
outDir: string | undefined;
|
|
47
|
+
dryRun: boolean | undefined;
|
|
34
48
|
};
|
|
35
49
|
|
|
50
|
+
type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
|
|
51
|
+
|
|
36
52
|
function sleep(ms: number) {
|
|
37
53
|
return new Promise((resolve) => setTimeout(resolve, ms));
|
|
38
54
|
}
|
|
39
55
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
56
|
+
function renderRoute(route: Route): string {
|
|
57
|
+
let result = "";
|
|
58
|
+
if (typeof route === "string") {
|
|
59
|
+
result = route;
|
|
60
|
+
} else {
|
|
61
|
+
result = route.pattern;
|
|
62
|
+
const isCustomDomain = Boolean(
|
|
63
|
+
"custom_domain" in route && route.custom_domain
|
|
45
64
|
);
|
|
65
|
+
if (isCustomDomain && "zone_id" in route) {
|
|
66
|
+
result += ` (custom domain - zone id: ${route.zone_id})`;
|
|
67
|
+
} else if (isCustomDomain && "zone_name" in route) {
|
|
68
|
+
result += ` (custom domain - zone name: ${route.zone_name})`;
|
|
69
|
+
} else if (isCustomDomain) {
|
|
70
|
+
result += ` (custom domain)`;
|
|
71
|
+
} else if ("zone_id" in route) {
|
|
72
|
+
result += ` (zone id: ${route.zone_id})`;
|
|
73
|
+
} else if ("zone_name" in route) {
|
|
74
|
+
result += ` (zone name: ${route.zone_name})`;
|
|
75
|
+
}
|
|
46
76
|
}
|
|
47
|
-
|
|
48
|
-
|
|
49
|
-
const {
|
|
50
|
-
account_id: accountId,
|
|
51
|
-
build,
|
|
52
|
-
// @ts-expect-error hidden
|
|
53
|
-
__path__,
|
|
54
|
-
} = config;
|
|
77
|
+
return result;
|
|
78
|
+
}
|
|
55
79
|
|
|
56
|
-
|
|
57
|
-
|
|
80
|
+
// this function takes a string with quotes in it
|
|
81
|
+
// (i.e. `hello "world", if that really is your name`)
|
|
82
|
+
// and peels out the first instance of a substring
|
|
83
|
+
// bounded by quotes (so, in the example above, `world`)
|
|
84
|
+
//
|
|
85
|
+
// this is useful because the /domains api will return
|
|
86
|
+
// which domains conflicted in an error message, bounded
|
|
87
|
+
// by a string, which we can use to provide helpful
|
|
88
|
+
// messages to a user
|
|
89
|
+
function getQuoteBoundedSubstring(content: string) {
|
|
90
|
+
const matches = content.split('"');
|
|
91
|
+
return matches[1] ?? "";
|
|
92
|
+
}
|
|
58
93
|
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
94
|
+
function isOriginConflictError(
|
|
95
|
+
e: unknown
|
|
96
|
+
): e is { code: 100116; message: string; notes: Array<{ text: string }> } {
|
|
97
|
+
return (
|
|
98
|
+
typeof e === "object" &&
|
|
99
|
+
e !== null &&
|
|
100
|
+
(e as { code: number }).code === 100116
|
|
62
101
|
);
|
|
102
|
+
}
|
|
63
103
|
|
|
64
|
-
|
|
65
|
-
|
|
104
|
+
function isDNSConflictError(
|
|
105
|
+
e: unknown
|
|
106
|
+
): e is { code: 100117; message: string; notes: Array<{ text: string }> } {
|
|
107
|
+
return (
|
|
108
|
+
typeof e === "object" &&
|
|
109
|
+
e !== null &&
|
|
110
|
+
(e as { code: number }).code === 100117
|
|
111
|
+
);
|
|
112
|
+
}
|
|
113
|
+
|
|
114
|
+
// empty error class to throw and then explicitly catch via `instanceof`
|
|
115
|
+
class CustomDomainOverrideRejected extends Error {}
|
|
116
|
+
|
|
117
|
+
// publishing to custom domains involves a few more steps than just updating
|
|
118
|
+
// the routing table, and thus the api implementing it is fairly defensive -
|
|
119
|
+
// it will error eagerly on conflicts against existing domains or existing
|
|
120
|
+
// managed DNS records
|
|
121
|
+
//
|
|
122
|
+
// however, you can pass params to override the errors. we start on the
|
|
123
|
+
// defensive path, and if one of these errors occur, we prompt the user
|
|
124
|
+
// for confirmation that they do indeed want to override the conflicts, and
|
|
125
|
+
// then retry the request with the right override added
|
|
126
|
+
//
|
|
127
|
+
// if a user does not confirm that they want to override, we skip publishing
|
|
128
|
+
// to these custom domains, but continue on through the rest of the
|
|
129
|
+
// publish stage
|
|
130
|
+
function publishCustomDomains(
|
|
131
|
+
workerUrl: string,
|
|
132
|
+
domains: Array<RouteObject>
|
|
133
|
+
): Promise<string[]> {
|
|
134
|
+
const config = {
|
|
135
|
+
override_scope: true,
|
|
136
|
+
override_existing_origin: false,
|
|
137
|
+
override_existing_dns_record: false,
|
|
138
|
+
};
|
|
139
|
+
const origins = domains.map((domainRoute) => {
|
|
140
|
+
return {
|
|
141
|
+
hostname: domainRoute.pattern,
|
|
142
|
+
zone_id: "zone_id" in domainRoute ? domainRoute.zone_id : undefined,
|
|
143
|
+
zone_name: "zone_name" in domainRoute ? domainRoute.zone_name : undefined,
|
|
144
|
+
};
|
|
145
|
+
});
|
|
146
|
+
|
|
147
|
+
if (!process.stdout.isTTY) {
|
|
148
|
+
// running in non-interactive mode.
|
|
149
|
+
// existing origins / dns records are not indicative of errors,
|
|
150
|
+
// so we aggressively update rather than aggressively fail
|
|
151
|
+
config.override_existing_origin = true;
|
|
152
|
+
config.override_existing_dns_record = true;
|
|
66
153
|
}
|
|
67
154
|
|
|
155
|
+
// Mixing promise chains with async/await is funky, but it allows us to keep related
|
|
156
|
+
// logic synchronous-looking (i.e. prompting for confirmation and then re-requesting)
|
|
157
|
+
// while retaining the flexibility of promise chain fall-throughs. We can group error
|
|
158
|
+
// handling logic in dedicated catch calls, and all we have to do is re-throw an
|
|
159
|
+
// error and it will pass down to the next catch call
|
|
160
|
+
return fetchResult(`${workerUrl}/domains`, {
|
|
161
|
+
method: "PUT",
|
|
162
|
+
body: JSON.stringify({ ...config, origins }),
|
|
163
|
+
headers: {
|
|
164
|
+
"Content-Type": "application/json",
|
|
165
|
+
},
|
|
166
|
+
})
|
|
167
|
+
.catch(async (err) => {
|
|
168
|
+
if (isOriginConflictError(err)) {
|
|
169
|
+
const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
|
|
170
|
+
const shouldContinue = await confirm(
|
|
171
|
+
`Custom Domains already exist for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
|
|
172
|
+
);
|
|
173
|
+
if (!shouldContinue) {
|
|
174
|
+
throw new CustomDomainOverrideRejected();
|
|
175
|
+
}
|
|
176
|
+
config.override_existing_origin = true;
|
|
177
|
+
await fetchResult(`${workerUrl}/domains`, {
|
|
178
|
+
method: "PUT",
|
|
179
|
+
body: JSON.stringify({ ...config, origins }),
|
|
180
|
+
headers: {
|
|
181
|
+
"Content-Type": "application/json",
|
|
182
|
+
},
|
|
183
|
+
});
|
|
184
|
+
} else {
|
|
185
|
+
throw err;
|
|
186
|
+
}
|
|
187
|
+
})
|
|
188
|
+
.catch(async (err) => {
|
|
189
|
+
if (isDNSConflictError(err)) {
|
|
190
|
+
const conflictingOrigins = getQuoteBoundedSubstring(err.notes[0].text);
|
|
191
|
+
const shouldContinue = await confirm(
|
|
192
|
+
`You already have conflicting DNS records for these domains: "${conflictingOrigins}"\nUpdate them to point to this script instead?`
|
|
193
|
+
);
|
|
194
|
+
if (!shouldContinue) {
|
|
195
|
+
throw new CustomDomainOverrideRejected();
|
|
196
|
+
}
|
|
197
|
+
config.override_existing_dns_record = true;
|
|
198
|
+
await fetchResult(`${workerUrl}/domains`, {
|
|
199
|
+
method: "PUT",
|
|
200
|
+
body: JSON.stringify({ ...config, origins }),
|
|
201
|
+
headers: {
|
|
202
|
+
"Content-Type": "application/json",
|
|
203
|
+
},
|
|
204
|
+
});
|
|
205
|
+
} else {
|
|
206
|
+
throw err;
|
|
207
|
+
}
|
|
208
|
+
})
|
|
209
|
+
.then(() => domains.map((domain) => renderRoute(domain)))
|
|
210
|
+
.catch((err) => {
|
|
211
|
+
if (err instanceof CustomDomainOverrideRejected) {
|
|
212
|
+
return [
|
|
213
|
+
domains.length > 1
|
|
214
|
+
? `Publishing to ${domains.length} Custom Domains was skipped, fix conflicts and try again`
|
|
215
|
+
: `Publishing to Custom Domain "${domains[0].pattern}" was skipped, fix conflict and try again`,
|
|
216
|
+
];
|
|
217
|
+
}
|
|
218
|
+
throw err;
|
|
219
|
+
});
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
export default async function publish(props: Props): Promise<void> {
|
|
223
|
+
// TODO: warn if git/hg has uncommitted changes
|
|
224
|
+
const { config, accountId } = props;
|
|
225
|
+
|
|
226
|
+
assert(
|
|
227
|
+
props.compatibilityDate || config.compatibility_date,
|
|
228
|
+
"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."
|
|
229
|
+
);
|
|
230
|
+
|
|
68
231
|
const triggers = props.triggers || config.triggers?.crons;
|
|
69
|
-
const routes =
|
|
232
|
+
const routes =
|
|
233
|
+
props.routes ?? config.routes ?? (config.route ? [config.route] : []) ?? [];
|
|
234
|
+
const routesOnly: Array<Route> = [];
|
|
235
|
+
const customDomainsOnly: Array<RouteObject> = [];
|
|
236
|
+
for (const route of routes) {
|
|
237
|
+
if (typeof route !== "string" && route.custom_domain) {
|
|
238
|
+
if (route.pattern.includes("*")) {
|
|
239
|
+
throw new Error(
|
|
240
|
+
`Cannot use "${route.pattern}" as a Custom Domain; wildcard operators (*) are not allowed`
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
if (route.pattern.includes("/")) {
|
|
244
|
+
throw new Error(
|
|
245
|
+
`Cannot use "${route.pattern}" as a Custom Domain; paths are not allowed`
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
customDomainsOnly.push(route);
|
|
249
|
+
} else {
|
|
250
|
+
routesOnly.push(route);
|
|
251
|
+
}
|
|
252
|
+
}
|
|
253
|
+
|
|
254
|
+
// deployToWorkersDev defaults to true only if there aren't any routes defined
|
|
255
|
+
const deployToWorkersDev = config.workers_dev ?? routes.length === 0;
|
|
70
256
|
|
|
71
257
|
const jsxFactory = props.jsxFactory || config.jsx_factory;
|
|
72
258
|
const jsxFragment = props.jsxFragment || config.jsx_fragment;
|
|
73
259
|
|
|
74
|
-
|
|
260
|
+
const minify = props.minify ?? config.minify;
|
|
261
|
+
|
|
262
|
+
const nodeCompat = props.nodeCompat ?? config.node_compat;
|
|
263
|
+
if (nodeCompat) {
|
|
264
|
+
logger.warn(
|
|
265
|
+
"Enabling node.js compatibility mode for built-ins and globals. This is experimental and has serious tradeoffs. Please see https://github.com/ionic-team/rollup-plugin-node-polyfills/ for more details."
|
|
266
|
+
);
|
|
267
|
+
}
|
|
75
268
|
|
|
76
|
-
|
|
269
|
+
const scriptName = props.name;
|
|
77
270
|
assert(
|
|
78
271
|
scriptName,
|
|
79
272
|
'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>"`'
|
|
80
273
|
);
|
|
81
274
|
|
|
82
|
-
if (config.site?.["entry-point"]) {
|
|
83
|
-
console.warn(
|
|
84
|
-
"Deprecation notice: The `site.entry-point` config field is no longer used.\n" +
|
|
85
|
-
"The entry-point should be specified via the command line (e.g. `wrangler publish path/to/script`) or the `build.upload.main` config field.\n" +
|
|
86
|
-
"Please remove the `site.entry-point` field from the `wrangler.toml` file."
|
|
87
|
-
);
|
|
88
|
-
}
|
|
89
|
-
|
|
90
275
|
assert(
|
|
91
276
|
!config.site || config.site.bucket,
|
|
92
|
-
"A [site] definition requires a `bucket` field with a path to the site's
|
|
277
|
+
"A [site] definition requires a `bucket` field with a path to the site's assets directory."
|
|
93
278
|
);
|
|
94
279
|
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
//
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
}
|
|
106
|
-
file = path.resolve(path.dirname(__path__), build.upload.main);
|
|
280
|
+
if (props.outDir) {
|
|
281
|
+
// we're using a custom output directory,
|
|
282
|
+
// so let's first ensure it exists
|
|
283
|
+
mkdirSync(props.outDir, { recursive: true });
|
|
284
|
+
// add a README
|
|
285
|
+
const readmePath = path.join(props.outDir, "README.md");
|
|
286
|
+
writeFileSync(
|
|
287
|
+
readmePath,
|
|
288
|
+
`This folder contains the built output assets for the worker "${scriptName}" generated at ${new Date().toISOString()}.`
|
|
289
|
+
);
|
|
107
290
|
}
|
|
108
291
|
|
|
109
|
-
|
|
110
|
-
scriptName += props.env ? `-${props.env}` : "";
|
|
111
|
-
}
|
|
292
|
+
const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
|
|
112
293
|
const envName = props.env ?? "production";
|
|
113
294
|
|
|
114
|
-
const
|
|
115
|
-
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
stdout: "inherit",
|
|
121
|
-
stderr: "inherit",
|
|
122
|
-
...(props.config.build?.cwd && { cwd: props.config.build.cwd }),
|
|
123
|
-
});
|
|
124
|
-
}
|
|
125
|
-
|
|
126
|
-
const moduleCollector = makeModuleCollector();
|
|
127
|
-
const result = await esbuild.build({
|
|
128
|
-
...(props.experimentalPublic
|
|
129
|
-
? {
|
|
130
|
-
stdin: {
|
|
131
|
-
contents: (
|
|
132
|
-
await readFile(
|
|
133
|
-
path.join(__dirname, "../static-asset-facade.js"),
|
|
134
|
-
"utf8"
|
|
135
|
-
)
|
|
136
|
-
).replace("__ENTRY_POINT__", file),
|
|
137
|
-
sourcefile: "static-asset-facade.js",
|
|
138
|
-
resolveDir: path.dirname(file),
|
|
139
|
-
},
|
|
140
|
-
nodePaths: [path.join(__dirname, "../vendor")],
|
|
141
|
-
}
|
|
142
|
-
: { entryPoints: [file] }),
|
|
143
|
-
bundle: true,
|
|
144
|
-
outdir: destination.path,
|
|
145
|
-
external: ["__STATIC_CONTENT_MANIFEST"],
|
|
146
|
-
format: "esm",
|
|
147
|
-
sourcemap: true,
|
|
148
|
-
metafile: true,
|
|
149
|
-
conditions: ["worker", "browser"],
|
|
150
|
-
loader: {
|
|
151
|
-
".js": "jsx",
|
|
152
|
-
".html": "text",
|
|
153
|
-
".pem": "text",
|
|
154
|
-
".txt": "text",
|
|
155
|
-
},
|
|
156
|
-
plugins: [moduleCollector.plugin],
|
|
157
|
-
...(jsxFactory && { jsxFactory }),
|
|
158
|
-
...(jsxFragment && { jsxFragment }),
|
|
159
|
-
});
|
|
295
|
+
const start = Date.now();
|
|
296
|
+
const notProd = Boolean(!props.legacyEnv && props.env);
|
|
297
|
+
const workerName = notProd ? `${scriptName} (${envName})` : scriptName;
|
|
298
|
+
const workerUrl = notProd
|
|
299
|
+
? `/accounts/${accountId}/workers/services/${scriptName}/environments/${envName}`
|
|
300
|
+
: `/accounts/${accountId}/workers/scripts/${scriptName}`;
|
|
160
301
|
|
|
161
|
-
|
|
162
|
-
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
163
|
-
const metafile = result.metafile!;
|
|
164
|
-
const entryPoints = Object.entries(metafile.outputs).filter(
|
|
165
|
-
([_path, output]) => output.entryPoint !== undefined
|
|
166
|
-
);
|
|
167
|
-
assert(
|
|
168
|
-
entryPoints.length > 0,
|
|
169
|
-
`Cannot find entry-point "${file}" in generated bundle.` +
|
|
170
|
-
listEntryPoints(entryPoints)
|
|
171
|
-
);
|
|
172
|
-
assert(
|
|
173
|
-
entryPoints.length < 2,
|
|
174
|
-
"More than one entry-point found for generated bundle." +
|
|
175
|
-
listEntryPoints(entryPoints)
|
|
176
|
-
);
|
|
177
|
-
const entryPointExports = entryPoints[0][1].exports;
|
|
178
|
-
const resolvedEntryPointPath = entryPoints[0][0];
|
|
179
|
-
const { format } = props;
|
|
180
|
-
const bundle = {
|
|
181
|
-
type: entryPointExports.length > 0 ? "esm" : "commonjs",
|
|
182
|
-
exports: entryPointExports,
|
|
183
|
-
};
|
|
302
|
+
let available_on_subdomain; // we'll set this later
|
|
184
303
|
|
|
185
|
-
|
|
186
|
-
// That way we'll be able to accurately tell if this is a service worker or not.
|
|
304
|
+
const { format } = props.entry;
|
|
187
305
|
|
|
188
|
-
if (
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
return;
|
|
306
|
+
if (
|
|
307
|
+
!props.isWorkersSite &&
|
|
308
|
+
Boolean(props.assetPaths) &&
|
|
309
|
+
format === "service-worker"
|
|
310
|
+
) {
|
|
311
|
+
throw new Error(
|
|
312
|
+
"You cannot use the service-worker format with an `assets` directory yet. For information on how to migrate to the module-worker format, see: https://developers.cloudflare.com/workers/learning/migrating-to-module-workers/"
|
|
313
|
+
);
|
|
197
314
|
}
|
|
198
315
|
|
|
199
|
-
|
|
200
|
-
|
|
316
|
+
if (config.wasm_modules && format === "modules") {
|
|
317
|
+
throw new Error(
|
|
318
|
+
"You cannot configure [wasm_modules] with an ES module worker. Instead, import the .wasm module directly in your code"
|
|
319
|
+
);
|
|
320
|
+
}
|
|
201
321
|
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
if (config.migrations !== undefined) {
|
|
206
|
-
const scripts = await fetchResult<{ id: string; migration_tag: string }[]>(
|
|
207
|
-
`/accounts/${accountId}/workers/scripts`
|
|
322
|
+
if (config.text_blobs && format === "modules") {
|
|
323
|
+
throw new Error(
|
|
324
|
+
"You cannot configure [text_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
|
|
208
325
|
);
|
|
209
|
-
const script = scripts.find(({ id }) => id === scriptName);
|
|
210
|
-
if (script?.migration_tag) {
|
|
211
|
-
// was already published once
|
|
212
|
-
const foundIndex = config.migrations.findIndex(
|
|
213
|
-
(migration) => migration.tag === script.migration_tag
|
|
214
|
-
);
|
|
215
|
-
if (foundIndex === -1) {
|
|
216
|
-
console.warn(
|
|
217
|
-
`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...`
|
|
218
|
-
);
|
|
219
|
-
migrations = {
|
|
220
|
-
old_tag: script.migration_tag,
|
|
221
|
-
new_tag: config.migrations[config.migrations.length - 1].tag,
|
|
222
|
-
steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
|
|
223
|
-
};
|
|
224
|
-
} else {
|
|
225
|
-
migrations = {
|
|
226
|
-
old_tag: script.migration_tag,
|
|
227
|
-
new_tag: config.migrations[config.migrations.length - 1].tag,
|
|
228
|
-
steps: config.migrations
|
|
229
|
-
.slice(foundIndex + 1)
|
|
230
|
-
.map(({ tag: _tag, ...rest }) => rest),
|
|
231
|
-
};
|
|
232
|
-
}
|
|
233
|
-
} else {
|
|
234
|
-
migrations = {
|
|
235
|
-
new_tag: config.migrations[config.migrations.length - 1].tag,
|
|
236
|
-
steps: config.migrations.map(({ tag: _tag, ...rest }) => rest),
|
|
237
|
-
};
|
|
238
|
-
}
|
|
239
326
|
}
|
|
240
327
|
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
328
|
+
if (config.data_blobs && format === "modules") {
|
|
329
|
+
throw new Error(
|
|
330
|
+
"You cannot configure [data_blobs] with an ES module worker. Instead, import the file directly in your code, and optionally configure `[rules]` in your wrangler.toml"
|
|
331
|
+
);
|
|
332
|
+
}
|
|
333
|
+
try {
|
|
334
|
+
const { modules, resolvedEntryPointPath, bundleType } = await bundleWorker(
|
|
335
|
+
props.entry,
|
|
336
|
+
typeof destination === "string" ? destination : destination.path,
|
|
337
|
+
{
|
|
338
|
+
serveAssetsFromWorker:
|
|
339
|
+
!props.isWorkersSite && Boolean(props.assetPaths),
|
|
340
|
+
jsxFactory,
|
|
341
|
+
jsxFragment,
|
|
342
|
+
rules: props.rules,
|
|
343
|
+
tsconfig: props.tsconfig ?? config.tsconfig,
|
|
344
|
+
minify,
|
|
345
|
+
nodeCompat,
|
|
346
|
+
}
|
|
347
|
+
);
|
|
248
348
|
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
? { binding: "__STATIC_CONTENT", id: assets.namespace }
|
|
253
|
-
: []
|
|
254
|
-
),
|
|
255
|
-
vars: envRootObj.vars,
|
|
256
|
-
durable_objects: envRootObj.durable_objects,
|
|
257
|
-
services: envRootObj.experimental_services,
|
|
258
|
-
};
|
|
349
|
+
const content = readFileSync(resolvedEntryPointPath, {
|
|
350
|
+
encoding: "utf-8",
|
|
351
|
+
});
|
|
259
352
|
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
353
|
+
// durable object migrations
|
|
354
|
+
const migrations = !props.dryRun
|
|
355
|
+
? await getMigrationsToUpload(scriptName, {
|
|
356
|
+
accountId,
|
|
357
|
+
config,
|
|
358
|
+
legacyEnv: props.legacyEnv,
|
|
359
|
+
env: props.env,
|
|
360
|
+
})
|
|
361
|
+
: undefined;
|
|
362
|
+
|
|
363
|
+
const assets = await syncAssets(
|
|
364
|
+
accountId,
|
|
365
|
+
// When we're using the newer service environments, we wouldn't
|
|
366
|
+
// have added the env name on to the script name. However, we must
|
|
367
|
+
// include it in the kv namespace name regardless (since there's no
|
|
368
|
+
// concept of service environments for kv namespaces yet).
|
|
369
|
+
scriptName + (!props.legacyEnv && props.env ? `-${props.env}` : ""),
|
|
370
|
+
props.assetPaths,
|
|
371
|
+
false,
|
|
372
|
+
props.dryRun
|
|
373
|
+
);
|
|
266
374
|
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
375
|
+
const bindings: CfWorkerInit["bindings"] = {
|
|
376
|
+
kv_namespaces: (config.kv_namespaces || []).concat(
|
|
377
|
+
assets.namespace
|
|
378
|
+
? { binding: "__STATIC_CONTENT", id: assets.namespace }
|
|
379
|
+
: []
|
|
380
|
+
),
|
|
381
|
+
vars: config.vars,
|
|
382
|
+
wasm_modules: config.wasm_modules,
|
|
383
|
+
text_blobs: {
|
|
384
|
+
...config.text_blobs,
|
|
385
|
+
...(assets.manifest &&
|
|
386
|
+
format === "service-worker" && {
|
|
387
|
+
__STATIC_CONTENT_MANIFEST: "__STATIC_CONTENT_MANIFEST",
|
|
388
|
+
}),
|
|
389
|
+
},
|
|
390
|
+
data_blobs: config.data_blobs,
|
|
391
|
+
durable_objects: config.durable_objects,
|
|
392
|
+
r2_buckets: config.r2_buckets,
|
|
393
|
+
services: config.services,
|
|
394
|
+
unsafe: config.unsafe?.bindings,
|
|
395
|
+
};
|
|
396
|
+
|
|
397
|
+
if (assets.manifest) {
|
|
398
|
+
modules.push({
|
|
399
|
+
name: "__STATIC_CONTENT_MANIFEST",
|
|
400
|
+
content: JSON.stringify(assets.manifest),
|
|
401
|
+
type: "text",
|
|
402
|
+
});
|
|
403
|
+
}
|
|
289
404
|
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
405
|
+
const worker: CfWorkerInit = {
|
|
406
|
+
name: scriptName,
|
|
407
|
+
main: {
|
|
408
|
+
name: path.basename(resolvedEntryPointPath),
|
|
409
|
+
content: content,
|
|
410
|
+
type: bundleType,
|
|
411
|
+
},
|
|
412
|
+
bindings,
|
|
413
|
+
migrations,
|
|
414
|
+
modules,
|
|
415
|
+
compatibility_date: props.compatibilityDate ?? config.compatibility_date,
|
|
416
|
+
compatibility_flags:
|
|
417
|
+
props.compatibilityFlags ?? config.compatibility_flags,
|
|
418
|
+
usage_model: config.usage_model,
|
|
419
|
+
};
|
|
420
|
+
|
|
421
|
+
const withoutStaticAssets = {
|
|
422
|
+
...bindings,
|
|
423
|
+
kv_namespaces: config.kv_namespaces,
|
|
424
|
+
text_blobs: config.text_blobs,
|
|
425
|
+
};
|
|
426
|
+
printBindings(withoutStaticAssets);
|
|
427
|
+
|
|
428
|
+
if (!props.dryRun) {
|
|
429
|
+
// Upload the script so it has time to propagate.
|
|
430
|
+
// We can also now tell whether available_on_subdomain is set
|
|
431
|
+
available_on_subdomain = (
|
|
432
|
+
await fetchResult<{ available_on_subdomain: boolean }>(
|
|
433
|
+
workerUrl,
|
|
434
|
+
{
|
|
435
|
+
method: "PUT",
|
|
436
|
+
body: createWorkerUploadForm(worker),
|
|
437
|
+
},
|
|
438
|
+
new URLSearchParams({
|
|
439
|
+
include_subdomain_availability: "true",
|
|
440
|
+
// pass excludeScript so the whole body of the
|
|
441
|
+
// script doesn't get included in the response
|
|
442
|
+
excludeScript: "true",
|
|
443
|
+
})
|
|
444
|
+
)
|
|
445
|
+
).available_on_subdomain;
|
|
446
|
+
}
|
|
447
|
+
} finally {
|
|
448
|
+
if (typeof destination !== "string") {
|
|
449
|
+
// this means we're using a temp dir,
|
|
450
|
+
// so let's clean up before we proceed
|
|
451
|
+
await destination.cleanup();
|
|
452
|
+
}
|
|
293
453
|
}
|
|
294
454
|
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
// Upload the script so it has time to propagate.
|
|
302
|
-
const { available_on_subdomain } = await fetchResult(
|
|
303
|
-
workerUrl,
|
|
304
|
-
{
|
|
305
|
-
method: "PUT",
|
|
306
|
-
body: toFormData(worker),
|
|
307
|
-
},
|
|
308
|
-
new URLSearchParams({ available_on_subdomains: "true" })
|
|
309
|
-
);
|
|
455
|
+
if (props.dryRun) {
|
|
456
|
+
logger.log(`--dry-run: exiting now.`);
|
|
457
|
+
return;
|
|
458
|
+
}
|
|
459
|
+
assert(accountId, "Missing accountId");
|
|
310
460
|
|
|
311
461
|
const uploadMs = Date.now() - start;
|
|
312
|
-
console.log("Uploaded", workerName, formatTime(uploadMs));
|
|
313
462
|
const deployments: Promise<string[]>[] = [];
|
|
314
463
|
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
464
|
+
if (deployToWorkersDev) {
|
|
465
|
+
// Deploy to a subdomain of `workers.dev`
|
|
466
|
+
const userSubdomain = await getSubdomain(accountId);
|
|
467
|
+
const scriptURL =
|
|
468
|
+
props.legacyEnv || !props.env
|
|
469
|
+
? `${scriptName}.${userSubdomain}.workers.dev`
|
|
470
|
+
: `${envName}.${scriptName}.${userSubdomain}.workers.dev`;
|
|
471
|
+
if (!available_on_subdomain) {
|
|
472
|
+
// Enable the `workers.dev` subdomain.
|
|
473
|
+
deployments.push(
|
|
474
|
+
fetchResult(`${workerUrl}/subdomain`, {
|
|
475
|
+
method: "POST",
|
|
476
|
+
body: JSON.stringify({ enabled: true }),
|
|
477
|
+
headers: {
|
|
478
|
+
"Content-Type": "application/json",
|
|
479
|
+
},
|
|
480
|
+
})
|
|
481
|
+
.then(() => [scriptURL])
|
|
482
|
+
// Add a delay when the subdomain is first created.
|
|
483
|
+
// This is to prevent an issue where a negative cache-hit
|
|
484
|
+
// causes the subdomain to be unavailable for 30 seconds.
|
|
485
|
+
// This is a temporary measure until we fix this on the edge.
|
|
486
|
+
.then(async (url) => {
|
|
487
|
+
await sleep(3000);
|
|
488
|
+
return url;
|
|
489
|
+
})
|
|
490
|
+
);
|
|
491
|
+
} else {
|
|
492
|
+
deployments.push(Promise.resolve([scriptURL]));
|
|
493
|
+
}
|
|
494
|
+
} else {
|
|
495
|
+
if (available_on_subdomain) {
|
|
496
|
+
// Disable the workers.dev deployment
|
|
497
|
+
await fetchResult(`${workerUrl}/subdomain`, {
|
|
331
498
|
method: "POST",
|
|
332
|
-
body: JSON.stringify({ enabled:
|
|
499
|
+
body: JSON.stringify({ enabled: false }),
|
|
333
500
|
headers: {
|
|
334
501
|
"Content-Type": "application/json",
|
|
335
502
|
},
|
|
336
|
-
})
|
|
337
|
-
|
|
338
|
-
// Add a delay when the subdomain is first created.
|
|
339
|
-
// This is to prevent an issue where a negative cache-hit
|
|
340
|
-
// causes the subdomain to be unavailable for 30 seconds.
|
|
341
|
-
// This is a temporary measure until we fix this on the edge.
|
|
342
|
-
.then(async (url) => {
|
|
343
|
-
await sleep(3000);
|
|
344
|
-
return url;
|
|
345
|
-
})
|
|
346
|
-
);
|
|
347
|
-
} else {
|
|
348
|
-
deployments.push(Promise.resolve([scriptURL]));
|
|
503
|
+
});
|
|
504
|
+
}
|
|
349
505
|
}
|
|
350
506
|
|
|
507
|
+
logger.log("Uploaded", workerName, formatTime(uploadMs));
|
|
508
|
+
|
|
351
509
|
// Update routing table for the script.
|
|
352
|
-
if (
|
|
510
|
+
if (routesOnly.length > 0) {
|
|
353
511
|
deployments.push(
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
// and how to configure it.
|
|
358
|
-
method: "PUT",
|
|
359
|
-
body: JSON.stringify(routes.map((pattern) => ({ pattern }))),
|
|
360
|
-
headers: {
|
|
361
|
-
"Content-Type": "application/json",
|
|
362
|
-
},
|
|
363
|
-
}).then(() => {
|
|
364
|
-
if (routes.length > 10) {
|
|
365
|
-
return routes
|
|
512
|
+
publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
|
|
513
|
+
if (routesOnly.length > 10) {
|
|
514
|
+
return routesOnly
|
|
366
515
|
.slice(0, 9)
|
|
367
|
-
.map(
|
|
368
|
-
.concat([`...and ${
|
|
516
|
+
.map((route) => renderRoute(route))
|
|
517
|
+
.concat([`...and ${routesOnly.length - 10} more routes`]);
|
|
369
518
|
}
|
|
370
|
-
return
|
|
519
|
+
return routesOnly.map((route) => renderRoute(route));
|
|
371
520
|
})
|
|
372
521
|
);
|
|
373
522
|
}
|
|
374
523
|
|
|
524
|
+
// Update custom domains for the script
|
|
525
|
+
if (customDomainsOnly.length > 0) {
|
|
526
|
+
deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
|
|
527
|
+
}
|
|
528
|
+
|
|
375
529
|
// Configure any schedules for the script.
|
|
376
530
|
// TODO: rename this to `schedules`?
|
|
377
531
|
if (triggers && triggers.length) {
|
|
378
532
|
deployments.push(
|
|
379
533
|
fetchResult(`${workerUrl}/schedules`, {
|
|
380
|
-
//
|
|
381
|
-
// So technically, this will override any previous schedules.
|
|
382
|
-
// We should change the endpoint to support PATCH.
|
|
534
|
+
// Note: PUT will override previous schedules on this script.
|
|
383
535
|
method: "PUT",
|
|
384
536
|
body: JSON.stringify(triggers.map((cron) => ({ cron }))),
|
|
385
537
|
headers: {
|
|
386
538
|
"Content-Type": "application/json",
|
|
387
539
|
},
|
|
388
|
-
}).then(() => triggers.map(
|
|
540
|
+
}).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
|
|
389
541
|
);
|
|
390
542
|
}
|
|
391
543
|
|
|
392
|
-
if (!deployments.length) {
|
|
393
|
-
return;
|
|
394
|
-
}
|
|
395
|
-
|
|
396
544
|
const targets = await Promise.all(deployments);
|
|
397
545
|
const deployMs = Date.now() - start - uploadMs;
|
|
398
|
-
|
|
399
|
-
|
|
400
|
-
|
|
546
|
+
|
|
547
|
+
if (deployments.length > 0) {
|
|
548
|
+
logger.log("Published", workerName, formatTime(deployMs));
|
|
549
|
+
for (const target of targets.flat()) {
|
|
550
|
+
logger.log(" ", target);
|
|
551
|
+
}
|
|
552
|
+
} else {
|
|
553
|
+
logger.log("No publish targets for", workerName, formatTime(deployMs));
|
|
554
|
+
}
|
|
555
|
+
}
|
|
556
|
+
|
|
557
|
+
function formatTime(duration: number) {
|
|
558
|
+
return `(${(duration / 1000).toFixed(2)} sec)`;
|
|
559
|
+
}
|
|
560
|
+
|
|
561
|
+
async function getSubdomain(accountId: string): Promise<string> {
|
|
562
|
+
try {
|
|
563
|
+
const { subdomain } = await fetchResult(
|
|
564
|
+
`/accounts/${accountId}/workers/subdomain`
|
|
565
|
+
);
|
|
566
|
+
return subdomain;
|
|
567
|
+
} catch (e) {
|
|
568
|
+
const error = e as { code?: number };
|
|
569
|
+
if (typeof error === "object" && !!error && error.code === 10007) {
|
|
570
|
+
// 10007 error code: not found
|
|
571
|
+
// https://api.cloudflare.com/#worker-subdomain-get-subdomain
|
|
572
|
+
|
|
573
|
+
const errorMessage =
|
|
574
|
+
"Error: You need to register a workers.dev subdomain before publishing to workers.dev";
|
|
575
|
+
const solutionMessage =
|
|
576
|
+
"You can either publish your worker to one or more routes by specifying them in wrangler.toml, or register a workers.dev subdomain here:";
|
|
577
|
+
const onboardingLink = `https://dash.cloudflare.com/${accountId}/workers/onboarding`;
|
|
578
|
+
|
|
579
|
+
throw new Error(`${errorMessage}\n${solutionMessage}\n${onboardingLink}`);
|
|
580
|
+
} else {
|
|
581
|
+
throw e;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
}
|
|
585
|
+
|
|
586
|
+
/**
|
|
587
|
+
* Associate the newly deployed Worker with the given routes.
|
|
588
|
+
*/
|
|
589
|
+
async function publishRoutes(
|
|
590
|
+
routes: Route[],
|
|
591
|
+
{
|
|
592
|
+
workerUrl,
|
|
593
|
+
scriptName,
|
|
594
|
+
notProd,
|
|
595
|
+
}: { workerUrl: string; scriptName: string; notProd: boolean }
|
|
596
|
+
): Promise<string[]> {
|
|
597
|
+
try {
|
|
598
|
+
return await fetchResult(`${workerUrl}/routes`, {
|
|
599
|
+
// Note: PUT will delete previous routes on this script.
|
|
600
|
+
method: "PUT",
|
|
601
|
+
body: JSON.stringify(
|
|
602
|
+
routes.map((route) =>
|
|
603
|
+
typeof route !== "object" ? { pattern: route } : route
|
|
604
|
+
)
|
|
605
|
+
),
|
|
606
|
+
headers: {
|
|
607
|
+
"Content-Type": "application/json",
|
|
608
|
+
},
|
|
609
|
+
});
|
|
610
|
+
} catch (e) {
|
|
611
|
+
if (isAuthenticationError(e)) {
|
|
612
|
+
// An authentication error is probably due to a known issue,
|
|
613
|
+
// where the user is logged in via an API token that does not have "All Zones".
|
|
614
|
+
return await publishRoutesFallback(routes, { scriptName, notProd });
|
|
615
|
+
} else {
|
|
616
|
+
throw e;
|
|
617
|
+
}
|
|
401
618
|
}
|
|
402
619
|
}
|
|
403
620
|
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
621
|
+
/**
|
|
622
|
+
* Try updating routes for the Worker using a less optimal zone-based API.
|
|
623
|
+
*
|
|
624
|
+
* Compute match zones to the routes, then for each route attempt to connect it to the Worker via the zone.
|
|
625
|
+
*/
|
|
626
|
+
async function publishRoutesFallback(
|
|
627
|
+
routes: Route[],
|
|
628
|
+
{ scriptName, notProd }: { scriptName: string; notProd: boolean }
|
|
629
|
+
) {
|
|
630
|
+
if (notProd) {
|
|
631
|
+
throw new Error(
|
|
632
|
+
"Service environments combined with an API token that doesn't have 'All Zones' permissions is not supported.\n" +
|
|
633
|
+
"Either turn off service environments by setting `legacy_env = true`, creating an API token with 'All Zones' permissions, or logging in via OAuth"
|
|
634
|
+
);
|
|
635
|
+
}
|
|
636
|
+
logger.warn(
|
|
637
|
+
"The current authentication token does not have 'All Zones' permissions.\n" +
|
|
638
|
+
"Falling back to using the zone-based API endpoint to update each route individually.\n" +
|
|
639
|
+
"Note that there is no access to routes associated with zones that the API token does not have permission for.\n" +
|
|
640
|
+
"Existing routes for this Worker in such zones will not be deleted."
|
|
641
|
+
);
|
|
642
|
+
|
|
643
|
+
const deployedRoutes: string[] = [];
|
|
644
|
+
|
|
645
|
+
// Collect the routes (and their zones) that will be deployed.
|
|
646
|
+
const activeZones = new Map<string, string>();
|
|
647
|
+
const routesToDeploy = new Map<string, string>();
|
|
648
|
+
for (const route of routes) {
|
|
649
|
+
const zone = await getZoneForRoute(route);
|
|
650
|
+
if (zone) {
|
|
651
|
+
activeZones.set(zone.id, zone.host);
|
|
652
|
+
routesToDeploy.set(
|
|
653
|
+
typeof route === "string" ? route : route.pattern,
|
|
654
|
+
zone.id
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
}
|
|
658
|
+
|
|
659
|
+
// Collect the routes that are already deployed.
|
|
660
|
+
const allRoutes = new Map<string, string>();
|
|
661
|
+
const alreadyDeployedRoutes = new Set<string>();
|
|
662
|
+
for (const [zone, host] of activeZones) {
|
|
663
|
+
try {
|
|
664
|
+
for (const { pattern, script } of await fetchListResult<{
|
|
665
|
+
pattern: string;
|
|
666
|
+
script: string;
|
|
667
|
+
}>(`/zones/${zone}/workers/routes`)) {
|
|
668
|
+
allRoutes.set(pattern, script);
|
|
669
|
+
if (script === scriptName) {
|
|
670
|
+
alreadyDeployedRoutes.add(pattern);
|
|
671
|
+
}
|
|
672
|
+
}
|
|
673
|
+
} catch (e) {
|
|
674
|
+
if (isAuthenticationError(e)) {
|
|
675
|
+
e.notes.push({
|
|
676
|
+
text: `This could be because the API token being used does not have permission to access the zone "${host}" (${zone}).`,
|
|
677
|
+
});
|
|
678
|
+
}
|
|
679
|
+
throw e;
|
|
680
|
+
}
|
|
681
|
+
}
|
|
682
|
+
|
|
683
|
+
// Deploy each route that is not already deployed.
|
|
684
|
+
for (const [routePattern, zoneId] of routesToDeploy.entries()) {
|
|
685
|
+
if (allRoutes.has(routePattern)) {
|
|
686
|
+
const knownScript = allRoutes.get(routePattern);
|
|
687
|
+
if (knownScript === scriptName) {
|
|
688
|
+
// This route is already associated with this worker, so no need to hit the API.
|
|
689
|
+
alreadyDeployedRoutes.delete(routePattern);
|
|
690
|
+
continue;
|
|
691
|
+
} else {
|
|
692
|
+
throw new Error(
|
|
693
|
+
`The route with pattern "${routePattern}" is already associated with another worker called "${knownScript}".`
|
|
694
|
+
);
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const { pattern } = await fetchResult(`/zones/${zoneId}/workers/routes`, {
|
|
699
|
+
method: "POST",
|
|
700
|
+
body: JSON.stringify({
|
|
701
|
+
pattern: routePattern,
|
|
702
|
+
script: scriptName,
|
|
703
|
+
}),
|
|
704
|
+
headers: {
|
|
705
|
+
"Content-Type": "application/json",
|
|
706
|
+
},
|
|
707
|
+
});
|
|
708
|
+
|
|
709
|
+
deployedRoutes.push(pattern);
|
|
710
|
+
}
|
|
711
|
+
|
|
712
|
+
if (alreadyDeployedRoutes.size) {
|
|
713
|
+
logger.warn(
|
|
714
|
+
"Previously deployed routes:\n" +
|
|
715
|
+
"The following routes were already associated with this worker, and have not been deleted:\n" +
|
|
716
|
+
[...alreadyDeployedRoutes.values()].map((route) => ` - "${route}"\n`) +
|
|
717
|
+
"If these routes are not wanted then you can remove them in the dashboard."
|
|
718
|
+
);
|
|
719
|
+
}
|
|
720
|
+
|
|
721
|
+
return deployedRoutes;
|
|
408
722
|
}
|
|
409
723
|
|
|
410
|
-
|
|
724
|
+
function isAuthenticationError(e: unknown): e is ParseError {
|
|
725
|
+
return e instanceof ParseError && (e as { code?: number }).code === 10000;
|
|
726
|
+
}
|