wrangler 0.0.0-e1b8ac4 → 0.0.0-e1c2f5b9

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 (295) hide show
  1. package/README.md +23 -3
  2. package/bin/wrangler.js +170 -62
  3. package/miniflare-dist/index.mjs +1499 -21
  4. package/package.json +193 -156
  5. package/src/__tests__/access.test.ts +25 -0
  6. package/src/__tests__/api-dev.test.ts +238 -0
  7. package/src/__tests__/api-devregistry.test.js +64 -0
  8. package/src/__tests__/api.test.ts +80 -0
  9. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  10. package/src/__tests__/config-cache.test.ts +30 -24
  11. package/src/__tests__/configuration.test.ts +4152 -3537
  12. package/src/__tests__/d1.test.ts +123 -0
  13. package/src/__tests__/delete.test.ts +263 -0
  14. package/src/__tests__/deployments.test.ts +105 -0
  15. package/src/__tests__/dev.test.tsx +1559 -1028
  16. package/src/__tests__/dialogs.test.tsx +40 -0
  17. package/src/__tests__/generate.test.ts +235 -0
  18. package/src/__tests__/get-host-from-url.test.ts +16 -0
  19. package/src/__tests__/guess-worker-format.test.ts +68 -68
  20. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  21. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  22. package/src/__tests__/helpers/mock-auth-domain.ts +20 -0
  23. package/src/__tests__/helpers/mock-bin.ts +20 -20
  24. package/src/__tests__/helpers/mock-cfetch.ts +165 -99
  25. package/src/__tests__/helpers/mock-console.ts +58 -39
  26. package/src/__tests__/helpers/mock-dialogs.ts +94 -94
  27. package/src/__tests__/helpers/mock-get-zone-from-host.ts +8 -0
  28. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  29. package/src/__tests__/helpers/mock-istty.ts +65 -18
  30. package/src/__tests__/helpers/mock-known-routes.ts +7 -0
  31. package/src/__tests__/helpers/mock-kv.ts +27 -27
  32. package/src/__tests__/helpers/mock-oauth-flow.ts +244 -228
  33. package/src/__tests__/helpers/mock-process.ts +23 -13
  34. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  35. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  36. package/src/__tests__/helpers/msw/handlers/access.ts +13 -0
  37. package/src/__tests__/helpers/msw/handlers/deployments.ts +59 -0
  38. package/src/__tests__/helpers/msw/handlers/namespaces.ts +104 -0
  39. package/src/__tests__/helpers/msw/handlers/oauth.ts +31 -0
  40. package/src/__tests__/helpers/msw/handlers/r2.ts +80 -0
  41. package/src/__tests__/helpers/msw/handlers/script.ts +75 -0
  42. package/src/__tests__/helpers/msw/handlers/user.ts +63 -0
  43. package/src/__tests__/helpers/msw/handlers/zones.ts +22 -0
  44. package/src/__tests__/helpers/msw/index.ts +21 -0
  45. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  46. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  47. package/src/__tests__/helpers/worker-scripts/child-wrangler.toml +1 -0
  48. package/src/__tests__/helpers/worker-scripts/hello-world-worker.js +5 -0
  49. package/src/__tests__/helpers/worker-scripts/hello-world-wrangler.toml +1 -0
  50. package/src/__tests__/helpers/worker-scripts/parent-worker.js +8 -0
  51. package/src/__tests__/helpers/worker-scripts/parent-wrangler.toml +5 -0
  52. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  53. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  54. package/src/__tests__/https-options.test.ts +142 -109
  55. package/src/__tests__/index.test.ts +245 -234
  56. package/src/__tests__/init.test.ts +3027 -1925
  57. package/src/__tests__/jest.setup.ts +157 -61
  58. package/src/__tests__/kv.test.ts +1773 -1507
  59. package/src/__tests__/logger.test.ts +96 -96
  60. package/src/__tests__/logout.test.ts +47 -0
  61. package/src/__tests__/metrics.test.ts +495 -0
  62. package/src/__tests__/middleware.scheduled.test.ts +145 -0
  63. package/src/__tests__/middleware.test.ts +750 -0
  64. package/src/__tests__/package-manager.test.ts +303 -303
  65. package/src/__tests__/pages-deployment-tail.test.ts +884 -0
  66. package/src/__tests__/pages.test.ts +2424 -735
  67. package/src/__tests__/parse.test.ts +252 -252
  68. package/src/__tests__/paths.test.ts +39 -0
  69. package/src/__tests__/publish.test.ts +7621 -5798
  70. package/src/__tests__/pubsub.test.ts +490 -0
  71. package/src/__tests__/queues.test.ts +522 -0
  72. package/src/__tests__/r2.test.ts +388 -228
  73. package/src/__tests__/route.test.ts +18 -18
  74. package/src/__tests__/secret.test.ts +673 -460
  75. package/src/__tests__/tail.test.ts +776 -567
  76. package/src/__tests__/test-old-node-version.js +31 -0
  77. package/src/__tests__/tsconfig-sanity.ts +12 -0
  78. package/src/__tests__/tsconfig.json +8 -0
  79. package/src/__tests__/tsconfig.tsbuildinfo +1 -0
  80. package/src/__tests__/type-generation.test.ts +233 -0
  81. package/src/__tests__/user.test.ts +117 -120
  82. package/src/__tests__/utils-collectKeyValues.test.ts +47 -0
  83. package/src/__tests__/validate-dev-props.test.ts +56 -0
  84. package/src/__tests__/version.test.ts +35 -0
  85. package/src/__tests__/whoami.test.tsx +264 -125
  86. package/src/__tests__/worker-namespace.test.ts +326 -0
  87. package/src/abort.d.ts +1 -1
  88. package/src/api/dev.ts +218 -0
  89. package/src/api/index.ts +2 -0
  90. package/src/bundle-reporter.tsx +68 -0
  91. package/src/bundle.ts +785 -166
  92. package/src/cfetch/index.ts +120 -83
  93. package/src/cfetch/internal.ts +211 -92
  94. package/src/cli.ts +23 -8
  95. package/src/config/config.ts +236 -204
  96. package/src/config/diagnostics.ts +61 -61
  97. package/src/config/environment.ts +514 -357
  98. package/src/config/index.ts +326 -193
  99. package/src/config/validation-helpers.ts +379 -366
  100. package/src/config/validation.ts +1973 -1402
  101. package/src/config-cache.ts +81 -41
  102. package/src/create-worker-preview.ts +239 -142
  103. package/src/create-worker-upload-form.ts +309 -238
  104. package/src/d1/backups.tsx +223 -0
  105. package/src/d1/constants.ts +2 -0
  106. package/src/d1/create.tsx +63 -0
  107. package/src/d1/delete.tsx +56 -0
  108. package/src/d1/execute.tsx +352 -0
  109. package/src/d1/formatTimeAgo.ts +14 -0
  110. package/src/d1/index.ts +101 -0
  111. package/src/d1/list.tsx +48 -0
  112. package/src/d1/migrations/apply.tsx +196 -0
  113. package/src/d1/migrations/create.tsx +77 -0
  114. package/src/d1/migrations/helpers.ts +147 -0
  115. package/src/d1/migrations/index.tsx +3 -0
  116. package/src/d1/migrations/list.tsx +79 -0
  117. package/src/d1/migrations/options.ts +18 -0
  118. package/src/d1/options.ts +22 -0
  119. package/src/d1/types.tsx +24 -0
  120. package/src/d1/utils.ts +48 -0
  121. package/src/delete.ts +108 -0
  122. package/src/deployments.ts +83 -0
  123. package/src/deprecated/index.ts +145 -0
  124. package/src/dev/dev-vars.ts +20 -17
  125. package/src/dev/dev.tsx +544 -329
  126. package/src/dev/get-local-persistence-path.tsx +31 -0
  127. package/src/dev/local.tsx +912 -301
  128. package/src/dev/remote.tsx +591 -230
  129. package/src/dev/start-server.ts +543 -0
  130. package/src/dev/use-esbuild.ts +183 -91
  131. package/src/dev/validate-dev-props.ts +31 -0
  132. package/src/dev-registry.tsx +201 -0
  133. package/src/dev.tsx +949 -0
  134. package/src/dialogs.tsx +132 -99
  135. package/src/dispatch-namespace.ts +207 -0
  136. package/src/docs/index.ts +97 -0
  137. package/src/durable.ts +87 -87
  138. package/src/entry.ts +235 -228
  139. package/src/environment-variables/factory.ts +88 -0
  140. package/src/environment-variables/misc-variables.ts +30 -0
  141. package/src/errors.ts +6 -6
  142. package/src/generate/index.ts +300 -0
  143. package/src/git-client.ts +135 -0
  144. package/src/global-wrangler-config-path.ts +26 -0
  145. package/src/https-options.ts +84 -80
  146. package/src/index.tsx +637 -2850
  147. package/src/init.ts +1025 -0
  148. package/src/inspect.ts +698 -593
  149. package/src/intl-polyfill.d.ts +123 -123
  150. package/src/is-ci.ts +14 -0
  151. package/src/is-interactive.ts +16 -0
  152. package/src/jest.d.ts +4 -0
  153. package/src/kv/helpers.ts +430 -0
  154. package/src/kv/index.ts +596 -0
  155. package/src/logger.ts +64 -45
  156. package/src/metrics/index.ts +5 -0
  157. package/src/metrics/metrics-config.ts +239 -0
  158. package/src/metrics/metrics-dispatcher.ts +96 -0
  159. package/src/metrics/metrics-usage-headers.ts +24 -0
  160. package/src/metrics/send-event.ts +97 -0
  161. package/src/miniflare-cli/assets.ts +250 -0
  162. package/src/miniflare-cli/index.ts +202 -33
  163. package/src/miniflare-cli/request-context.ts +18 -18
  164. package/src/miniflare-cli/tsconfig.json +9 -0
  165. package/src/miniflare-cli/tsconfig.tsbuildinfo +1 -0
  166. package/src/miniflare-cli/types.ts +11 -0
  167. package/src/module-collection.ts +221 -212
  168. package/src/open-in-browser.ts +4 -4
  169. package/src/package-manager.ts +173 -128
  170. package/src/pages/build.tsx +270 -0
  171. package/src/pages/constants.ts +18 -0
  172. package/src/pages/deployment-tails.tsx +284 -0
  173. package/src/pages/deployments.tsx +84 -0
  174. package/src/pages/dev.tsx +710 -0
  175. package/src/pages/errors.ts +66 -0
  176. package/src/pages/functions/buildPlugin.ts +107 -0
  177. package/src/pages/functions/buildWorker.ts +166 -0
  178. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  179. package/src/pages/functions/filepath-routing.ts +189 -0
  180. package/src/pages/functions/identifiers.ts +78 -0
  181. package/src/pages/functions/routes-consolidation.test.ts +250 -0
  182. package/src/pages/functions/routes-consolidation.ts +73 -0
  183. package/src/pages/functions/routes-transformation.test.ts +282 -0
  184. package/src/pages/functions/routes-transformation.ts +115 -0
  185. package/src/pages/functions/routes-validation.test.ts +403 -0
  186. package/src/pages/functions/routes-validation.ts +202 -0
  187. package/src/pages/functions/routes.ts +151 -0
  188. package/src/pages/functions/tsconfig.json +8 -0
  189. package/src/pages/functions/tsconfig.tsbuildinfo +1 -0
  190. package/src/pages/functions.tsx +82 -0
  191. package/src/pages/hash.tsx +13 -0
  192. package/src/pages/index.tsx +102 -0
  193. package/src/pages/projects.tsx +169 -0
  194. package/src/pages/prompt-select-project.tsx +31 -0
  195. package/src/pages/publish.tsx +461 -0
  196. package/src/pages/types.ts +41 -0
  197. package/src/pages/upload.tsx +447 -0
  198. package/src/pages/utils.ts +23 -0
  199. package/src/parse.ts +202 -138
  200. package/src/paths.ts +53 -8
  201. package/src/proxy.ts +623 -405
  202. package/src/publish/index.ts +270 -0
  203. package/src/publish/publish.ts +1036 -0
  204. package/src/pubsub/index.ts +286 -0
  205. package/src/pubsub/pubsub-commands.tsx +624 -0
  206. package/src/queues/cli/commands/consumer/add.ts +71 -0
  207. package/src/queues/cli/commands/consumer/index.ts +22 -0
  208. package/src/queues/cli/commands/consumer/remove.ts +38 -0
  209. package/src/queues/cli/commands/create.ts +25 -0
  210. package/src/queues/cli/commands/delete.ts +26 -0
  211. package/src/queues/cli/commands/index.ts +36 -0
  212. package/src/queues/cli/commands/list.ts +25 -0
  213. package/src/queues/client.ts +135 -0
  214. package/src/queues/utils.ts +18 -0
  215. package/src/r2/constants.ts +4 -0
  216. package/src/r2/helpers.ts +131 -0
  217. package/src/r2/index.ts +289 -0
  218. package/src/routes.ts +140 -0
  219. package/src/secret/index.ts +379 -0
  220. package/src/selfsigned.d.ts +23 -23
  221. package/src/sites.tsx +258 -254
  222. package/src/tail/createTail.ts +379 -0
  223. package/src/tail/filters.ts +108 -110
  224. package/src/tail/index.ts +211 -296
  225. package/src/tail/printing.ts +86 -46
  226. package/src/tsconfig-sanity.ts +16 -0
  227. package/src/type-generation.ts +181 -0
  228. package/src/update-check.ts +11 -11
  229. package/src/user/access.ts +68 -0
  230. package/src/user/auth-variables.ts +113 -0
  231. package/src/user/choose-account.tsx +69 -0
  232. package/src/user/generate-auth-url.ts +33 -0
  233. package/src/user/generate-random-state.ts +16 -0
  234. package/src/user/index.ts +2 -0
  235. package/src/user/user.tsx +1238 -0
  236. package/src/utils/collectKeyValues.ts +14 -0
  237. package/src/whoami.tsx +141 -43
  238. package/src/worker.ts +177 -107
  239. package/src/yargs-types.ts +24 -0
  240. package/src/zones.ts +158 -40
  241. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  242. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  243. package/templates/__tests__/tsconfig.json +8 -0
  244. package/templates/__tests__/tsconfig.tsbuildinfo +1 -0
  245. package/templates/checked-fetch.js +17 -0
  246. package/templates/d1-beta-facade.js +205 -0
  247. package/templates/facade.d.ts +14 -0
  248. package/templates/first-party-worker-module-facade.ts +19 -0
  249. package/templates/format-dev-errors.ts +33 -0
  250. package/templates/init-tests/test-jest-new-worker.js +23 -0
  251. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  252. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  253. package/templates/middleware/common.ts +62 -0
  254. package/templates/middleware/loader-modules.ts +82 -0
  255. package/templates/middleware/loader-sw.ts +233 -0
  256. package/templates/middleware/middleware-miniflare3-json-error.ts +20 -0
  257. package/templates/middleware/middleware-pretty-error.ts +40 -0
  258. package/templates/middleware/middleware-scheduled.ts +15 -0
  259. package/templates/new-worker-scheduled.js +3 -3
  260. package/templates/new-worker-scheduled.ts +15 -15
  261. package/templates/new-worker.js +3 -3
  262. package/templates/new-worker.ts +15 -15
  263. package/templates/no-op-worker.js +10 -0
  264. package/templates/pages-dev-pipeline.ts +31 -0
  265. package/templates/pages-dev-util.ts +52 -0
  266. package/templates/pages-shim.ts +12 -0
  267. package/templates/pages-template-plugin.ts +171 -0
  268. package/templates/pages-template-worker.ts +189 -0
  269. package/templates/serve-static-assets.ts +65 -0
  270. package/templates/service-bindings-module-facade.js +54 -0
  271. package/templates/service-bindings-sw-facade.js +42 -0
  272. package/templates/tsconfig-sanity.ts +11 -0
  273. package/templates/tsconfig.init.json +106 -0
  274. package/templates/tsconfig.json +6 -103
  275. package/templates/tsconfig.tsbuildinfo +1 -0
  276. package/wrangler-dist/cli.d.ts +906 -0
  277. package/wrangler-dist/cli.js +147920 -108883
  278. package/pages/functions/buildPlugin.ts +0 -105
  279. package/pages/functions/buildWorker.ts +0 -151
  280. package/pages/functions/filepath-routing.ts +0 -189
  281. package/pages/functions/identifiers.ts +0 -78
  282. package/pages/functions/routes.ts +0 -156
  283. package/pages/functions/template-plugin.ts +0 -147
  284. package/pages/functions/template-worker.ts +0 -143
  285. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  286. package/src/environment-variables.ts +0 -35
  287. package/src/generate-auth-url.ts +0 -33
  288. package/src/generate-random-state.ts +0 -16
  289. package/src/kv.ts +0 -408
  290. package/src/miniflare-cli/enum-keys.ts +0 -17
  291. package/src/pages.tsx +0 -2093
  292. package/src/publish.ts +0 -726
  293. package/src/r2.ts +0 -50
  294. package/src/user.tsx +0 -1202
  295. package/templates/static-asset-facade.js +0 -43
package/src/publish.ts DELETED
@@ -1,726 +0,0 @@
1
- import assert from "node:assert";
2
- import { mkdirSync, readFileSync, writeFileSync } from "node:fs";
3
- import path from "node:path";
4
- import { URLSearchParams } from "node:url";
5
- import tmp from "tmp-promise";
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";
14
- import { syncAssets } from "./sites";
15
- import { getZoneForRoute } from "./zones";
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";
24
- import type { AssetPaths } from "./sites";
25
- import type { CfWorkerInit } from "./worker";
26
-
27
- type Props = {
28
- config: Config;
29
- accountId: string | undefined;
30
- entry: Entry;
31
- rules: Config["rules"];
32
- name: string | undefined;
33
- env: string | undefined;
34
- compatibilityDate: string | undefined;
35
- compatibilityFlags: string[] | undefined;
36
- assetPaths: AssetPaths | undefined;
37
- triggers: string[] | undefined;
38
- routes: string[] | undefined;
39
- legacyEnv: boolean | undefined;
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;
48
- };
49
-
50
- type RouteObject = ZoneIdRoute | ZoneNameRoute | CustomDomainRoute;
51
-
52
- function sleep(ms: number) {
53
- return new Promise((resolve) => setTimeout(resolve, ms));
54
- }
55
-
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
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
- }
76
- }
77
- return result;
78
- }
79
-
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
- }
93
-
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
101
- );
102
- }
103
-
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;
153
- }
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
-
231
- const triggers = props.triggers || config.triggers?.crons;
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;
256
-
257
- const jsxFactory = props.jsxFactory || config.jsx_factory;
258
- const jsxFragment = props.jsxFragment || config.jsx_fragment;
259
-
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
- }
268
-
269
- const scriptName = props.name;
270
- assert(
271
- scriptName,
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>"`'
273
- );
274
-
275
- assert(
276
- !config.site || config.site.bucket,
277
- "A [site] definition requires a `bucket` field with a path to the site's assets directory."
278
- );
279
-
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
- );
290
- }
291
-
292
- const destination = props.outDir ?? (await tmp.dir({ unsafeCleanup: true }));
293
- const envName = props.env ?? "production";
294
-
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}`;
301
-
302
- let available_on_subdomain; // we'll set this later
303
-
304
- const { format } = props.entry;
305
-
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
- );
314
- }
315
-
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
- }
321
-
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"
325
- );
326
- }
327
-
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
- );
348
-
349
- const content = readFileSync(resolvedEntryPointPath, {
350
- encoding: "utf-8",
351
- });
352
-
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
- );
374
-
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
- }
404
-
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
- }
453
- }
454
-
455
- if (props.dryRun) {
456
- logger.log(`--dry-run: exiting now.`);
457
- return;
458
- }
459
- assert(accountId, "Missing accountId");
460
-
461
- const uploadMs = Date.now() - start;
462
- const deployments: Promise<string[]>[] = [];
463
-
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`, {
498
- method: "POST",
499
- body: JSON.stringify({ enabled: false }),
500
- headers: {
501
- "Content-Type": "application/json",
502
- },
503
- });
504
- }
505
- }
506
-
507
- logger.log("Uploaded", workerName, formatTime(uploadMs));
508
-
509
- // Update routing table for the script.
510
- if (routesOnly.length > 0) {
511
- deployments.push(
512
- publishRoutes(routesOnly, { workerUrl, scriptName, notProd }).then(() => {
513
- if (routesOnly.length > 10) {
514
- return routesOnly
515
- .slice(0, 9)
516
- .map((route) => renderRoute(route))
517
- .concat([`...and ${routesOnly.length - 10} more routes`]);
518
- }
519
- return routesOnly.map((route) => renderRoute(route));
520
- })
521
- );
522
- }
523
-
524
- // Update custom domains for the script
525
- if (customDomainsOnly.length > 0) {
526
- deployments.push(publishCustomDomains(workerUrl, customDomainsOnly));
527
- }
528
-
529
- // Configure any schedules for the script.
530
- // TODO: rename this to `schedules`?
531
- if (triggers && triggers.length) {
532
- deployments.push(
533
- fetchResult(`${workerUrl}/schedules`, {
534
- // Note: PUT will override previous schedules on this script.
535
- method: "PUT",
536
- body: JSON.stringify(triggers.map((cron) => ({ cron }))),
537
- headers: {
538
- "Content-Type": "application/json",
539
- },
540
- }).then(() => triggers.map((trigger) => `schedule: ${trigger}`))
541
- );
542
- }
543
-
544
- const targets = await Promise.all(deployments);
545
- const deployMs = Date.now() - start - uploadMs;
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
- }
618
- }
619
- }
620
-
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;
722
- }
723
-
724
- function isAuthenticationError(e: unknown): e is ParseError {
725
- return e instanceof ParseError && (e as { code?: number }).code === 10000;
726
- }