wrangler 0.0.0-e64812e → 0.0.0-e6488257

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 (185) hide show
  1. package/README.md +29 -11
  2. package/bin/wrangler.js +86 -67
  3. package/config-schema.json +2947 -0
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +114 -77
  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 +0 -4
  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-pretty-error.ts +40 -0
  21. package/templates/middleware/middleware-scheduled.ts +15 -0
  22. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  23. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  24. package/templates/modules-watch-stub.js +4 -0
  25. package/templates/new-worker-scheduled.js +3 -3
  26. package/templates/new-worker-scheduled.ts +16 -16
  27. package/templates/new-worker.js +3 -3
  28. package/templates/new-worker.ts +19 -16
  29. package/templates/no-op-worker.js +10 -0
  30. package/templates/pages-dev-pipeline.ts +32 -0
  31. package/templates/pages-dev-util.ts +55 -0
  32. package/templates/pages-shim.ts +9 -0
  33. package/templates/pages-template-plugin.ts +190 -0
  34. package/templates/pages-template-worker.ts +198 -0
  35. package/templates/startDevWorker/InspectorProxyWorker.ts +664 -0
  36. package/templates/startDevWorker/ProxyWorker.ts +334 -0
  37. package/templates/tsconfig-sanity.ts +11 -0
  38. package/templates/tsconfig.init.json +105 -0
  39. package/templates/tsconfig.json +6 -103
  40. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +240 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +24215 -0
  45. package/wrangler-dist/cli.js +188741 -107044
  46. package/wrangler-dist/wasm-sync.wasm +0 -0
  47. package/Cloudflare_CA.pem +0 -18
  48. package/import_meta_url.js +0 -3
  49. package/miniflare-config-stubs/.env.empty +0 -0
  50. package/miniflare-config-stubs/package.empty.json +0 -1
  51. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  52. package/miniflare-dist/index.mjs +0 -4886
  53. package/pages/functions/buildPlugin.ts +0 -105
  54. package/pages/functions/buildWorker.ts +0 -151
  55. package/pages/functions/filepath-routing.test.ts +0 -234
  56. package/pages/functions/filepath-routing.ts +0 -189
  57. package/pages/functions/identifiers.ts +0 -78
  58. package/pages/functions/routes.ts +0 -156
  59. package/pages/functions/template-plugin.ts +0 -147
  60. package/pages/functions/template-worker.ts +0 -143
  61. package/src/__tests__/config-cache.test.ts +0 -36
  62. package/src/__tests__/configuration.test.ts +0 -3374
  63. package/src/__tests__/dev.test.tsx +0 -980
  64. package/src/__tests__/guess-worker-format.test.ts +0 -85
  65. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  66. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  67. package/src/__tests__/helpers/faye-websocket.d.ts +0 -6
  68. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  69. package/src/__tests__/helpers/mock-bin.ts +0 -36
  70. package/src/__tests__/helpers/mock-cfetch.ts +0 -211
  71. package/src/__tests__/helpers/mock-console.ts +0 -87
  72. package/src/__tests__/helpers/mock-dialogs.ts +0 -130
  73. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  74. package/src/__tests__/helpers/mock-istty.ts +0 -27
  75. package/src/__tests__/helpers/mock-kv.ts +0 -33
  76. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -255
  77. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  78. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  79. package/src/__tests__/helpers/run-in-tmp.ts +0 -39
  80. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  81. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  82. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  83. package/src/__tests__/https-options.test.ts +0 -130
  84. package/src/__tests__/index.test.ts +0 -256
  85. package/src/__tests__/init.test.ts +0 -1634
  86. package/src/__tests__/jest.setup.ts +0 -77
  87. package/src/__tests__/kv.test.ts +0 -1481
  88. package/src/__tests__/logger.test.ts +0 -115
  89. package/src/__tests__/package-manager.test.ts +0 -353
  90. package/src/__tests__/pages.test.ts +0 -754
  91. package/src/__tests__/parse.test.ts +0 -330
  92. package/src/__tests__/publish.test.ts +0 -5468
  93. package/src/__tests__/r2.test.ts +0 -233
  94. package/src/__tests__/route.test.ts +0 -45
  95. package/src/__tests__/secret.test.ts +0 -481
  96. package/src/__tests__/tail.test.ts +0 -690
  97. package/src/__tests__/user.test.ts +0 -131
  98. package/src/__tests__/whoami.test.tsx +0 -105
  99. package/src/abort.d.ts +0 -3
  100. package/src/bundle.ts +0 -200
  101. package/src/cfetch/index.ts +0 -121
  102. package/src/cfetch/internal.ts +0 -145
  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 -420
  108. package/src/config/index.ts +0 -225
  109. package/src/config/validation-helpers.ts +0 -575
  110. package/src/config/validation.ts +0 -1539
  111. package/src/config-cache.ts +0 -45
  112. package/src/create-worker-preview.ts +0 -185
  113. package/src/create-worker-upload-form.ts +0 -254
  114. package/src/dev/dev-vars.ts +0 -36
  115. package/src/dev/dev.tsx +0 -419
  116. package/src/dev/local.tsx +0 -318
  117. package/src/dev/remote.tsx +0 -227
  118. package/src/dev/use-esbuild.ts +0 -118
  119. package/src/dialogs.tsx +0 -135
  120. package/src/durable.ts +0 -102
  121. package/src/entry.ts +0 -322
  122. package/src/environment-variables.ts +0 -35
  123. package/src/errors.ts +0 -11
  124. package/src/https-options.ts +0 -123
  125. package/src/index.tsx +0 -2864
  126. package/src/inspect.ts +0 -662
  127. package/src/intl-polyfill.d.ts +0 -139
  128. package/src/kv.ts +0 -408
  129. package/src/logger.ts +0 -66
  130. package/src/miniflare-cli/README.md +0 -30
  131. package/src/miniflare-cli/enum-keys.ts +0 -17
  132. package/src/miniflare-cli/index.ts +0 -41
  133. package/src/miniflare-cli/request-context.ts +0 -40
  134. package/src/module-collection.ts +0 -258
  135. package/src/open-in-browser.ts +0 -19
  136. package/src/package-manager.ts +0 -174
  137. package/src/pages.tsx +0 -2038
  138. package/src/parse.ts +0 -202
  139. package/src/paths.ts +0 -26
  140. package/src/proxy.ts +0 -465
  141. package/src/publish.ts +0 -583
  142. package/src/r2.ts +0 -50
  143. package/src/selfsigned.d.ts +0 -29
  144. package/src/sites.tsx +0 -295
  145. package/src/tail/filters.ts +0 -279
  146. package/src/tail/index.ts +0 -299
  147. package/src/tail/printing.ts +0 -67
  148. package/src/update-check.ts +0 -19
  149. package/src/user.tsx +0 -1203
  150. package/src/whoami.tsx +0 -70
  151. package/src/worker.ts +0 -180
  152. package/templates/static-asset-facade.js +0 -47
  153. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  154. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  155. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  156. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  157. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  158. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  159. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  160. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  161. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  162. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  163. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  164. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  166. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  167. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  168. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  169. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  170. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  171. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  172. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  173. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  174. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  175. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  176. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  177. package/vendor/wrangler-mime/LICENSE +0 -21
  178. package/vendor/wrangler-mime/Mime.js +0 -97
  179. package/vendor/wrangler-mime/README.md +0 -187
  180. package/vendor/wrangler-mime/cli.js +0 -46
  181. package/vendor/wrangler-mime/index.js +0 -4
  182. package/vendor/wrangler-mime/lite.js +0 -4
  183. package/vendor/wrangler-mime/package.json +0 -52
  184. package/vendor/wrangler-mime/types/other.js +0 -1
  185. package/vendor/wrangler-mime/types/standard.js +0 -1
@@ -1,27 +0,0 @@
1
- const ORIGINAL_STDOUT_ISTTY = process.stdout.isTTY;
2
- const ORIGINAL_STDIN_ISTTY = process.stdin.isTTY;
3
-
4
- /**
5
- * Mock `process.stdout.isTTY`
6
- */
7
- export function useMockIsTTY() {
8
- /**
9
- * Explicitly set `process.stdout.isTTY` to a given value
10
- */
11
- const setIsTTY = (isTTY: boolean) => {
12
- process.stdout.isTTY = isTTY;
13
- process.stdin.isTTY = isTTY;
14
- };
15
-
16
- beforeEach(() => {
17
- process.stdout.isTTY = ORIGINAL_STDOUT_ISTTY;
18
- process.stdin.isTTY = ORIGINAL_STDIN_ISTTY;
19
- });
20
-
21
- afterEach(() => {
22
- process.stdout.isTTY = ORIGINAL_STDOUT_ISTTY;
23
- process.stdin.isTTY = ORIGINAL_STDIN_ISTTY;
24
- });
25
-
26
- return { setIsTTY };
27
- }
@@ -1,33 +0,0 @@
1
- import { createFetchResult, setMockRawResponse } from "./mock-cfetch";
2
- import type { NamespaceKeyInfo } from "../../kv";
3
-
4
- export function mockKeyListRequest(
5
- expectedNamespaceId: string,
6
- expectedKeys: NamespaceKeyInfo[],
7
- keysPerRequest = 1000,
8
- blankCursorValue: "" | undefined | null = undefined
9
- ) {
10
- const requests = { count: 0 };
11
- // See https://api.cloudflare.com/#workers-kv-namespace-list-a-namespace-s-keys
12
-
13
- setMockRawResponse(
14
- "/accounts/:accountId/storage/kv/namespaces/:namespaceId/keys",
15
- "GET",
16
- ([_url, accountId, namespaceId], _init, query) => {
17
- requests.count++;
18
- expect(accountId).toEqual("some-account-id");
19
- expect(namespaceId).toEqual(expectedNamespaceId);
20
- if (expectedKeys.length <= keysPerRequest) {
21
- return createFetchResult(expectedKeys);
22
- } else {
23
- const start = parseInt(query.get("cursor") ?? "0") || 0;
24
- const end = start + keysPerRequest;
25
- const cursor = end < expectedKeys.length ? end : blankCursorValue;
26
- return createFetchResult(expectedKeys.slice(start, end), true, [], [], {
27
- cursor,
28
- });
29
- }
30
- }
31
- );
32
- return requests;
33
- }
@@ -1,255 +0,0 @@
1
- import fetchMock from "jest-fetch-mock";
2
- import { Request } from "undici";
3
- import { getCloudflareApiBaseUrl } from "../../cfetch";
4
- import openInBrowser from "../../open-in-browser";
5
- import { mockHttpServer } from "./mock-http-server";
6
-
7
- // the response to send when wrangler wants an oauth grant
8
- let oauthGrantResponse: GrantResponseOptions | "timeout" = {};
9
-
10
- /**
11
- * Functions to help with mocking various parts of the OAuth Flow
12
- */
13
- export const mockOAuthFlow = () => {
14
- const fetchHttp = mockHttpServer();
15
-
16
- afterEach(() => {
17
- fetchMock.resetMocks();
18
- });
19
-
20
- /**
21
- * Mock out the callback from a browser to our HttpServer.
22
- *
23
- * This function will override `openInBrowser()` so that instead of opening a browser window
24
- * at the OAuth URL, it will automatically trigger the callback URL on the mock HttpServer that
25
- * we have created as part of the call to `mockOAuthFlow()`.
26
- */
27
- const mockOAuthServerCallback = () => {
28
- (
29
- openInBrowser as jest.MockedFunction<typeof openInBrowser>
30
- ).mockImplementation(async (url: string) => {
31
- // We don't support the grant response timing out.
32
- if (oauthGrantResponse === "timeout") {
33
- throw "unimplemented";
34
- }
35
-
36
- // Create a fake callback request that would be created by the OAuth server
37
- const { searchParams } = new URL(url);
38
- const queryParams = toQueryParams(oauthGrantResponse, searchParams);
39
- const request = new Request(
40
- `${searchParams.get("redirect_uri")}?${queryParams}`
41
- );
42
-
43
- // Trigger the mock HttpServer to handle this fake request to continue the OAuth flow.
44
- fetchHttp(request).catch((e) => {
45
- throw new Error(
46
- "Failed to send OAuth Grant to wrangler, maybe the server was closed?",
47
- e as Error
48
- );
49
- });
50
- });
51
- };
52
-
53
- const mockGrantAuthorization = ({
54
- respondWith,
55
- }: {
56
- respondWith: "timeout" | "success" | "failure" | GrantResponseOptions;
57
- }) => {
58
- if (respondWith === "failure") {
59
- oauthGrantResponse = {
60
- error: "access_denied",
61
- };
62
- } else if (respondWith === "success") {
63
- oauthGrantResponse = {
64
- code: "test-oauth-code",
65
- };
66
- } else if (respondWith === "timeout") {
67
- oauthGrantResponse = "timeout";
68
- } else {
69
- oauthGrantResponse = respondWith;
70
- }
71
- };
72
-
73
- const mockRevokeAuthorization = () => {
74
- const outcome = {
75
- actual: new Request("https://example.org"),
76
- expected: new Request("https://dash.cloudflare.com/oauth2/revoke", {
77
- method: "POST",
78
- }),
79
- };
80
-
81
- fetchMock.mockIf(outcome.expected.url, async (req) => {
82
- outcome.actual = req;
83
- return "";
84
- });
85
-
86
- return outcome;
87
- };
88
-
89
- const mockGetMemberships = (args: {
90
- success: boolean;
91
- result: { id: string; account: { id: string; name: string } }[];
92
- }) => {
93
- const outcome = {
94
- actual: new Request("https://example.org"),
95
- expected: new Request(`${getCloudflareApiBaseUrl()}/memberships`, {
96
- method: "GET",
97
- }),
98
- };
99
-
100
- fetchMock.mockIf(outcome.expected.url, async (req) => {
101
- outcome.actual = req;
102
- return {
103
- status: 200,
104
- body: JSON.stringify(args),
105
- };
106
- });
107
-
108
- return outcome;
109
- };
110
-
111
- const mockGrantAccessToken = ({
112
- respondWith,
113
- }: {
114
- respondWith: MockTokenResponse;
115
- }) => {
116
- const outcome = {
117
- actual: new Request("https://example.org"),
118
- expected: new Request("https://dash.cloudflare.com/oauth2/token", {
119
- method: "POST",
120
- }),
121
- };
122
-
123
- fetchMock.mockOnceIf(outcome.expected.url, async (req) => {
124
- outcome.actual = req;
125
- return makeTokenResponse(respondWith);
126
- });
127
-
128
- return outcome;
129
- };
130
-
131
- const mockExchangeRefreshTokenForAccessToken = ({
132
- respondWith,
133
- }: {
134
- respondWith: "refreshSuccess" | "refreshError" | "badResponse";
135
- }) => {
136
- fetchMock.mockOnceIf(
137
- "https://dash.cloudflare.com/oauth2/token",
138
- async () => {
139
- switch (respondWith) {
140
- case "refreshSuccess":
141
- return {
142
- status: 200,
143
- body: JSON.stringify({
144
- access_token: "access_token_success_mock",
145
- expires_in: 1701,
146
- refresh_token: "refresh_token_sucess_mock",
147
- scope: "scope_success_mock",
148
- token_type: "bearer",
149
- }),
150
- };
151
- case "refreshError":
152
- return {
153
- status: 400,
154
- body: JSON.stringify({
155
- error: "invalid_request",
156
- error_description: "error_description_mock",
157
- error_hint: "error_hint_mock",
158
- error_verbose: "error_verbose_mock",
159
- status_code: 400,
160
- }),
161
- };
162
- case "badResponse":
163
- return {
164
- status: 400,
165
- body: `<html> <body> This shouldn't be sent, but should be handled </body> </html>`,
166
- };
167
-
168
- default:
169
- return "Not a respondWith option for `mockExchangeRefreshTokenForAccessToken`";
170
- }
171
- }
172
- );
173
- };
174
-
175
- return {
176
- mockGetMemberships,
177
- mockGrantAccessToken,
178
- mockGrantAuthorization,
179
- mockOAuthServerCallback,
180
- mockRevokeAuthorization,
181
- mockExchangeRefreshTokenForAccessToken,
182
- };
183
- };
184
-
185
- type GrantResponseOptions = {
186
- code?: string;
187
- error?: ErrorType | ErrorType[];
188
- };
189
-
190
- const toQueryParams = (
191
- { code, error }: GrantResponseOptions,
192
- wranglerRequestParams: URLSearchParams
193
- ): string => {
194
- const queryParams = [];
195
- if (code) {
196
- queryParams.push(`code=${code}`);
197
- }
198
- if (error) {
199
- const stringifiedErr = Array.isArray(error) ? error.join(",") : error;
200
- queryParams.push(`error=${stringifiedErr}`);
201
- }
202
-
203
- queryParams.push(`state=${wranglerRequestParams.get("state")}`);
204
-
205
- return queryParams.join("&");
206
- };
207
-
208
- type ErrorType =
209
- | "invalid_request"
210
- | "invalid_grant"
211
- | "unauthorized_client"
212
- | "access_denied"
213
- | "unsupported_response_type"
214
- | "invalid_scope"
215
- | "server_error"
216
- | "temporarily_unavailable"
217
- | "invalid_client"
218
- | "unsupported_grant_type"
219
- | "invalid_json"
220
- | "invalid_token"
221
- | "test-token-grant-error";
222
-
223
- type MockTokenResponse =
224
- | "ok"
225
- | "error"
226
- | {
227
- access_token: string;
228
- expires_in: number;
229
- refresh_token: string;
230
- scope: string;
231
- }
232
- | {
233
- error: ErrorType;
234
- };
235
-
236
- const makeTokenResponse = (partialResponse: MockTokenResponse): string => {
237
- let fullResponse: MockTokenResponse;
238
-
239
- if (partialResponse === "ok") {
240
- fullResponse = {
241
- access_token: "test-access-token",
242
- expires_in: 100000,
243
- refresh_token: "test-refresh-token",
244
- scope: "account:read",
245
- };
246
- } else if (partialResponse === "error") {
247
- fullResponse = {
248
- error: "test-token-grant-error",
249
- };
250
- } else {
251
- fullResponse = partialResponse;
252
- }
253
-
254
- return JSON.stringify(fullResponse);
255
- };
@@ -1,103 +0,0 @@
1
- const ORIGINAL_STDIN = process.stdin;
2
-
3
- /**
4
- * Mock process.stdin so that we can pipe in text for non-interactive mode tests.
5
- */
6
- export function useMockStdin({ isTTY }: { isTTY: boolean }) {
7
- const mockStdin = new MockStdIn(isTTY);
8
-
9
- beforeEach(() => {
10
- mockStdin.reset();
11
- Object.defineProperty(process, "stdin", {
12
- value: mockStdin,
13
- configurable: true,
14
- writable: false,
15
- });
16
- });
17
-
18
- afterEach(() => {
19
- Object.defineProperty(process, "stdin", {
20
- value: ORIGINAL_STDIN,
21
- configurable: true,
22
- writable: false,
23
- });
24
- });
25
-
26
- return mockStdin;
27
- }
28
-
29
- const failCallback: (value: unknown) => void = () => {
30
- throw new Error(
31
- "TEST FAILURE: stdin callback called before being initialized."
32
- );
33
- };
34
-
35
- /**
36
- * A mock version of `process.std`, which can be used to simulate piping data
37
- * into the wrangler process in non-interactive mode.
38
- */
39
- class MockStdIn {
40
- private endCallback = failCallback;
41
- private errorCallback = failCallback;
42
- private chunks: string[] = [];
43
- private error: Error | undefined;
44
-
45
- /**
46
- * Set this to true if you want the stdin stream to error.
47
- */
48
- throwError(error: Error) {
49
- this.error = error;
50
- }
51
-
52
- /**
53
- * Call this to clean out the chunks that are queued for sending.
54
- */
55
- reset() {
56
- this.chunks.length = 0;
57
- this.error = undefined;
58
- }
59
-
60
- /**
61
- * Queue up some chunks to be sent.
62
- */
63
- send(...chunks: string[]) {
64
- this.chunks.push(...chunks);
65
- }
66
-
67
- constructor(
68
- /**
69
- * Used by wrangler to check whether stdin is interactive.
70
- */
71
- readonly isTTY: boolean
72
- ) {}
73
-
74
- /**
75
- * Used by wrangler to add event listeners.
76
- */
77
- on(eventName: string, callback: () => void) {
78
- switch (eventName) {
79
- case "readable":
80
- setImmediate(callback);
81
- break;
82
- case "end":
83
- this.endCallback = callback;
84
- break;
85
- case "error":
86
- this.errorCallback = callback;
87
- break;
88
- }
89
- }
90
-
91
- /**
92
- * Used by wrangler to get the next chunk of data in the stream.
93
- */
94
- read() {
95
- if (this.error) {
96
- setImmediate(() => this.errorCallback(this.error));
97
- }
98
- if (this.chunks.length === 0) {
99
- setImmediate(this.endCallback);
100
- }
101
- return this.chunks.shift() ?? null;
102
- }
103
- }
@@ -1,29 +0,0 @@
1
- import { WebSocket } from "mock-socket";
2
-
3
- /**
4
- * A version of the mock WebSocket that supports the methods that we use.
5
- */
6
- export class MockWebSocket extends WebSocket {
7
- on(event: string | symbol, listener: (...args: unknown[]) => void): this {
8
- switch (event) {
9
- case "message":
10
- this.onmessage = ({ data }) => {
11
- listener(data);
12
- };
13
- break;
14
- case "open":
15
- this.onopen = listener;
16
- break;
17
- case "close":
18
- this.onclose = listener;
19
- break;
20
- default:
21
- throw new Error("Unknown event type: " + event.toString());
22
- }
23
- return this;
24
- }
25
-
26
- terminate() {
27
- this.close();
28
- }
29
- }
@@ -1,39 +0,0 @@
1
- import * as fs from "node:fs";
2
- import os from "node:os";
3
- import * as path from "node:path";
4
- import { reinitialiseAuthTokens } from "../../user";
5
-
6
- const originalCwd = process.cwd();
7
-
8
- export function runInTempDir({ homedir }: { homedir?: string } = {}) {
9
- let tmpDir: string;
10
-
11
- beforeAll(() => {
12
- if (tmpDir !== undefined) {
13
- process.chdir(originalCwd);
14
- fs.rmSync(tmpDir, { recursive: true });
15
- }
16
- });
17
-
18
- beforeEach(() => {
19
- tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "wrangler-tests"));
20
- process.chdir(tmpDir);
21
- if (homedir !== undefined) {
22
- // Override where the home directory is so that we can write our own user config,
23
- // without destroying the real thing.
24
- fs.mkdirSync(homedir);
25
- // Note it is very important that we use the "default" value from "node:os" (e.g. `import os from "node:os";`)
26
- // rather than an alias to the module (e.g. `import * as os from "node:os";`).
27
- // This is because the module gets transpiled so that the "method" `homedir()` gets converted to a
28
- // getter that is not configurable (and so cannot be spied upon).
29
- jest.spyOn(os, "homedir").mockReturnValue(homedir);
30
- // Now that we have changed the home directory location, we must reinitialize the user auth state
31
- reinitialiseAuthTokens();
32
- }
33
- });
34
-
35
- afterEach(() => {
36
- process.chdir(originalCwd);
37
- fs.rmSync(tmpDir, { recursive: true });
38
- });
39
- }
@@ -1,16 +0,0 @@
1
- import { main } from "../../index";
2
- import { normalizeSlashes, stripTimings } from "./mock-console";
3
-
4
- /**
5
- * A helper to 'run' wrangler commands for tests.
6
- */
7
- export async function runWrangler(cmd?: string) {
8
- try {
9
- await main(cmd?.split(" ") ?? []);
10
- } catch (err) {
11
- if (err instanceof Error) {
12
- err.message = normalizeSlashes(stripTimings(err.message));
13
- }
14
- throw err;
15
- }
16
- }
@@ -1,31 +0,0 @@
1
- import fs from "node:fs";
2
-
3
- /** Write a mock Worker script to disk. */
4
- export function writeWorkerSource({
5
- basePath = ".",
6
- format = "js",
7
- type = "esm",
8
- }: {
9
- basePath?: string;
10
- format?: "js" | "ts" | "jsx" | "tsx" | "mjs";
11
- type?: "esm" | "sw";
12
- } = {}) {
13
- if (basePath !== ".") {
14
- fs.mkdirSync(basePath, { recursive: true });
15
- }
16
- fs.writeFileSync(
17
- `${basePath}/index.${format}`,
18
- type === "esm"
19
- ? `import { foo } from "./another";
20
- export default {
21
- async fetch(request) {
22
- return new Response('Hello' + foo);
23
- },
24
- };`
25
- : `import { foo } from "./another";
26
- addEventListener('fetch', event => {
27
- event.respondWith(new Response('Hello' + foo));
28
- })`
29
- );
30
- fs.writeFileSync(`${basePath}/another.${format}`, `export const foo = 100;`);
31
- }
@@ -1,17 +0,0 @@
1
- import * as fs from "fs";
2
- import TOML from "@iarna/toml";
3
- import type { RawConfig } from "../../config";
4
-
5
- /** Write a mock wrangler.toml file to disk. */
6
- export default function writeWranglerToml(config: RawConfig = {}) {
7
- fs.writeFileSync(
8
- "./wrangler.toml",
9
- TOML.stringify({
10
- compatibility_date: "2022-01-12",
11
- name: "test-name",
12
- ...(config as TOML.JsonMap),
13
- }),
14
-
15
- "utf-8"
16
- );
17
- }
@@ -1,130 +0,0 @@
1
- import fs from "node:fs";
2
- import os from "node:os";
3
- import { resolve } from "node:path";
4
- import { getHttpsOptions } from "../https-options";
5
- import { mockConsoleMethods } from "./helpers/mock-console";
6
- import { runInTempDir } from "./helpers/run-in-tmp";
7
-
8
- describe("getHttpsOptions()", () => {
9
- runInTempDir({ homedir: "./home" });
10
- const std = mockConsoleMethods();
11
-
12
- it("should use cached values if they have not expired", async () => {
13
- fs.mkdirSync(resolve(os.homedir(), ".wrangler/local-cert"), {
14
- recursive: true,
15
- });
16
- fs.writeFileSync(
17
- resolve(os.homedir(), ".wrangler/local-cert/key.pem"),
18
- "PRIVATE KEY"
19
- );
20
- fs.writeFileSync(
21
- resolve(os.homedir(), ".wrangler/local-cert/cert.pem"),
22
- "PUBLIC KEY"
23
- );
24
- const result = await getHttpsOptions();
25
- expect(result.key).toEqual("PRIVATE KEY");
26
- expect(result.cert).toEqual("PUBLIC KEY");
27
- expect(std.out).toMatchInlineSnapshot(`""`);
28
- expect(std.warn).toMatchInlineSnapshot(`""`);
29
- expect(std.err).toMatchInlineSnapshot(`""`);
30
- });
31
-
32
- it("should generate and cache new keys if none are cached", async () => {
33
- const result = await getHttpsOptions();
34
- const key = fs.readFileSync(
35
- resolve(os.homedir(), ".wrangler/local-cert/key.pem"),
36
- "utf8"
37
- );
38
- const cert = fs.readFileSync(
39
- resolve(os.homedir(), ".wrangler/local-cert/cert.pem"),
40
- "utf8"
41
- );
42
- expect(result.key).toEqual(key);
43
- expect(result.cert).toEqual(cert);
44
- expect(std.out).toMatchInlineSnapshot(
45
- `"Generating new self-signed certificate..."`
46
- );
47
- expect(std.warn).toMatchInlineSnapshot(`""`);
48
- expect(std.err).toMatchInlineSnapshot(`""`);
49
- });
50
-
51
- it("should generate and cache new keys if cached files have expired", async () => {
52
- fs.mkdirSync(resolve(os.homedir(), ".wrangler/local-cert"), {
53
- recursive: true,
54
- });
55
- const ORIGINAL_KEY = "EXPIRED PRIVATE KEY";
56
- const ORIGINAL_CERT = "EXPIRED PUBLIC KEY";
57
- fs.writeFileSync(
58
- resolve(os.homedir(), ".wrangler/local-cert/key.pem"),
59
- ORIGINAL_KEY
60
- );
61
- fs.writeFileSync(
62
- resolve(os.homedir(), ".wrangler/local-cert/cert.pem"),
63
- ORIGINAL_CERT
64
- );
65
- mockStatSync(/\.pem$/, { mtimeMs: new Date(2000).valueOf() });
66
-
67
- const result = await getHttpsOptions();
68
- const key = fs.readFileSync(
69
- resolve(os.homedir(), ".wrangler/local-cert/key.pem"),
70
- "utf8"
71
- );
72
- const cert = fs.readFileSync(
73
- resolve(os.homedir(), ".wrangler/local-cert/cert.pem"),
74
- "utf8"
75
- );
76
- expect(key).not.toEqual(ORIGINAL_KEY);
77
- expect(cert).not.toEqual(ORIGINAL_CERT);
78
- expect(result.key).toEqual(key);
79
- expect(result.cert).toEqual(cert);
80
- expect(std.out).toMatchInlineSnapshot(
81
- `"Generating new self-signed certificate..."`
82
- );
83
- expect(std.warn).toMatchInlineSnapshot(`""`);
84
- expect(std.err).toMatchInlineSnapshot(`""`);
85
- });
86
-
87
- it("should warn if not able to write to the cache", async () => {
88
- mockWriteFileSyncThrow(/\.pem$/);
89
- await getHttpsOptions();
90
- expect(
91
- fs.existsSync(resolve(os.homedir(), ".wrangler/local-cert/key.pem"))
92
- ).toBe(false);
93
- expect(
94
- fs.existsSync(resolve(os.homedir(), ".wrangler/local-cert/cert.pem"))
95
- ).toBe(false);
96
- expect(std.out).toMatchInlineSnapshot(
97
- `"Generating new self-signed certificate..."`
98
- );
99
- expect(std.warn).toMatchInlineSnapshot(`
100
- "â–² [WARNING] Unable to cache generated self-signed certificate in home/.wrangler/local-cert.
101
-
102
- ERROR: Cannot write file
103
-
104
- "
105
- `);
106
- expect(std.err).toMatchInlineSnapshot(`""`);
107
- });
108
- });
109
-
110
- function mockStatSync(matcher: RegExp, stats: Partial<fs.Stats>) {
111
- const originalStatSync = jest.requireActual("node:fs").statSync;
112
- jest.spyOn(fs, "statSync").mockImplementation((statPath, options) => {
113
- return matcher.test(statPath.toString())
114
- ? (stats as fs.Stats)
115
- : originalStatSync(statPath, options);
116
- });
117
- }
118
-
119
- function mockWriteFileSyncThrow(matcher: RegExp) {
120
- const originalWriteFileSync = jest.requireActual("node:fs").writeFileSync;
121
- jest
122
- .spyOn(fs, "writeFileSync")
123
- .mockImplementation((filePath, data, options) => {
124
- if (matcher.test(filePath.toString())) {
125
- throw new Error("ERROR: Cannot write file");
126
- } else {
127
- return originalWriteFileSync(filePath, data, options);
128
- }
129
- });
130
- }