wrangler 0.0.0-e95e5a0 → 0.0.0-e981d0be5

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 (184) hide show
  1. package/README.md +46 -34
  2. package/bin/wrangler.js +84 -39
  3. package/config-schema.json +2278 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +132 -99
  6. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  7. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  8. package/templates/__tests__/tsconfig.json +8 -0
  9. package/templates/checked-fetch.js +30 -0
  10. package/templates/facade.d.ts +19 -0
  11. package/templates/gitignore +2 -3
  12. package/templates/init-tests/test-jest-new-worker.js +23 -0
  13. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  14. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  15. package/templates/middleware/common.ts +67 -0
  16. package/templates/middleware/loader-modules.ts +134 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  19. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  21. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  22. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  23. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  24. package/templates/middleware/middleware-pretty-error.ts +40 -0
  25. package/templates/middleware/middleware-scheduled.ts +29 -0
  26. package/templates/modules-watch-stub.js +4 -0
  27. package/templates/new-worker-scheduled.js +17 -0
  28. package/templates/new-worker-scheduled.ts +32 -0
  29. package/templates/new-worker.js +3 -3
  30. package/templates/new-worker.ts +22 -4
  31. package/templates/no-op-worker.js +10 -0
  32. package/templates/pages-dev-pipeline.ts +33 -0
  33. package/templates/pages-dev-util.ts +55 -0
  34. package/templates/pages-shim.ts +9 -0
  35. package/templates/pages-template-plugin.ts +190 -0
  36. package/templates/pages-template-worker.ts +198 -0
  37. package/templates/startDevWorker/InspectorProxyWorker.ts +679 -0
  38. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  39. package/templates/tsconfig-sanity.ts +11 -0
  40. package/templates/tsconfig.init.json +22 -0
  41. package/templates/tsconfig.json +13 -103
  42. package/templates/tsconfig.tsbuildinfo +1 -0
  43. package/wrangler-dist/InspectorProxyWorker.js +471 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +238 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +26693 -0
  48. package/wrangler-dist/cli.js +148512 -106990
  49. package/import_meta_url.js +0 -3
  50. package/miniflare-config-stubs/.env.empty +0 -0
  51. package/miniflare-config-stubs/package.empty.json +0 -1
  52. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  53. package/miniflare-dist/index.mjs +0 -4886
  54. package/pages/functions/buildPlugin.ts +0 -92
  55. package/pages/functions/buildWorker.ts +0 -138
  56. package/pages/functions/filepath-routing.test.ts +0 -234
  57. package/pages/functions/filepath-routing.ts +0 -189
  58. package/pages/functions/identifiers.ts +0 -78
  59. package/pages/functions/routes.ts +0 -156
  60. package/pages/functions/template-plugin.ts +0 -146
  61. package/pages/functions/template-worker.ts +0 -143
  62. package/src/__tests__/config-cache.test.ts +0 -36
  63. package/src/__tests__/configuration.test.ts +0 -3125
  64. package/src/__tests__/dev.test.tsx +0 -762
  65. package/src/__tests__/guess-worker-format.test.ts +0 -85
  66. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  67. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  68. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  69. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  70. package/src/__tests__/helpers/mock-bin.ts +0 -36
  71. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  72. package/src/__tests__/helpers/mock-console.ts +0 -87
  73. package/src/__tests__/helpers/mock-dialogs.ts +0 -90
  74. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  75. package/src/__tests__/helpers/mock-istty.ts +0 -27
  76. package/src/__tests__/helpers/mock-kv.ts +0 -33
  77. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  78. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  79. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  80. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  81. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  82. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  83. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  84. package/src/__tests__/https-options.test.ts +0 -130
  85. package/src/__tests__/index.test.ts +0 -249
  86. package/src/__tests__/init.test.ts +0 -1516
  87. package/src/__tests__/jest.setup.ts +0 -69
  88. package/src/__tests__/kv.test.ts +0 -1454
  89. package/src/__tests__/logger.test.ts +0 -115
  90. package/src/__tests__/package-manager.test.ts +0 -206
  91. package/src/__tests__/pages.test.ts +0 -329
  92. package/src/__tests__/parse.test.ts +0 -322
  93. package/src/__tests__/publish.test.ts +0 -4875
  94. package/src/__tests__/r2.test.ts +0 -214
  95. package/src/__tests__/route.test.ts +0 -45
  96. package/src/__tests__/secret.test.ts +0 -446
  97. package/src/__tests__/tail.test.ts +0 -690
  98. package/src/__tests__/user.test.ts +0 -131
  99. package/src/__tests__/whoami.test.tsx +0 -105
  100. package/src/bundle.ts +0 -169
  101. package/src/cfetch/index.ts +0 -104
  102. package/src/cfetch/internal.ts +0 -137
  103. package/src/cli.ts +0 -13
  104. package/src/config/README.md +0 -107
  105. package/src/config/config.ts +0 -234
  106. package/src/config/diagnostics.ts +0 -80
  107. package/src/config/environment.ts +0 -394
  108. package/src/config/index.ts +0 -63
  109. package/src/config/validation-helpers.ts +0 -575
  110. package/src/config/validation.ts +0 -1424
  111. package/src/config-cache.ts +0 -45
  112. package/src/create-worker-preview.ts +0 -175
  113. package/src/create-worker-upload-form.ts +0 -240
  114. package/src/dev/dev-vars.ts +0 -36
  115. package/src/dev/dev.tsx +0 -418
  116. package/src/dev/local.tsx +0 -312
  117. package/src/dev/remote.tsx +0 -213
  118. package/src/dev/use-esbuild.ts +0 -118
  119. package/src/dialogs.tsx +0 -87
  120. package/src/entry.ts +0 -267
  121. package/src/environment-variables.ts +0 -35
  122. package/src/errors.ts +0 -11
  123. package/src/https-options.ts +0 -123
  124. package/src/index.tsx +0 -2668
  125. package/src/inspect.ts +0 -623
  126. package/src/intl-polyfill.d.ts +0 -139
  127. package/src/kv.ts +0 -319
  128. package/src/logger.ts +0 -66
  129. package/src/miniflare-cli/README.md +0 -30
  130. package/src/miniflare-cli/enum-keys.ts +0 -17
  131. package/src/miniflare-cli/index.ts +0 -41
  132. package/src/miniflare-cli/request-context.ts +0 -40
  133. package/src/module-collection.ts +0 -258
  134. package/src/open-in-browser.ts +0 -26
  135. package/src/package-manager.ts +0 -127
  136. package/src/pages.tsx +0 -1866
  137. package/src/parse.ts +0 -183
  138. package/src/paths.ts +0 -26
  139. package/src/proxy.ts +0 -449
  140. package/src/publish.ts +0 -469
  141. package/src/r2.ts +0 -50
  142. package/src/selfsigned.d.ts +0 -29
  143. package/src/sites.tsx +0 -293
  144. package/src/tail/filters.ts +0 -279
  145. package/src/tail/index.ts +0 -299
  146. package/src/tail/printing.ts +0 -67
  147. package/src/update-check.ts +0 -19
  148. package/src/user.tsx +0 -1193
  149. package/src/whoami.tsx +0 -70
  150. package/src/worker.ts +0 -172
  151. package/templates/static-asset-facade.js +0 -47
  152. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  153. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  154. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  155. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  156. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  157. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  158. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  159. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  160. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  161. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  166. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  167. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  168. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  169. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  170. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  171. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  172. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  173. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  174. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  175. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  176. package/vendor/wrangler-mime/LICENSE +0 -21
  177. package/vendor/wrangler-mime/Mime.js +0 -97
  178. package/vendor/wrangler-mime/README.md +0 -187
  179. package/vendor/wrangler-mime/cli.js +0 -46
  180. package/vendor/wrangler-mime/index.js +0 -4
  181. package/vendor/wrangler-mime/lite.js +0 -4
  182. package/vendor/wrangler-mime/package.json +0 -52
  183. package/vendor/wrangler-mime/types/other.js +0 -1
  184. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -1,131 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import path from "node:path";
4
- import fetchMock from "jest-fetch-mock";
5
- import {
6
- readAuthConfigFile,
7
- requireAuth,
8
- USER_AUTH_CONFIG_FILE,
9
- writeAuthConfigFile,
10
- } from "../user";
11
- import { mockConsoleMethods } from "./helpers/mock-console";
12
- import { useMockIsTTY } from "./helpers/mock-istty";
13
- import { mockOAuthFlow } from "./helpers/mock-oauth-flow";
14
- import { runInTempDir } from "./helpers/run-in-tmp";
15
- import { runWrangler } from "./helpers/run-wrangler";
16
- import type { Config } from "../config";
17
- import type { UserAuthConfig } from "../user";
18
-
19
- describe("User", () => {
20
- runInTempDir({ homedir: "./home" });
21
- const std = mockConsoleMethods();
22
- const {
23
- mockOAuthServerCallback,
24
- mockGrantAccessToken,
25
- mockGrantAuthorization,
26
- mockRevokeAuthorization,
27
- mockExchangeRefreshTokenForAccessToken,
28
- } = mockOAuthFlow();
29
-
30
- const { setIsTTY } = useMockIsTTY();
31
-
32
- describe("login", () => {
33
- it("should login a user when `wrangler login` is run", async () => {
34
- mockOAuthServerCallback();
35
- const accessTokenRequest = mockGrantAccessToken({ respondWith: "ok" });
36
- mockGrantAuthorization({ respondWith: "success" });
37
-
38
- await runWrangler("login");
39
-
40
- expect(accessTokenRequest.actual.url).toEqual(
41
- accessTokenRequest.expected.url
42
- );
43
- expect(accessTokenRequest.actual.method).toEqual(
44
- accessTokenRequest.expected.method
45
- );
46
-
47
- expect(std.out).toMatchInlineSnapshot(`
48
- "Attempting to login via OAuth...
49
- Successfully logged in."
50
- `);
51
-
52
- expect(readAuthConfigFile()).toEqual<UserAuthConfig>({
53
- api_token: undefined,
54
- oauth_token: "test-access-token",
55
- refresh_token: "test-refresh-token",
56
- expiration_time: expect.any(String),
57
- });
58
- });
59
- });
60
-
61
- describe("logout", () => {
62
- it("should exit with a message stating the user is not logged in", async () => {
63
- await runWrangler("logout");
64
- expect(std.out).toMatchInlineSnapshot(`"Not logged in, exiting..."`);
65
- });
66
-
67
- it("should logout user that has been properly logged in", async () => {
68
- writeAuthConfigFile({
69
- oauth_token: "some-oauth-tok",
70
- refresh_token: "some-refresh-tok",
71
- });
72
- const outcome = mockRevokeAuthorization();
73
-
74
- await runWrangler("logout");
75
-
76
- expect(outcome.actual.url).toEqual(
77
- "https://dash.cloudflare.com/oauth2/revoke"
78
- );
79
- expect(outcome.actual.method).toEqual("POST");
80
-
81
- expect(std.out).toMatchInlineSnapshot(`"Successfully logged out."`);
82
-
83
- // Make sure that we made the request to logout.
84
- expect(fetchMock).toHaveBeenCalledTimes(1);
85
-
86
- // Make sure that logout removed the config file containing the auth tokens.
87
- const config = path.join(os.homedir(), USER_AUTH_CONFIG_FILE);
88
- expect(fs.existsSync(config)).toBeFalsy();
89
- });
90
- });
91
-
92
- // TODO: Improve OAuth mocking to handle `/token` endpoints from different calls
93
- it("should handle errors for failed token refresh", async () => {
94
- setIsTTY(false);
95
- mockOAuthServerCallback();
96
- writeAuthConfigFile({
97
- oauth_token: "hunter2",
98
- refresh_token: "Order 66",
99
- });
100
- mockGrantAuthorization({ respondWith: "success" });
101
-
102
- mockExchangeRefreshTokenForAccessToken({
103
- respondWith: "badResponse",
104
- });
105
-
106
- // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
107
- await expect(
108
- requireAuth({} as Config)
109
- ).rejects.toThrowErrorMatchingInlineSnapshot(
110
- `"Did not login, quitting..."`
111
- );
112
- });
113
-
114
- it("should confirm no error message when refresh is successful", async () => {
115
- setIsTTY(false);
116
- mockOAuthServerCallback();
117
- writeAuthConfigFile({
118
- oauth_token: "hunter2",
119
- refresh_token: "Order 66",
120
- });
121
- mockGrantAuthorization({ respondWith: "success" });
122
-
123
- mockExchangeRefreshTokenForAccessToken({
124
- respondWith: "refreshSuccess",
125
- });
126
-
127
- // Handles the requireAuth error throw from failed login that is unhandled due to directly calling it here
128
- await expect(requireAuth({} as Config)).rejects.toThrowError();
129
- expect(std.err).toContain("");
130
- });
131
- });
@@ -1,105 +0,0 @@
1
- import { render } from "ink-testing-library";
2
- import React from "react";
3
- import { writeAuthConfigFile } from "../user";
4
- import { getUserInfo, WhoAmI } from "../whoami";
5
- import { setMockResponse } from "./helpers/mock-cfetch";
6
- import { mockConsoleMethods } from "./helpers/mock-console";
7
- import { useMockIsTTY } from "./helpers/mock-istty";
8
- import { runInTempDir } from "./helpers/run-in-tmp";
9
- import type { UserInfo } from "../whoami";
10
-
11
- describe("getUserInfo()", () => {
12
- runInTempDir({ homedir: "./home" });
13
- const std = mockConsoleMethods();
14
- const { setIsTTY } = useMockIsTTY();
15
-
16
- beforeEach(() => {
17
- setIsTTY(true);
18
- });
19
-
20
- it("should return undefined if there is no config file", async () => {
21
- const userInfo = await getUserInfo();
22
- expect(userInfo).toBeUndefined();
23
- });
24
-
25
- it("should return undefined if there is an empty config file", async () => {
26
- writeAuthConfigFile({});
27
- const userInfo = await getUserInfo();
28
- expect(userInfo).toBeUndefined();
29
- });
30
-
31
- it("should return the user's email and accounts if authenticated via config token", async () => {
32
- writeAuthConfigFile({ oauth_token: "some-oauth-token" });
33
-
34
- setMockResponse("/user", () => {
35
- return { email: "user@example.com" };
36
- });
37
- setMockResponse("/accounts", () => {
38
- return [
39
- { name: "Account One", id: "account-1" },
40
- { name: "Account Two", id: "account-2" },
41
- { name: "Account Three", id: "account-3" },
42
- ];
43
- });
44
-
45
- const userInfo = await getUserInfo();
46
-
47
- expect(userInfo).toEqual({
48
- authType: "OAuth",
49
- apiToken: "some-oauth-token",
50
- email: "user@example.com",
51
- accounts: [
52
- { name: "Account One", id: "account-1" },
53
- { name: "Account Two", id: "account-2" },
54
- { name: "Account Three", id: "account-3" },
55
- ],
56
- });
57
- });
58
-
59
- it("should display a warning message if the config file contains a legacy api_token field", async () => {
60
- writeAuthConfigFile({ api_token: "API_TOKEN" });
61
- await getUserInfo();
62
- expect(std.warn).toMatchInlineSnapshot(`
63
- "▲ [WARNING] It looks like you have used Wrangler 1's \`config\` command to login with an API token.
64
-
65
- This is no longer supported in the current version of Wrangler.
66
- If you wish to authenticate via an API token then please set the \`CLOUDFLARE_API_TOKEN\`
67
- environment variable.
68
-
69
- "
70
- `);
71
- });
72
- });
73
-
74
- describe("WhoAmI component", () => {
75
- it("should return undefined if there is no user", async () => {
76
- const { lastFrame } = render(<WhoAmI user={undefined}></WhoAmI>);
77
-
78
- expect(lastFrame()).toMatchInlineSnapshot(
79
- `"You are not authenticated. Please run \`wrangler login\`."`
80
- );
81
- });
82
-
83
- it("should display the user's email and accounts", async () => {
84
- const user: UserInfo = {
85
- authType: "OAuth",
86
- apiToken: "some-oauth-token",
87
- email: "user@example.com",
88
- accounts: [
89
- { name: "Account One", id: "account-1" },
90
- { name: "Account Two", id: "account-2" },
91
- { name: "Account Three", id: "account-3" },
92
- ],
93
- };
94
-
95
- const { lastFrame } = render(<WhoAmI user={user}></WhoAmI>);
96
-
97
- expect(lastFrame()).toContain(
98
- "You are logged in with an OAuth Token, associated with the email 'user@example.com'!"
99
- );
100
- expect(lastFrame()).toMatch(/Account Name .+ Account ID/);
101
- expect(lastFrame()).toMatch(/Account One .+ account-1/);
102
- expect(lastFrame()).toMatch(/Account Two .+ account-2/);
103
- expect(lastFrame()).toMatch(/Account Three .+ account-3/);
104
- });
105
- });
package/src/bundle.ts DELETED
@@ -1,169 +0,0 @@
1
- import assert from "node:assert";
2
- import * as fs from "node:fs";
3
- import * as path from "node:path";
4
- import NodeGlobalsPolyfills from "@esbuild-plugins/node-globals-polyfill";
5
- import NodeModulesPolyfills from "@esbuild-plugins/node-modules-polyfill";
6
- import * as esbuild from "esbuild";
7
- import createModuleCollector from "./module-collection";
8
- import type { Config } from "./config";
9
- import type { Entry } from "./entry";
10
- import type { CfModule } from "./worker";
11
-
12
- type BundleResult = {
13
- modules: CfModule[];
14
- resolvedEntryPointPath: string;
15
- bundleType: "esm" | "commonjs";
16
- stop: (() => void) | undefined;
17
- };
18
-
19
- /**
20
- * Generate a bundle for the worker identified by the arguments passed in.
21
- */
22
- export async function bundleWorker(
23
- entry: Entry,
24
- destination: string,
25
- options: {
26
- serveAssetsFromWorker: boolean;
27
- jsxFactory: string | undefined;
28
- jsxFragment: string | undefined;
29
- rules: Config["rules"];
30
- watch?: esbuild.WatchMode;
31
- tsconfig: string | undefined;
32
- minify: boolean | undefined;
33
- nodeCompat: boolean | undefined;
34
- }
35
- ): Promise<BundleResult> {
36
- const {
37
- serveAssetsFromWorker,
38
- jsxFactory,
39
- jsxFragment,
40
- rules,
41
- watch,
42
- tsconfig,
43
- minify,
44
- nodeCompat,
45
- } = options;
46
- const entryDirectory = path.dirname(entry.file);
47
- const moduleCollector = createModuleCollector({
48
- wrangler1xlegacyModuleReferences: {
49
- rootDirectory: entryDirectory,
50
- fileNames: new Set(
51
- fs
52
- .readdirSync(entryDirectory, { withFileTypes: true })
53
- .filter(
54
- (dirEntry) =>
55
- dirEntry.isFile() && dirEntry.name !== path.basename(entry.file)
56
- )
57
- .map((dirEnt) => dirEnt.name)
58
- ),
59
- },
60
- format: entry.format,
61
- rules,
62
- });
63
- const result = await esbuild.build({
64
- ...getEntryPoint(entry.file, serveAssetsFromWorker),
65
- bundle: true,
66
- absWorkingDir: entry.directory,
67
- outdir: destination,
68
- external: ["__STATIC_CONTENT_MANIFEST"],
69
- format: "esm",
70
- target: "es2020",
71
- sourcemap: true,
72
- minify,
73
- metafile: true,
74
- conditions: ["worker", "browser"],
75
- ...(process.env.NODE_ENV && {
76
- define: {
77
- "process.env.NODE_ENV": `"${process.env.NODE_ENV}"`,
78
- ...(nodeCompat ? { global: "globalThis" } : {}),
79
- },
80
- }),
81
- loader: {
82
- ".js": "jsx",
83
- ".mjs": "jsx",
84
- ".cjs": "jsx",
85
- },
86
- plugins: [
87
- moduleCollector.plugin,
88
- ...(nodeCompat
89
- ? [NodeGlobalsPolyfills({ buffer: true }), NodeModulesPolyfills()]
90
- : []),
91
- ],
92
- ...(jsxFactory && { jsxFactory }),
93
- ...(jsxFragment && { jsxFragment }),
94
- ...(tsconfig && { tsconfig }),
95
- watch,
96
- });
97
-
98
- const entryPointOutputs = Object.entries(result.metafile.outputs).filter(
99
- ([_path, output]) => output.entryPoint !== undefined
100
- );
101
- assert(
102
- entryPointOutputs.length > 0,
103
- `Cannot find entry-point "${entry.file}" in generated bundle.` +
104
- listEntryPoints(entryPointOutputs)
105
- );
106
- assert(
107
- entryPointOutputs.length < 2,
108
- "More than one entry-point found for generated bundle." +
109
- listEntryPoints(entryPointOutputs)
110
- );
111
-
112
- const entryPointExports = entryPointOutputs[0][1].exports;
113
- const bundleType = entryPointExports.length > 0 ? "esm" : "commonjs";
114
-
115
- return {
116
- modules: moduleCollector.modules,
117
- resolvedEntryPointPath: path.resolve(
118
- entry.directory,
119
- entryPointOutputs[0][0]
120
- ),
121
- bundleType,
122
- stop: result.stop,
123
- };
124
- }
125
-
126
- type EntryPoint =
127
- | { stdin: esbuild.StdinOptions; nodePaths: string[] }
128
- | { entryPoints: string[] };
129
-
130
- /**
131
- * Create an object that describes the entry point for esbuild.
132
- *
133
- * If we are using the experimental asset handling, then the entry point is
134
- * actually a shim worker that will either return an asset from a KV store,
135
- * or delegate to the actual worker.
136
- */
137
- function getEntryPoint(
138
- entryFile: string,
139
- serveAssetsFromWorker: boolean
140
- ): EntryPoint {
141
- if (serveAssetsFromWorker) {
142
- return {
143
- stdin: {
144
- contents: fs
145
- .readFileSync(
146
- path.join(__dirname, "../templates/static-asset-facade.js"),
147
- "utf8"
148
- )
149
- .replace("__ENTRY_POINT__", entryFile),
150
- sourcefile: "static-asset-facade.js",
151
- resolveDir: path.dirname(entryFile),
152
- },
153
- nodePaths: [path.join(__dirname, "../vendor")],
154
- };
155
- } else {
156
- return { entryPoints: [entryFile] };
157
- }
158
- }
159
-
160
- /**
161
- * Generate a string that describes the entry-points that were identified by esbuild.
162
- */
163
- function listEntryPoints(
164
- outputs: [string, ValueOf<esbuild.Metafile["outputs"]>][]
165
- ): string {
166
- return outputs.map(([_input, output]) => output.entryPoint).join("\n");
167
- }
168
-
169
- type ValueOf<T> = T[keyof T];
@@ -1,104 +0,0 @@
1
- import { URLSearchParams } from "node:url";
2
- import { ParseError } from "../parse";
3
- import { fetchInternal } from "./internal";
4
- import type { RequestInit } from "undici";
5
-
6
- // Check out https://api.cloudflare.com/ for API docs.
7
-
8
- export { getCloudflareAPIBaseURL as getCloudflareApiBaseUrl } from "./internal";
9
-
10
- export interface FetchError {
11
- code: number;
12
- message: string;
13
- }
14
- export interface FetchResult<ResponseType = unknown> {
15
- success: boolean;
16
- result: ResponseType;
17
- errors: FetchError[];
18
- messages: string[];
19
- result_info?: unknown;
20
- }
21
-
22
- export { fetchKVGetValue } from "./internal";
23
-
24
- /**
25
- * Make a fetch request, and extract the `result` from the JSON response.
26
- */
27
- export async function fetchResult<ResponseType>(
28
- resource: string,
29
- init: RequestInit = {},
30
- queryParams?: URLSearchParams
31
- ): Promise<ResponseType> {
32
- const json = await fetchInternal<FetchResult<ResponseType>>(
33
- resource,
34
- init,
35
- queryParams
36
- );
37
- if (json.success) {
38
- return json.result;
39
- } else {
40
- throwFetchError(resource, json);
41
- }
42
- }
43
-
44
- /**
45
- * Make a fetch request for a list of values,
46
- * extracting the `result` from the JSON response,
47
- * and repeating the request if the results are paginated.
48
- */
49
- export async function fetchListResult<ResponseType>(
50
- resource: string,
51
- init: RequestInit = {},
52
- queryParams?: URLSearchParams
53
- ): Promise<ResponseType[]> {
54
- const results: ResponseType[] = [];
55
- let getMoreResults = true;
56
- let cursor: string | undefined;
57
- while (getMoreResults) {
58
- if (cursor) {
59
- queryParams = new URLSearchParams(queryParams);
60
- queryParams.set("cursor", cursor);
61
- }
62
- const json = await fetchInternal<FetchResult<ResponseType[]>>(
63
- resource,
64
- init,
65
- queryParams
66
- );
67
- if (json.success) {
68
- results.push(...json.result);
69
- if (hasCursor(json.result_info)) {
70
- cursor = json.result_info?.cursor;
71
- } else {
72
- getMoreResults = false;
73
- }
74
- } else {
75
- throwFetchError(resource, json);
76
- }
77
- }
78
- return results;
79
- }
80
-
81
- function throwFetchError(
82
- resource: string,
83
- response: FetchResult<unknown>
84
- ): never {
85
- const error = new ParseError({
86
- text: "Received a bad response from the API",
87
- notes: response.errors.map((err) => ({
88
- text: err.code ? `${err.message} [code: ${err.code}]` : err.message,
89
- })),
90
- });
91
- // add the first error code directly to this error
92
- // so consumers can use it for specific behaviour
93
- const code = response.errors[0]?.code;
94
- if (code) {
95
- //@ts-expect-error non-standard property on Error
96
- error.code = code;
97
- }
98
- throw error;
99
- }
100
-
101
- function hasCursor(result_info: unknown): result_info is { cursor: string } {
102
- const cursor = (result_info as { cursor: string } | undefined)?.cursor;
103
- return cursor !== undefined && cursor !== null && cursor !== "";
104
- }
@@ -1,137 +0,0 @@
1
- import { fetch, Headers } from "undici";
2
- import { getEnvironmentVariableFactory } from "../environment-variables";
3
- import { ParseError, parseJSON } from "../parse";
4
- import { getAPIToken, loginOrRefreshIfRequired } from "../user";
5
- import type { URLSearchParams } from "node:url";
6
- import type { RequestInit, HeadersInit } from "undici";
7
-
8
- /**
9
- * Get the URL to use to access the Cloudflare API.
10
- */
11
- export const getCloudflareAPIBaseURL = getEnvironmentVariableFactory({
12
- variableName: "CLOUDFLARE_API_BASE_URL",
13
- deprecatedName: "CF_API_BASE_URL",
14
- defaultValue: "https://api.cloudflare.com/client/v4",
15
- });
16
-
17
- /**
18
- * Make a fetch request to the Cloudflare API.
19
- *
20
- * This function handles acquiring the API token and logging the caller in, as necessary.
21
- *
22
- * Check out https://api.cloudflare.com/ for API docs.
23
- *
24
- * This function should not be used directly, instead use the functions in `cfetch/index.ts`.
25
- */
26
- export async function fetchInternal<ResponseType>(
27
- resource: string,
28
- init: RequestInit = {},
29
- queryParams?: URLSearchParams
30
- ): Promise<ResponseType> {
31
- await requireLoggedIn();
32
- const apiToken = requireApiToken();
33
- const headers = cloneHeaders(init.headers);
34
- addAuthorizationHeader(headers, apiToken);
35
-
36
- const queryString = queryParams ? `?${queryParams.toString()}` : "";
37
- const method = init.method ?? "GET";
38
- const response = await fetch(
39
- `${getCloudflareAPIBaseURL()}${resource}${queryString}`,
40
- {
41
- method,
42
- ...init,
43
- headers,
44
- }
45
- );
46
- const jsonText = await response.text();
47
- try {
48
- return parseJSON(jsonText) as ResponseType;
49
- } catch (err) {
50
- throw new ParseError({
51
- text: "Received a malformed response from the API",
52
- notes: [
53
- {
54
- text: truncate(jsonText, 100),
55
- },
56
- {
57
- text: `${method} ${resource} -> ${response.status} ${response.statusText}`,
58
- },
59
- ],
60
- });
61
- }
62
- }
63
-
64
- function truncate(text: string, maxLength: number): string {
65
- const { length } = text;
66
- if (length <= maxLength) {
67
- return text;
68
- }
69
- return `${text.substring(0, maxLength)}... (length = ${length})`;
70
- }
71
-
72
- function cloneHeaders(
73
- headers: HeadersInit | undefined
74
- ): Record<string, string> {
75
- return headers instanceof Headers
76
- ? Object.fromEntries(headers.entries())
77
- : Array.isArray(headers)
78
- ? Object.fromEntries(headers)
79
- : { ...headers };
80
- }
81
-
82
- async function requireLoggedIn(): Promise<void> {
83
- const loggedIn = await loginOrRefreshIfRequired();
84
- if (!loggedIn) {
85
- throw new Error("Not logged in.");
86
- }
87
- }
88
-
89
- function requireApiToken(): string {
90
- const authToken = getAPIToken();
91
- if (!authToken) {
92
- throw new Error("No API token found.");
93
- }
94
- return authToken;
95
- }
96
-
97
- function addAuthorizationHeader(
98
- headers: Record<string, string>,
99
- apiToken: string
100
- ): void {
101
- if ("Authorization" in headers) {
102
- throw new Error(
103
- "The request already specifies an authorisation header - cannot add a new one."
104
- );
105
- }
106
- headers["Authorization"] = `Bearer ${apiToken}`;
107
- }
108
-
109
- /**
110
- * The implementation for fetching a kv value from the cloudflare API.
111
- * We special-case this one call, because it's the only API call that
112
- * doesn't return json. We inline the implementation and try not to share
113
- * any code with the other calls. We should push back on any new APIs that
114
- * try to introduce non-"standard" response structures.
115
- */
116
-
117
- export async function fetchKVGetValue(
118
- accountId: string,
119
- namespaceId: string,
120
- key: string
121
- ): Promise<string> {
122
- await requireLoggedIn();
123
- const apiToken = requireApiToken();
124
- const headers = { Authorization: `Bearer ${apiToken}` };
125
- const resource = `${getCloudflareAPIBaseURL()}/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`;
126
- const response = await fetch(resource, {
127
- method: "GET",
128
- headers,
129
- });
130
- if (response.ok) {
131
- return await response.text();
132
- } else {
133
- throw new Error(
134
- `Failed to fetch ${resource} - ${response.status}: ${response.statusText});`
135
- );
136
- }
137
- }
package/src/cli.ts DELETED
@@ -1,13 +0,0 @@
1
- import "dotenv/config"; // Grab locally specified env params from a `.env` file.
2
- import process from "process";
3
- import { hideBin } from "yargs/helpers";
4
- import { FatalError } from "./errors";
5
- import { main } from ".";
6
-
7
- main(hideBin(process.argv)).catch((e) => {
8
- // The logging of any error that was thrown from `main()` is handled in the `yargs.fail()` handler.
9
- // Here we just want to ensure that the process exits with a non-zero code.
10
- // We don't want to do this inside the `main()` function, since that would kill the process when running our tests.
11
- const exitCode = (e instanceof FatalError && e.code) || 1;
12
- process.exit(exitCode);
13
- });