wrangler 0.0.0-e978986 → 0.0.0-e9e9872

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 (186) hide show
  1. package/README.md +7 -1
  2. package/bin/wrangler.js +114 -57
  3. package/kv-asset-handler.js +1 -0
  4. package/miniflare-dist/index.mjs +10 -2
  5. package/package.json +159 -152
  6. package/src/__tests__/config-cache-without-cache-dir.test.ts +38 -0
  7. package/src/__tests__/config-cache.test.ts +30 -24
  8. package/src/__tests__/configuration.test.ts +3935 -3363
  9. package/src/__tests__/dev.test.tsx +1128 -949
  10. package/src/__tests__/guess-worker-format.test.ts +68 -68
  11. package/src/__tests__/helpers/cmd-shim.d.ts +6 -6
  12. package/src/__tests__/helpers/mock-account-id.ts +24 -24
  13. package/src/__tests__/helpers/mock-bin.ts +20 -20
  14. package/src/__tests__/helpers/mock-cfetch.ts +92 -92
  15. package/src/__tests__/helpers/mock-console.ts +49 -39
  16. package/src/__tests__/helpers/mock-dialogs.ts +94 -71
  17. package/src/__tests__/helpers/mock-http-server.ts +30 -30
  18. package/src/__tests__/helpers/mock-istty.ts +65 -18
  19. package/src/__tests__/helpers/mock-kv.ts +26 -26
  20. package/src/__tests__/helpers/mock-oauth-flow.ts +223 -228
  21. package/src/__tests__/helpers/mock-process.ts +39 -0
  22. package/src/__tests__/helpers/mock-stdin.ts +82 -77
  23. package/src/__tests__/helpers/mock-web-socket.ts +21 -21
  24. package/src/__tests__/helpers/run-in-tmp.ts +27 -28
  25. package/src/__tests__/helpers/run-wrangler.ts +8 -8
  26. package/src/__tests__/helpers/write-worker-source.ts +16 -16
  27. package/src/__tests__/helpers/write-wrangler-toml.ts +9 -9
  28. package/src/__tests__/https-options.test.ts +142 -109
  29. package/src/__tests__/index.test.ts +239 -233
  30. package/src/__tests__/init.test.ts +1605 -1180
  31. package/src/__tests__/jest.setup.ts +76 -33
  32. package/src/__tests__/kv.test.ts +1160 -991
  33. package/src/__tests__/logger.test.ts +100 -74
  34. package/src/__tests__/package-manager.test.ts +303 -303
  35. package/src/__tests__/pages.test.ts +1160 -563
  36. package/src/__tests__/parse.test.ts +252 -252
  37. package/src/__tests__/publish.test.ts +6426 -5299
  38. package/src/__tests__/pubsub.test.ts +367 -0
  39. package/src/__tests__/r2.test.ts +133 -133
  40. package/src/__tests__/route.test.ts +18 -18
  41. package/src/__tests__/secret.test.ts +470 -459
  42. package/src/__tests__/tail.test.ts +538 -530
  43. package/src/__tests__/user.test.ts +124 -112
  44. package/src/__tests__/whoami.test.tsx +208 -83
  45. package/src/__tests__/worker-namespace.test.ts +327 -0
  46. package/src/abort.d.ts +1 -1
  47. package/src/api/dev.ts +52 -0
  48. package/src/api/index.ts +1 -0
  49. package/src/bundle-reporter.tsx +29 -0
  50. package/src/bundle.ts +158 -146
  51. package/src/cfetch/index.ts +80 -80
  52. package/src/cfetch/internal.ts +92 -88
  53. package/src/cli.ts +21 -7
  54. package/src/config/config.ts +204 -195
  55. package/src/config/diagnostics.ts +61 -61
  56. package/src/config/environment.ts +390 -357
  57. package/src/config/index.ts +206 -193
  58. package/src/config/validation-helpers.ts +366 -357
  59. package/src/config/validation.ts +1573 -1367
  60. package/src/config-cache.ts +79 -41
  61. package/src/create-worker-preview.ts +206 -136
  62. package/src/create-worker-upload-form.ts +247 -238
  63. package/src/dev/dev-vars.ts +13 -13
  64. package/src/dev/dev.tsx +334 -336
  65. package/src/dev/local.tsx +310 -274
  66. package/src/dev/remote.tsx +366 -211
  67. package/src/dev/use-esbuild.ts +126 -94
  68. package/src/dev.tsx +538 -0
  69. package/src/dialogs.tsx +97 -97
  70. package/src/durable.ts +87 -87
  71. package/src/entry.ts +234 -228
  72. package/src/environment-variables.ts +23 -23
  73. package/src/errors.ts +6 -6
  74. package/src/faye-websocket.d.ts +6 -0
  75. package/src/generate.ts +33 -0
  76. package/src/git-client.ts +42 -0
  77. package/src/global-wrangler-config-path.ts +26 -0
  78. package/src/https-options.ts +84 -80
  79. package/src/index.tsx +1800 -2752
  80. package/src/init.ts +549 -0
  81. package/src/inspect.ts +593 -593
  82. package/src/intl-polyfill.d.ts +123 -123
  83. package/src/is-interactive.ts +12 -0
  84. package/src/kv.ts +299 -277
  85. package/src/logger.ts +46 -39
  86. package/src/miniflare-cli/enum-keys.ts +8 -8
  87. package/src/miniflare-cli/index.ts +43 -31
  88. package/src/miniflare-cli/request-context.ts +18 -18
  89. package/src/module-collection.ts +212 -212
  90. package/src/open-in-browser.ts +4 -6
  91. package/src/package-manager.ts +173 -128
  92. package/src/pages/build.tsx +202 -0
  93. package/src/pages/constants.ts +7 -0
  94. package/src/pages/deployments.tsx +101 -0
  95. package/src/pages/dev.tsx +964 -0
  96. package/src/pages/functions/buildPlugin.ts +105 -0
  97. package/src/pages/functions/buildWorker.ts +151 -0
  98. package/{pages → src/pages}/functions/filepath-routing.test.ts +113 -113
  99. package/src/pages/functions/filepath-routing.ts +189 -0
  100. package/src/pages/functions/identifiers.ts +78 -0
  101. package/src/pages/functions/routes.ts +151 -0
  102. package/src/pages/index.tsx +84 -0
  103. package/src/pages/projects.tsx +157 -0
  104. package/src/pages/publish.tsx +335 -0
  105. package/src/pages/types.ts +40 -0
  106. package/src/pages/upload.tsx +396 -0
  107. package/src/pages/utils.ts +12 -0
  108. package/src/parse.ts +209 -125
  109. package/src/paths.ts +6 -6
  110. package/src/preview.ts +31 -0
  111. package/src/proxy.ts +400 -389
  112. package/src/publish.ts +702 -505
  113. package/src/pubsub/index.ts +286 -0
  114. package/src/pubsub/pubsub-commands.tsx +577 -0
  115. package/src/r2.ts +19 -19
  116. package/src/selfsigned.d.ts +23 -23
  117. package/src/sites.tsx +278 -201
  118. package/src/tail/filters.ts +108 -108
  119. package/src/tail/index.ts +217 -217
  120. package/src/tail/printing.ts +45 -45
  121. package/src/update-check.ts +11 -11
  122. package/src/user/choose-account.tsx +60 -0
  123. package/src/user/env-vars.ts +46 -0
  124. package/src/user/generate-auth-url.ts +33 -0
  125. package/src/user/generate-random-state.ts +16 -0
  126. package/src/user/index.ts +3 -0
  127. package/src/user/user.tsx +1170 -0
  128. package/src/whoami.tsx +61 -41
  129. package/src/worker-namespace.ts +190 -0
  130. package/src/worker.ts +110 -99
  131. package/src/zones.ts +76 -0
  132. package/templates/checked-fetch.js +17 -0
  133. package/templates/new-worker-scheduled.js +4 -4
  134. package/templates/new-worker-scheduled.ts +16 -16
  135. package/templates/new-worker.js +3 -3
  136. package/templates/new-worker.ts +15 -15
  137. package/templates/no-op-worker.js +10 -0
  138. package/templates/pages-template-plugin.ts +155 -0
  139. package/templates/pages-template-worker.ts +161 -0
  140. package/templates/static-asset-facade.js +38 -36
  141. package/templates/tsconfig.json +95 -95
  142. package/wrangler-dist/cli.d.ts +298 -0
  143. package/wrangler-dist/cli.js +33496 -31370
  144. package/pages/functions/buildPlugin.ts +0 -105
  145. package/pages/functions/buildWorker.ts +0 -151
  146. package/pages/functions/filepath-routing.ts +0 -189
  147. package/pages/functions/identifiers.ts +0 -78
  148. package/pages/functions/routes.ts +0 -156
  149. package/pages/functions/template-plugin.ts +0 -147
  150. package/pages/functions/template-worker.ts +0 -143
  151. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  152. package/src/pages.tsx +0 -2027
  153. package/src/user.tsx +0 -1203
  154. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  155. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  156. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  157. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  158. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  159. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  160. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  161. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  166. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  167. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  168. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  169. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  170. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  171. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  172. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  173. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  174. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  175. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  176. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  177. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  178. package/vendor/wrangler-mime/LICENSE +0 -21
  179. package/vendor/wrangler-mime/Mime.js +0 -97
  180. package/vendor/wrangler-mime/README.md +0 -187
  181. package/vendor/wrangler-mime/cli.js +0 -46
  182. package/vendor/wrangler-mime/index.js +0 -4
  183. package/vendor/wrangler-mime/lite.js +0 -4
  184. package/vendor/wrangler-mime/package.json +0 -52
  185. package/vendor/wrangler-mime/types/other.js +0 -1
  186. package/vendor/wrangler-mime/types/standard.js +0 -1
package/src/whoami.tsx CHANGED
@@ -3,68 +3,88 @@ import Table from "ink-table";
3
3
  import React from "react";
4
4
  import { fetchListResult, fetchResult } from "./cfetch";
5
5
  import { logger } from "./logger";
6
- import { getAPIToken } from "./user";
6
+ import { getAPIToken, getAuthFromEnv } from "./user";
7
7
 
8
8
  export async function whoami() {
9
- logger.log("Getting User settings...");
10
- const user = await getUserInfo();
11
- render(<WhoAmI user={user}></WhoAmI>);
9
+ logger.log("Getting User settings...");
10
+ const user = await getUserInfo();
11
+ render(<WhoAmI user={user}></WhoAmI>);
12
12
  }
13
13
 
14
14
  export function WhoAmI({ user }: { user: UserInfo | undefined }) {
15
- return user ? (
16
- <>
17
- <Email tokenType={user.authType} email={user.email}></Email>
18
- <Accounts accounts={user.accounts}></Accounts>
19
- </>
20
- ) : (
21
- <Text>You are not authenticated. Please run `wrangler login`.</Text>
22
- );
15
+ return user ? (
16
+ <>
17
+ <Email tokenType={user.authType} email={user.email}></Email>
18
+ <Accounts accounts={user.accounts}></Accounts>
19
+ </>
20
+ ) : (
21
+ <Text>You are not authenticated. Please run `wrangler login`.</Text>
22
+ );
23
23
  }
24
24
 
25
- function Email(props: { tokenType: string; email: string }) {
26
- return (
27
- <Text>
28
- 👋 You are logged in with an {props.tokenType} Token, associated with the
29
- email &apos;{props.email}&apos;!
30
- </Text>
31
- );
25
+ function Email(props: { tokenType: string; email: string | undefined }) {
26
+ return props.email === undefined ? (
27
+ <Text>
28
+ 👋 You are logged in with an {props.tokenType}. Unable to retrieve email
29
+ for this user. Are you missing the `User-&gt;User Details-&gt;Read`
30
+ permission?
31
+ </Text>
32
+ ) : (
33
+ <Text>
34
+ 👋 You are logged in with an {props.tokenType}, associated with the email
35
+ &apos;{props.email}&apos;!
36
+ </Text>
37
+ );
32
38
  }
33
39
 
34
40
  function Accounts(props: { accounts: AccountInfo[] }) {
35
- const accounts = props.accounts.map((account) => ({
36
- "Account Name": account.name,
37
- "Account ID": account.id,
38
- }));
39
- return <Table data={accounts}></Table>;
41
+ const accounts = props.accounts.map((account) => ({
42
+ "Account Name": account.name,
43
+ "Account ID": account.id,
44
+ }));
45
+ return <Table data={accounts}></Table>;
40
46
  }
41
47
 
42
48
  export interface UserInfo {
43
- apiToken: string;
44
- authType: string;
45
- email: string;
46
- accounts: AccountInfo[];
49
+ apiToken: string;
50
+ authType: string;
51
+ email: string | undefined;
52
+ accounts: AccountInfo[];
47
53
  }
48
54
 
49
55
  export async function getUserInfo(): Promise<UserInfo | undefined> {
50
- const apiToken = getAPIToken();
51
- return apiToken
52
- ? {
53
- apiToken,
54
- authType: "OAuth",
55
- email: await getEmail(),
56
- accounts: await getAccounts(),
57
- }
58
- : undefined;
56
+ const apiToken = getAPIToken();
57
+ if (!apiToken) return;
58
+
59
+ const usingEnvAuth = !!getAuthFromEnv();
60
+ const usingGlobalAuthKey = "authKey" in apiToken;
61
+ return {
62
+ apiToken: usingGlobalAuthKey ? apiToken.authKey : apiToken.apiToken,
63
+ authType: usingGlobalAuthKey
64
+ ? "Global API Key"
65
+ : usingEnvAuth
66
+ ? "API Token"
67
+ : "OAuth Token",
68
+ email: "authEmail" in apiToken ? apiToken.authEmail : await getEmail(),
69
+ accounts: await getAccounts(),
70
+ };
59
71
  }
60
72
 
61
- async function getEmail(): Promise<string> {
62
- const { email } = await fetchResult<{ email: string }>("/user");
63
- return email;
73
+ async function getEmail(): Promise<string | undefined> {
74
+ try {
75
+ const { email } = await fetchResult<{ email: string }>("/user");
76
+ return email;
77
+ } catch (e) {
78
+ if ((e as { code?: number }).code === 9109) {
79
+ return undefined;
80
+ } else {
81
+ throw e;
82
+ }
83
+ }
64
84
  }
65
85
 
66
86
  type AccountInfo = { name: string; id: string };
67
87
 
68
88
  async function getAccounts(): Promise<AccountInfo[]> {
69
- return await fetchListResult<AccountInfo>("/accounts");
89
+ return await fetchListResult<AccountInfo>("/accounts");
70
90
  }
@@ -0,0 +1,190 @@
1
+ import { fetchResult } from "./cfetch";
2
+ import { readConfig } from "./config";
3
+ import { logger } from "./logger";
4
+ import { requireAuth } from "./user";
5
+ import { printWranglerBanner } from ".";
6
+ import type { ConfigPath } from ".";
7
+ import type { Argv, CommandModule } from "yargs";
8
+
9
+ type Namespace = {
10
+ namespace_id: string;
11
+ namespace_name: string;
12
+ created_on: string;
13
+ created_by: string;
14
+ modified_on: string;
15
+ modified_by: string;
16
+ };
17
+
18
+ // Supporting Workers For Platforms
19
+ // More details at https://blog.cloudflare.com/workers-for-platforms/
20
+
21
+ /**
22
+ * Create a dynamic dispatch namespace.
23
+ */
24
+ async function createWorkerNamespace(accountId: string, name: string) {
25
+ const namespace = await fetchResult<Namespace>(
26
+ `/accounts/${accountId}/workers/dispatch/namespaces`,
27
+ {
28
+ method: "POST",
29
+ headers: {
30
+ "Content-Type": "application/json",
31
+ },
32
+ body: JSON.stringify({ name }),
33
+ }
34
+ );
35
+ logger.log(
36
+ `Created Worker namespace "${name}" with ID "${namespace.namespace_id}"`
37
+ );
38
+ }
39
+
40
+ /**
41
+ * Delete a dynamic dispatch namespace.
42
+ */
43
+ async function deleteWorkerNamespace(accountId: string, name: string) {
44
+ await fetchResult(
45
+ `/accounts/${accountId}/workers/dispatch/namespaces/${name}`,
46
+ { method: "DELETE" }
47
+ );
48
+ logger.log(`Deleted Worker namespace "${name}"`);
49
+ }
50
+
51
+ /**
52
+ * List all created dynamic dispatch namespaces for an account
53
+ */
54
+ async function listWorkerNamespaces(accountId: string) {
55
+ logger.log(
56
+ await fetchResult<Namespace>(
57
+ `/accounts/${accountId}/workers/dispatch/namespaces`,
58
+ {
59
+ headers: {
60
+ "Content-Type": "application/json",
61
+ },
62
+ }
63
+ )
64
+ );
65
+ }
66
+
67
+ /**
68
+ * Get info for a specific dynamic dispatch namespace
69
+ */
70
+ async function getWorkerNamespaceInfo(accountId: string, name: string) {
71
+ logger.log(
72
+ await fetchResult<Namespace>(
73
+ `/accounts/${accountId}/workers/dispatch/namespaces/${name}`,
74
+ {
75
+ headers: {
76
+ "Content-Type": "application/json",
77
+ },
78
+ }
79
+ )
80
+ );
81
+ }
82
+
83
+ /**
84
+ * Rename a dynamic dispatch namespace
85
+ */
86
+ async function renameWorkerNamespace(
87
+ accountId: string,
88
+ oldName: string,
89
+ newName: string
90
+ ) {
91
+ printWranglerBanner();
92
+
93
+ await fetchResult(
94
+ `/accounts/${accountId}/workers/dispatch/namespaces/${oldName}`,
95
+ {
96
+ method: "PUT",
97
+ headers: {
98
+ "Content-Type": "application/json",
99
+ },
100
+ body: JSON.stringify({ name: newName }),
101
+ }
102
+ );
103
+ logger.log(`Renamed Worker namespace "${oldName}" to "${newName}"`);
104
+ }
105
+
106
+ export function workerNamespaceCommands(
107
+ workerNamespaceYargs: Argv,
108
+ subHelp: CommandModule
109
+ ): Argv {
110
+ return workerNamespaceYargs
111
+ .command(subHelp)
112
+ .command("list", "List all Worker namespaces", {}, async (args) => {
113
+ const config = readConfig(args.config as ConfigPath, args);
114
+ const accountId = await requireAuth(config);
115
+ await listWorkerNamespaces(accountId);
116
+ })
117
+ .command(
118
+ "get <name>",
119
+ "Get information about a Worker namespace",
120
+ (yargs) => {
121
+ return yargs.positional("name", {
122
+ describe: "Name of the Worker namespace",
123
+ type: "string",
124
+ demandOption: true,
125
+ });
126
+ },
127
+ async (args) => {
128
+ const config = readConfig(args.config as ConfigPath, args);
129
+ const accountId = await requireAuth(config);
130
+ await getWorkerNamespaceInfo(accountId, args.name);
131
+ }
132
+ )
133
+ .command(
134
+ "create <name>",
135
+ "Create a Worker namespace",
136
+ (yargs) => {
137
+ return yargs.positional("name", {
138
+ describe: "Name of the Worker namespace",
139
+ type: "string",
140
+ demandOption: true,
141
+ });
142
+ },
143
+ async (args) => {
144
+ await printWranglerBanner();
145
+ const config = readConfig(args.config as ConfigPath, args);
146
+ const accountId = await requireAuth(config);
147
+ await createWorkerNamespace(accountId, args.name);
148
+ }
149
+ )
150
+ .command(
151
+ "delete <name>",
152
+ "Delete a Worker namespace",
153
+ (yargs) => {
154
+ return yargs.positional("name", {
155
+ describe: "Name of the Worker namespace",
156
+ type: "string",
157
+ demandOption: true,
158
+ });
159
+ },
160
+ async (args) => {
161
+ await printWranglerBanner();
162
+ const config = readConfig(args.config as ConfigPath, args);
163
+ const accountId = await requireAuth(config);
164
+ await deleteWorkerNamespace(accountId, args.name);
165
+ }
166
+ )
167
+ .command(
168
+ "rename <old-name> <new-name>",
169
+ "Rename a Worker namespace",
170
+ (yargs) => {
171
+ return yargs
172
+ .positional("old-name", {
173
+ describe: "Name of the Worker namespace",
174
+ type: "string",
175
+ demandOption: true,
176
+ })
177
+ .positional("new-name", {
178
+ describe: "New name of the Worker namespace",
179
+ type: "string",
180
+ demandOption: true,
181
+ });
182
+ },
183
+ async (args) => {
184
+ await printWranglerBanner();
185
+ const config = readConfig(args.config as ConfigPath, args);
186
+ const accountId = await requireAuth(config);
187
+ await renameWorkerNamespace(accountId, args.oldName, args.newName);
188
+ }
189
+ );
190
+ }
package/src/worker.ts CHANGED
@@ -1,17 +1,20 @@
1
+ import type { Route } from "./config/environment";
2
+ import type { ApiCredentials } from "./user";
3
+
1
4
  /**
2
5
  * A Cloudflare account.
3
6
  */
4
7
  export interface CfAccount {
5
- /**
6
- * An API token.
7
- *
8
- * @link https://api.cloudflare.com/#user-api-tokens-properties
9
- */
10
- apiToken: string;
11
- /**
12
- * An account ID.
13
- */
14
- accountId: string;
8
+ /**
9
+ * An API token.
10
+ *
11
+ * @link https://api.cloudflare.com/#user-api-tokens-properties
12
+ */
13
+ apiToken: ApiCredentials;
14
+ /**
15
+ * An account ID.
16
+ */
17
+ accountId: string;
15
18
  }
16
19
 
17
20
  /**
@@ -23,55 +26,55 @@ export type CfScriptFormat = "modules" | "service-worker";
23
26
  * A module type.
24
27
  */
25
28
  export type CfModuleType =
26
- | "esm"
27
- | "commonjs"
28
- | "compiled-wasm"
29
- | "text"
30
- | "buffer";
29
+ | "esm"
30
+ | "commonjs"
31
+ | "compiled-wasm"
32
+ | "text"
33
+ | "buffer";
31
34
 
32
35
  /**
33
36
  * An imported module.
34
37
  */
35
38
  export interface CfModule {
36
- /**
37
- * The module name.
38
- *
39
- * @example
40
- * './src/index.js'
41
- */
42
- name: string;
43
- /**
44
- * The module content, usually JavaScript or WASM code.
45
- *
46
- * @example
47
- * export default {
48
- * async fetch(request) {
49
- * return new Response('Ok')
50
- * }
51
- * }
52
- */
53
- content: string | Buffer;
54
- /**
55
- * The module type.
56
- *
57
- * If absent, will default to the main module's type.
58
- */
59
- type?: CfModuleType;
39
+ /**
40
+ * The module name.
41
+ *
42
+ * @example
43
+ * './src/index.js'
44
+ */
45
+ name: string;
46
+ /**
47
+ * The module content, usually JavaScript or WASM code.
48
+ *
49
+ * @example
50
+ * export default {
51
+ * async fetch(request) {
52
+ * return new Response('Ok')
53
+ * }
54
+ * }
55
+ */
56
+ content: string | Buffer;
57
+ /**
58
+ * The module type.
59
+ *
60
+ * If absent, will default to the main module's type.
61
+ */
62
+ type?: CfModuleType;
60
63
  }
61
64
 
62
65
  /**
63
66
  * A map of variable names to values.
64
67
  */
65
68
  interface CfVars {
66
- [key: string]: unknown;
69
+ [key: string]: unknown;
67
70
  }
68
71
 
69
72
  /**
70
73
  * A KV namespace.
71
74
  */
72
75
  interface CfKvNamespace {
73
- binding: string;
74
- id: string;
76
+ binding: string;
77
+ id: string;
75
78
  }
76
79
 
77
80
  /**
@@ -79,7 +82,7 @@ interface CfKvNamespace {
79
82
  */
80
83
 
81
84
  interface CfWasmModuleBindings {
82
- [key: string]: string;
85
+ [key: string]: string;
83
86
  }
84
87
 
85
88
  /**
@@ -87,7 +90,7 @@ interface CfWasmModuleBindings {
87
90
  */
88
91
 
89
92
  interface CfTextBlobBindings {
90
- [key: string]: string;
93
+ [key: string]: string;
91
94
  }
92
95
 
93
96
  /**
@@ -95,86 +98,94 @@ interface CfTextBlobBindings {
95
98
  */
96
99
 
97
100
  interface CfDataBlobBindings {
98
- [key: string]: string;
101
+ [key: string]: string;
99
102
  }
100
103
 
101
104
  /**
102
105
  * A Durable Object.
103
106
  */
104
107
  interface CfDurableObject {
105
- name: string;
106
- class_name: string;
107
- script_name?: string;
108
- environment?: string;
108
+ name: string;
109
+ class_name: string;
110
+ script_name?: string;
111
+ environment?: string;
109
112
  }
110
113
 
111
114
  interface CfR2Bucket {
112
- binding: string;
113
- bucket_name: string;
115
+ binding: string;
116
+ bucket_name: string;
114
117
  }
115
118
 
116
119
  interface CfService {
117
- binding: string;
118
- service: string;
119
- environment?: string;
120
+ binding: string;
121
+ service: string;
122
+ environment?: string;
123
+ }
124
+
125
+ interface CfWorkerNamespace {
126
+ binding: string;
127
+ namespace: string;
120
128
  }
121
129
 
122
130
  interface CfUnsafeBinding {
123
- name: string;
124
- type: string;
131
+ name: string;
132
+ type: string;
125
133
  }
126
134
 
127
135
  export interface CfDurableObjectMigrations {
128
- old_tag?: string;
129
- new_tag: string;
130
- steps: {
131
- new_classes?: string[];
132
- renamed_classes?: {
133
- from: string;
134
- to: string;
135
- }[];
136
- deleted_classes?: string[];
137
- }[];
136
+ old_tag?: string;
137
+ new_tag: string;
138
+ steps: {
139
+ new_classes?: string[];
140
+ renamed_classes?: {
141
+ from: string;
142
+ to: string;
143
+ }[];
144
+ deleted_classes?: string[];
145
+ }[];
138
146
  }
139
147
 
140
148
  /**
141
149
  * Options for creating a `CfWorker`.
142
150
  */
143
151
  export interface CfWorkerInit {
144
- /**
145
- * The name of the worker.
146
- */
147
- name: string | undefined;
148
- /**
149
- * The entrypoint module.
150
- */
151
- main: CfModule;
152
- /**
153
- * The list of additional modules.
154
- */
155
- modules: CfModule[] | undefined;
156
- /**
157
- * All the bindings
158
- */
159
- bindings: {
160
- vars: CfVars | undefined;
161
- kv_namespaces: CfKvNamespace[] | undefined;
162
- wasm_modules: CfWasmModuleBindings | undefined;
163
- text_blobs: CfTextBlobBindings | undefined;
164
- data_blobs: CfDataBlobBindings | undefined;
165
- durable_objects: { bindings: CfDurableObject[] } | undefined;
166
- r2_buckets: CfR2Bucket[] | undefined;
167
- services: CfService[] | undefined;
168
- unsafe: CfUnsafeBinding[] | undefined;
169
- };
170
- migrations: CfDurableObjectMigrations | undefined;
171
- compatibility_date: string | undefined;
172
- compatibility_flags: string[] | undefined;
173
- usage_model: "bundled" | "unbound" | undefined;
152
+ /**
153
+ * The name of the worker.
154
+ */
155
+ name: string | undefined;
156
+ /**
157
+ * The entrypoint module.
158
+ */
159
+ main: CfModule;
160
+ /**
161
+ * The list of additional modules.
162
+ */
163
+ modules: CfModule[] | undefined;
164
+ /**
165
+ * All the bindings
166
+ */
167
+ bindings: {
168
+ vars: CfVars | undefined;
169
+ kv_namespaces: CfKvNamespace[] | undefined;
170
+ wasm_modules: CfWasmModuleBindings | undefined;
171
+ text_blobs: CfTextBlobBindings | undefined;
172
+ data_blobs: CfDataBlobBindings | undefined;
173
+ durable_objects: { bindings: CfDurableObject[] } | undefined;
174
+ r2_buckets: CfR2Bucket[] | undefined;
175
+ services: CfService[] | undefined;
176
+ worker_namespaces: CfWorkerNamespace[] | undefined;
177
+ unsafe: CfUnsafeBinding[] | undefined;
178
+ };
179
+ migrations: CfDurableObjectMigrations | undefined;
180
+ compatibility_date: string | undefined;
181
+ compatibility_flags: string[] | undefined;
182
+ usage_model: "bundled" | "unbound" | undefined;
174
183
  }
175
184
 
176
185
  export interface CfWorkerContext {
177
- env: string | undefined;
178
- legacyEnv: boolean | undefined;
179
- zone: { id: string; host: string } | undefined;
186
+ env: string | undefined;
187
+ legacyEnv: boolean | undefined;
188
+ zone: string | undefined;
189
+ host: string | undefined;
190
+ routes: Route[] | undefined;
180
191
  }
package/src/zones.ts ADDED
@@ -0,0 +1,76 @@
1
+ import { fetchListResult } from "./cfetch";
2
+ import type { Route } from "./config/environment";
3
+
4
+ /**
5
+ * An object holding information about a zone for publishing.
6
+ */
7
+ export interface Zone {
8
+ id: string;
9
+ host: string;
10
+ }
11
+
12
+ export function getHostFromRoute(route: Route): string | undefined {
13
+ return typeof route === "string"
14
+ ? getHostFromUrl(route)
15
+ : typeof route === "object"
16
+ ? "zone_name" in route
17
+ ? getHostFromUrl(route.zone_name)
18
+ : getHostFromUrl(route.pattern)
19
+ : undefined;
20
+ }
21
+
22
+ /**
23
+ * Try to compute the a zone ID and host name for one or more routes.
24
+ *
25
+ * When we're given a route, we do 2 things:
26
+ * - We try to extract a host from it
27
+ * - We try to get a zone id from the host
28
+ */
29
+ export async function getZoneForRoute(route: Route): Promise<Zone | undefined> {
30
+ const host = getHostFromRoute(route);
31
+ const id =
32
+ typeof route === "object" && "zone_id" in route
33
+ ? route.zone_id
34
+ : host
35
+ ? await getZoneIdFromHost(host)
36
+ : undefined;
37
+ return id && host ? { id, host } : undefined;
38
+ }
39
+
40
+ /**
41
+ * Given something that resembles a URL, try to extract a host from it.
42
+ */
43
+ function getHostFromUrl(urlLike: string): string | undefined {
44
+ // strip leading * / *.
45
+ urlLike = urlLike.replace(/^\*(\.)?/g, "");
46
+
47
+ if (!(urlLike.startsWith("http://") || urlLike.startsWith("https://"))) {
48
+ urlLike = "http://" + urlLike;
49
+ }
50
+ return new URL(urlLike).host;
51
+ }
52
+
53
+ /**
54
+ * Given something that resembles a host, try to infer a zone id from it.
55
+ *
56
+ * It's hard to get a 'valid' domain from a string, so we don't even try to validate TLDs, etc.
57
+ * For each domain-like part of the host (e.g. w.x.y.z) try to get a zone id for it by
58
+ * lopping off subdomains until we get a hit from the API.
59
+ */
60
+ export async function getZoneIdFromHost(host: string): Promise<string> {
61
+ const hostPieces = host.split(".");
62
+
63
+ while (hostPieces.length > 1) {
64
+ const zones = await fetchListResult<{ id: string }>(
65
+ `/zones`,
66
+ {},
67
+ new URLSearchParams({ name: hostPieces.join(".") })
68
+ );
69
+ if (zones.length > 0) {
70
+ return zones[0].id;
71
+ }
72
+ hostPieces.shift();
73
+ }
74
+
75
+ throw new Error(`Could not find zone for ${host}`);
76
+ }