wrangler 0.0.0-e8e684c7 → 0.0.0-e9106dfa5

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 (207) hide show
  1. package/README.md +35 -49
  2. package/bin/wrangler.js +25 -100
  3. package/config-schema.json +2277 -0
  4. package/package.json +182 -174
  5. package/templates/__tests__/pages-dev-util.test.ts +128 -0
  6. package/templates/__tests__/tsconfig-sanity.ts +12 -0
  7. package/templates/__tests__/tsconfig.json +8 -0
  8. package/templates/checked-fetch.js +19 -6
  9. package/templates/facade.d.ts +19 -0
  10. package/templates/gitignore +2 -3
  11. package/templates/init-tests/test-jest-new-worker.js +23 -0
  12. package/templates/init-tests/test-vitest-new-worker.js +24 -0
  13. package/templates/init-tests/test-vitest-new-worker.ts +25 -0
  14. package/templates/middleware/common.ts +67 -0
  15. package/templates/middleware/loader-modules.ts +134 -0
  16. package/templates/middleware/loader-sw.ts +229 -0
  17. package/templates/middleware/middleware-ensure-req-body-drained.ts +18 -0
  18. package/templates/middleware/middleware-miniflare3-json-error.ts +32 -0
  19. package/templates/middleware/middleware-mock-analytics-engine.d.ts +3 -0
  20. package/templates/middleware/middleware-mock-analytics-engine.ts +30 -0
  21. package/templates/middleware/middleware-patch-console-prefix.d.ts +3 -0
  22. package/templates/middleware/middleware-patch-console-prefix.ts +21 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +29 -0
  25. package/templates/modules-watch-stub.js +4 -0
  26. package/templates/new-worker-scheduled.ts +1 -1
  27. package/templates/new-worker.js +1 -1
  28. package/templates/new-worker.ts +4 -1
  29. package/templates/pages-dev-pipeline.ts +33 -0
  30. package/templates/pages-dev-util.ts +55 -0
  31. package/templates/pages-shim.ts +1 -1
  32. package/templates/pages-template-plugin.ts +37 -14
  33. package/templates/pages-template-worker.ts +33 -7
  34. package/templates/startDevWorker/InspectorProxyWorker.ts +679 -0
  35. package/templates/startDevWorker/ProxyWorker.ts +336 -0
  36. package/templates/tsconfig-sanity.ts +11 -0
  37. package/templates/tsconfig.init.json +22 -0
  38. package/templates/tsconfig.json +12 -102
  39. package/templates/tsconfig.tsbuildinfo +1 -0
  40. package/wrangler-dist/InspectorProxyWorker.js +471 -0
  41. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  42. package/wrangler-dist/ProxyWorker.js +238 -0
  43. package/wrangler-dist/ProxyWorker.js.map +6 -0
  44. package/wrangler-dist/cli.d.ts +26527 -172
  45. package/wrangler-dist/cli.js +148646 -148093
  46. package/Cloudflare_CA.pem +0 -18
  47. package/import_meta_url.js +0 -3
  48. package/miniflare-config-stubs/.env.empty +0 -0
  49. package/miniflare-config-stubs/package.empty.json +0 -1
  50. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  51. package/miniflare-dist/index.mjs +0 -5542
  52. package/src/__tests__/config-cache-without-cache-dir.test.ts +0 -38
  53. package/src/__tests__/config-cache.test.ts +0 -42
  54. package/src/__tests__/configuration.test.ts +0 -4026
  55. package/src/__tests__/dev.test.tsx +0 -1318
  56. package/src/__tests__/generate.test.ts +0 -91
  57. package/src/__tests__/guess-worker-format.test.ts +0 -85
  58. package/src/__tests__/helpers/clipboardy-mock.js +0 -4
  59. package/src/__tests__/helpers/cmd-shim.d.ts +0 -11
  60. package/src/__tests__/helpers/mock-account-id.ts +0 -48
  61. package/src/__tests__/helpers/mock-bin.ts +0 -36
  62. package/src/__tests__/helpers/mock-cfetch.ts +0 -296
  63. package/src/__tests__/helpers/mock-console.ts +0 -97
  64. package/src/__tests__/helpers/mock-dialogs.ts +0 -153
  65. package/src/__tests__/helpers/mock-get-zone-from-host.ts +0 -8
  66. package/src/__tests__/helpers/mock-http-server.ts +0 -46
  67. package/src/__tests__/helpers/mock-istty.ts +0 -74
  68. package/src/__tests__/helpers/mock-known-routes.ts +0 -7
  69. package/src/__tests__/helpers/mock-kv.ts +0 -33
  70. package/src/__tests__/helpers/mock-oauth-flow.ts +0 -250
  71. package/src/__tests__/helpers/mock-process.ts +0 -39
  72. package/src/__tests__/helpers/mock-stdin.ts +0 -108
  73. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  74. package/src/__tests__/helpers/run-in-tmp.ts +0 -38
  75. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  76. package/src/__tests__/helpers/write-worker-source.ts +0 -31
  77. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  78. package/src/__tests__/https-options.test.ts +0 -163
  79. package/src/__tests__/index.test.ts +0 -245
  80. package/src/__tests__/init.test.ts +0 -2170
  81. package/src/__tests__/jest.setup.ts +0 -157
  82. package/src/__tests__/kv.test.ts +0 -1671
  83. package/src/__tests__/logger.test.ts +0 -141
  84. package/src/__tests__/metrics.test.ts +0 -450
  85. package/src/__tests__/package-manager.test.ts +0 -353
  86. package/src/__tests__/pages.test.ts +0 -1275
  87. package/src/__tests__/parse.test.ts +0 -330
  88. package/src/__tests__/publish.test.ts +0 -6955
  89. package/src/__tests__/pubsub.test.ts +0 -367
  90. package/src/__tests__/r2.test.ts +0 -336
  91. package/src/__tests__/route.test.ts +0 -45
  92. package/src/__tests__/secret.test.ts +0 -492
  93. package/src/__tests__/tail.test.ts +0 -802
  94. package/src/__tests__/test-old-node-version.js +0 -31
  95. package/src/__tests__/user.test.ts +0 -155
  96. package/src/__tests__/validate-dev-props.test.ts +0 -56
  97. package/src/__tests__/version.test.ts +0 -35
  98. package/src/__tests__/whoami.test.tsx +0 -289
  99. package/src/__tests__/worker-namespace.test.ts +0 -329
  100. package/src/abort.d.ts +0 -3
  101. package/src/api/dev.ts +0 -93
  102. package/src/api/index.ts +0 -1
  103. package/src/bundle-reporter.tsx +0 -29
  104. package/src/bundle.ts +0 -473
  105. package/src/cfetch/index.ts +0 -121
  106. package/src/cfetch/internal.ts +0 -298
  107. package/src/cli.ts +0 -27
  108. package/src/config/README.md +0 -107
  109. package/src/config/config.ts +0 -263
  110. package/src/config/diagnostics.ts +0 -80
  111. package/src/config/environment.ts +0 -485
  112. package/src/config/index.ts +0 -251
  113. package/src/config/validation-helpers.ts +0 -597
  114. package/src/config/validation.ts +0 -1862
  115. package/src/config-cache.ts +0 -85
  116. package/src/create-worker-preview.ts +0 -257
  117. package/src/create-worker-upload-form.ts +0 -291
  118. package/src/dev/dev-vars.ts +0 -36
  119. package/src/dev/dev.tsx +0 -545
  120. package/src/dev/local.tsx +0 -449
  121. package/src/dev/remote.tsx +0 -422
  122. package/src/dev/use-esbuild.ts +0 -178
  123. package/src/dev/validate-dev-props.ts +0 -31
  124. package/src/dev-registry.tsx +0 -160
  125. package/src/dev.tsx +0 -696
  126. package/src/dialogs.tsx +0 -135
  127. package/src/dispatch-namespace.ts +0 -206
  128. package/src/durable.ts +0 -102
  129. package/src/entry.ts +0 -328
  130. package/src/environment-variables.ts +0 -35
  131. package/src/errors.ts +0 -11
  132. package/src/faye-websocket.d.ts +0 -6
  133. package/src/generate.ts +0 -131
  134. package/src/git-client.ts +0 -42
  135. package/src/global-wrangler-config-path.ts +0 -26
  136. package/src/https-options.ts +0 -127
  137. package/src/index.tsx +0 -2260
  138. package/src/init.ts +0 -622
  139. package/src/inspect.ts +0 -747
  140. package/src/intl-polyfill.d.ts +0 -139
  141. package/src/is-ci.ts +0 -14
  142. package/src/is-interactive.ts +0 -12
  143. package/src/kv.ts +0 -430
  144. package/src/logger.ts +0 -73
  145. package/src/metrics/index.ts +0 -5
  146. package/src/metrics/metrics-config.ts +0 -239
  147. package/src/metrics/metrics-dispatcher.ts +0 -96
  148. package/src/metrics/metrics-usage-headers.ts +0 -24
  149. package/src/metrics/send-event.ts +0 -92
  150. package/src/miniflare-cli/README.md +0 -30
  151. package/src/miniflare-cli/assets.ts +0 -554
  152. package/src/miniflare-cli/enum-keys.ts +0 -17
  153. package/src/miniflare-cli/index.ts +0 -207
  154. package/src/miniflare-cli/request-context.ts +0 -40
  155. package/src/module-collection.ts +0 -258
  156. package/src/open-in-browser.ts +0 -17
  157. package/src/package-manager.ts +0 -219
  158. package/src/pages/build.tsx +0 -238
  159. package/src/pages/constants.ts +0 -12
  160. package/src/pages/deployments.tsx +0 -106
  161. package/src/pages/dev.tsx +0 -528
  162. package/src/pages/errors.ts +0 -22
  163. package/src/pages/functions/buildPlugin.ts +0 -109
  164. package/src/pages/functions/buildWorker.ts +0 -155
  165. package/src/pages/functions/filepath-routing.test.ts +0 -234
  166. package/src/pages/functions/filepath-routing.ts +0 -189
  167. package/src/pages/functions/identifiers.ts +0 -78
  168. package/src/pages/functions/routes-consolidation.test.ts +0 -250
  169. package/src/pages/functions/routes-consolidation.ts +0 -73
  170. package/src/pages/functions/routes-transformation.test.ts +0 -271
  171. package/src/pages/functions/routes-transformation.ts +0 -122
  172. package/src/pages/functions/routes.ts +0 -151
  173. package/src/pages/functions.tsx +0 -96
  174. package/src/pages/index.tsx +0 -94
  175. package/src/pages/projects.tsx +0 -169
  176. package/src/pages/publish.tsx +0 -391
  177. package/src/pages/types.ts +0 -49
  178. package/src/pages/upload.tsx +0 -413
  179. package/src/pages/utils.ts +0 -12
  180. package/src/parse.ts +0 -286
  181. package/src/paths.ts +0 -26
  182. package/src/preview.ts +0 -31
  183. package/src/proxy.ts +0 -486
  184. package/src/publish.ts +0 -822
  185. package/src/pubsub/index.ts +0 -286
  186. package/src/pubsub/pubsub-commands.tsx +0 -623
  187. package/src/r2.ts +0 -131
  188. package/src/selfsigned.d.ts +0 -29
  189. package/src/sites.tsx +0 -372
  190. package/src/tail/filters.ts +0 -281
  191. package/src/tail/index.ts +0 -312
  192. package/src/tail/printing.ts +0 -107
  193. package/src/update-check.ts +0 -19
  194. package/src/user/choose-account.tsx +0 -69
  195. package/src/user/env-vars.ts +0 -46
  196. package/src/user/generate-auth-url.ts +0 -33
  197. package/src/user/generate-random-state.ts +0 -16
  198. package/src/user/index.ts +0 -3
  199. package/src/user/user.tsx +0 -1191
  200. package/src/whoami.tsx +0 -169
  201. package/src/worker.ts +0 -204
  202. package/src/zones.ts +0 -167
  203. package/templates/first-party-worker-module-facade.ts +0 -18
  204. package/templates/format-dev-errors.ts +0 -32
  205. package/templates/serve-static-assets.ts +0 -63
  206. package/templates/service-bindings-module-facade.js +0 -54
  207. package/templates/service-bindings-sw-facade.js +0 -42
@@ -1,281 +0,0 @@
1
- /**
2
- * When tailing logs from a worker, oftentimes you don't want to see _every
3
- * single event_. That's where filters come in. We can send a set of filters
4
- * to the tail worker, and it will pre-filter any logs for us so that we
5
- * only recieve the ones we care about.
6
- */
7
-
8
- /**
9
- * These are the filters we accept in the CLI. They
10
- * were copied directly from wrangler 1 in order to
11
- * maintain compatability, so they aren't actually the exact
12
- * filters we need to send up to the tail worker. They generally map 1:1,
13
- * but often require some transformation or
14
- * renaming to match what it expects.
15
- *
16
- * For a full description of each filter, either check the
17
- * CLI description or see the documentation for `ApiFilter`.
18
- */
19
- export type TailCLIFilters = {
20
- status?: ("ok" | "error" | "canceled")[];
21
- header?: string;
22
- method?: string[];
23
- search?: string;
24
- samplingRate?: number;
25
- clientIp?: string[];
26
- };
27
-
28
- /**
29
- * These are the filters we send to the tail worker. We
30
- * actually send a list of filters (an array of objects),
31
- * so rather than having a single TailAPIFilters type,
32
- * each kind of filter gets its own type and we define
33
- * TailAPIFilter to be the union of those types.
34
- */
35
- export type TailAPIFilter =
36
- | SamplingRateFilter
37
- | OutcomeFilter
38
- | MethodFilter
39
- | HeaderFilter
40
- | ClientIPFilter
41
- | QueryFilter;
42
-
43
- /**
44
- * Filters logs based on a given sampling rate.
45
- * For example, a `sampling_rate` of 0.25 will let one-quarter of the
46
- * logs through.
47
- */
48
- type SamplingRateFilter = {
49
- sampling_rate: number;
50
- };
51
-
52
- /**
53
- * Filters logs based on the outcome of the worker's event handler.
54
- */
55
- type OutcomeFilter = {
56
- outcome: Outcome[];
57
- };
58
-
59
- /**
60
- * There are five possible outcomes we can get, three of which
61
- * (exception, exceededCpu, exceededMemory, and unknown) are considered errors
62
- */
63
- export type Outcome =
64
- | "ok"
65
- | "canceled"
66
- | "exception"
67
- | "exceededCpu"
68
- | "exceededMemory"
69
- | "unknown";
70
-
71
- /**
72
- * Filters logs based on the HTTP method used for the request
73
- * that triggered the worker.
74
- */
75
- type MethodFilter = {
76
- method: string[];
77
- };
78
-
79
- /**
80
- * Filters logs based on an HTTP header on the request that
81
- * triggered the worker.
82
- */
83
- type HeaderFilter = {
84
- header: {
85
- /**
86
- * Filters on the header "key", e.g. "X-CLOUDFLARE-HEADER"
87
- * or "X-CUSTOM-HEADER"
88
- */
89
- key: string;
90
-
91
- /**
92
- * Filters on the header "value", e.g. if this is set to
93
- * "filter-for-me" and the "key" is "X-SHOULD-LOG", only
94
- * events triggered by requests with the header
95
- * "X-SHOULD-LOG:filter-for-me" will be logged.
96
- */
97
- query?: string;
98
- };
99
- };
100
-
101
- /**
102
- * Filters on the IP address the request came from that triggered
103
- * the worker. A value of "self" will be replaced with the IP
104
- * address that is running `wrangler tail`
105
- */
106
- type ClientIPFilter = {
107
- client_ip: string[];
108
- };
109
-
110
- /**
111
- * Filters logs by a query string. This means only logs that
112
- * contain the given string will be sent to wrangler, and any
113
- * that don't will be discarded by the tail worker.
114
- */
115
- type QueryFilter = {
116
- query: string;
117
- };
118
-
119
- /**
120
- * The full message we send to the tail worker includes our
121
- * filters and a debug flag.
122
- */
123
- export type TailFilterMessage = {
124
- filters: TailAPIFilter[];
125
- debug: boolean;
126
- };
127
-
128
- /**
129
- * Translate the flags passed in via a CLI invokation of wrangler
130
- * into a message that we can send to the tail worker.
131
- *
132
- * @param cliFilters An object containing all the filters passed in from the CLI
133
- * @param debug Whether or not we should be in debug mode
134
- * @returns A filter message ready to be sent to the tail worker
135
- */
136
- export function translateCLICommandToFilterMessage(
137
- cliFilters: TailCLIFilters,
138
- debug: boolean
139
- ): TailFilterMessage {
140
- const apiFilters: TailAPIFilter[] = [];
141
-
142
- if (cliFilters.samplingRate) {
143
- apiFilters.push(parseSamplingRate(cliFilters.samplingRate));
144
- }
145
-
146
- if (cliFilters.status) {
147
- apiFilters.push(parseOutcome(cliFilters.status));
148
- }
149
-
150
- if (cliFilters.method) {
151
- apiFilters.push(parseMethod(cliFilters.method));
152
- }
153
-
154
- if (cliFilters.header) {
155
- apiFilters.push(parseHeader(cliFilters.header));
156
- }
157
-
158
- if (cliFilters.clientIp) {
159
- apiFilters.push(parseIP(cliFilters.clientIp));
160
- }
161
-
162
- if (cliFilters.search) {
163
- apiFilters.push(parseQuery(cliFilters.search));
164
- }
165
-
166
- return {
167
- filters: apiFilters,
168
- debug,
169
- };
170
- }
171
-
172
- /**
173
- * Parse the sampling rate passed in via command line
174
- *
175
- * @param sampling_rate the sampling rate passed in via CLI
176
- * @throws an Error if the rate doesn't make sense
177
- * @returns a SamplingRateFilter for use with the API
178
- */
179
- function parseSamplingRate(sampling_rate: number): SamplingRateFilter {
180
- if (sampling_rate <= 0 || sampling_rate >= 1) {
181
- throw new Error(
182
- "A sampling rate must be between 0 and 1 in order to have any effect.\nFor example, a sampling rate of 0.25 means 25% of events will be logged."
183
- );
184
- }
185
-
186
- return { sampling_rate };
187
- }
188
-
189
- /**
190
- * Translate from CLI "status"es to API "outcome"s, including
191
- * broadening "error" into "exception", "exceededCpu", and "unknown".
192
- *
193
- * @param statuses statuses passed in via CLI
194
- * @returns an OutcomeFilter for use with the API
195
- */
196
- function parseOutcome(
197
- statuses: ("ok" | "error" | "canceled")[]
198
- ): OutcomeFilter {
199
- const outcomes = new Set<Outcome>();
200
-
201
- for (const status of statuses) {
202
- switch (status) {
203
- case "ok":
204
- outcomes.add("ok");
205
- break;
206
-
207
- case "canceled":
208
- outcomes.add("canceled");
209
- break;
210
-
211
- case "error":
212
- outcomes.add("exception");
213
- outcomes.add("exceededCpu");
214
- outcomes.add("exceededMemory");
215
- outcomes.add("unknown");
216
- break;
217
-
218
- default:
219
- break;
220
- }
221
- }
222
-
223
- return {
224
- outcome: Array.from(outcomes),
225
- };
226
- }
227
-
228
- /**
229
- * We just send silly methods through to the API anyway, since they don't
230
- * cause any harm.
231
- *
232
- * @param method an array of HTTP request methods passed in via CLI
233
- * @returns a MethodFilter for use with the API
234
- */
235
- function parseMethod(method: string[]): MethodFilter {
236
- return { method };
237
- }
238
-
239
- /**
240
- * Header filters can contain either just a key ("X-HEADER-KEY") or both
241
- * a key and a value ("X-HEADER-KEY:some-value"). This function parses
242
- * a given string according to that pattern.
243
- *
244
- * @param header a header string, "X-HEADER-KEY" or "X-HEADER-KEY:some-value"
245
- * @returns a HeaderFilter for use with the API
246
- */
247
- function parseHeader(header: string): HeaderFilter {
248
- const [headerKey, headerQuery] = header.split(":", 2);
249
-
250
- return {
251
- header: {
252
- key: headerKey.trim(),
253
- query: headerQuery?.trim(),
254
- },
255
- };
256
- }
257
-
258
- /**
259
- * A list of IPs can be passed in to filter for messages that come from
260
- * a worker triggered by a request originating from one of those IPs.
261
- * You can also pass in the string "self" to filter for the IP of the
262
- * machine running `wrangler tail`.
263
- *
264
- * @param client_ip an array of IP addresses to filter
265
- * @returns a ClientIPFilter for use with the API
266
- */
267
- function parseIP(client_ip: string[]): ClientIPFilter {
268
- return { client_ip };
269
- }
270
-
271
- /**
272
- * Users can filter for logs that contain a "search" or a "query string".
273
- * For example, if `--search findme` is passed to then we will only
274
- * receive logs that contain the string "findme".
275
- *
276
- * @param query a query string to search for
277
- * @returns a QueryFilter for use with the API
278
- */
279
- function parseQuery(query: string): QueryFilter {
280
- return { query };
281
- }
package/src/tail/index.ts DELETED
@@ -1,312 +0,0 @@
1
- import WebSocket from "ws";
2
- import { version as packageVersion } from "../../package.json";
3
- import { fetchResult } from "../cfetch";
4
- import type { TailFilterMessage, Outcome } from "./filters";
5
- export type { TailCLIFilters } from "./filters";
6
- export { translateCLICommandToFilterMessage } from "./filters";
7
- export { jsonPrintLogs, prettyPrintLogs } from "./printing";
8
- import type { Request } from "undici";
9
-
10
- /**
11
- * When creating a Tail, the response from the API contains
12
- * - an ID used for identifying the tail
13
- * - a URL to a WebSocket connection available for the tail to connect to
14
- * - an expiration date when the tail is no longer guaranteed to be valid
15
- */
16
- type TailCreationApiResponse = {
17
- id: string;
18
- url: string;
19
- expires_at: Date;
20
- };
21
-
22
- /**
23
- * Generate a URL that, when `cfetch`ed, creates a tail.
24
- *
25
- * https://api.cloudflare.com/#worker-tail-logs-start-tail
26
- *
27
- * @param accountId the account ID associated with the worker to tail
28
- * @param workerName the name of the worker to tail
29
- * @returns a `cfetch`-ready URL for creating a new tail
30
- */
31
- function makeCreateTailUrl(
32
- accountId: string,
33
- workerName: string,
34
- env: string | undefined
35
- ): string {
36
- return env
37
- ? `/accounts/${accountId}/workers/services/${workerName}/environments/${env}/tails`
38
- : `/accounts/${accountId}/workers/scripts/${workerName}/tails`;
39
- }
40
-
41
- /**
42
- * Generate a URL that, when `cfetch`ed, deletes a tail
43
- *
44
- * https://api.cloudflare.com/#worker-tail-logs-delete-tail
45
- *
46
- * @param accountId the account ID associated with the worker we're tailing
47
- * @param workerName the name of the worker we're tailing
48
- * @param tailId the ID of the tail we want to delete
49
- * @returns a `cfetch`-ready URL for deleting a tail
50
- */
51
- function makeDeleteTailUrl(
52
- accountId: string,
53
- workerName: string,
54
- tailId: string,
55
- env: string | undefined
56
- ): string {
57
- return env
58
- ? `/accounts/${accountId}/workers/services/${workerName}/environments/${env}/tails/${tailId}`
59
- : `/accounts/${accountId}/workers/scripts/${workerName}/tails/${tailId}`;
60
- }
61
-
62
- /**
63
- * Create and connect to a tail.
64
- *
65
- * Under the hood, this function
66
- * - Registers a new Tail with the API
67
- * - Connects to the tail worker
68
- * - Sends any filters over the connection
69
- *
70
- * @param accountId the account ID associated with the worker to tail
71
- * @param workerName the name of the worker to tail
72
- * @param message a `TailFilterMessage` to send up to the tail worker
73
- * @returns a websocket connection, an expiration, and a function to call to delete the tail
74
- */
75
- export async function createTail(
76
- accountId: string,
77
- workerName: string,
78
- message: TailFilterMessage,
79
- env: string | undefined
80
- ): Promise<{
81
- tail: WebSocket;
82
- expiration: Date;
83
- deleteTail: () => Promise<void>;
84
- }> {
85
- // create the tail
86
- const createTailUrl = makeCreateTailUrl(accountId, workerName, env);
87
- const {
88
- id: tailId,
89
- url: websocketUrl,
90
- expires_at: expiration,
91
- } = await fetchResult<TailCreationApiResponse>(createTailUrl, {
92
- method: "POST",
93
- });
94
-
95
- // delete the tail (not yet!)
96
- const deleteUrl = makeDeleteTailUrl(accountId, workerName, tailId, env);
97
- async function deleteTail() {
98
- await fetchResult(deleteUrl, { method: "DELETE" });
99
- }
100
-
101
- // connect to the tail
102
- const tail = new WebSocket(websocketUrl, "trace-v1", {
103
- headers: {
104
- "Sec-WebSocket-Protocol": "trace-v1", // needs to be `trace-v1` to be accepted
105
- "User-Agent": `wrangler-js/${packageVersion}`,
106
- },
107
- });
108
-
109
- // send filters when we open up
110
- tail.on("open", function () {
111
- tail.send(
112
- JSON.stringify(message),
113
- { binary: false, compress: false, mask: false, fin: true },
114
- (err) => {
115
- if (err) {
116
- throw err;
117
- }
118
- }
119
- );
120
- });
121
-
122
- return { tail, expiration, deleteTail };
123
- }
124
-
125
- /**
126
- * Everything captured by the trace worker and sent to us via
127
- * `wrangler tail` is structured JSON that deserializes to this type.
128
- */
129
- export type TailEventMessage = {
130
- /**
131
- * Whether the execution of this worker succeeded or failed
132
- */
133
- outcome: Outcome;
134
-
135
- /**
136
- * The name of the script we're tailing
137
- */
138
- scriptName?: string;
139
-
140
- /**
141
- * Any exceptions raised by the worker
142
- */
143
- exceptions: {
144
- /**
145
- * The name of the exception.
146
- */
147
- name: string;
148
-
149
- /**
150
- * The error message
151
- */
152
- message: unknown;
153
-
154
- /**
155
- * When the exception was raised/thrown
156
- */
157
- timestamp: number;
158
- }[];
159
-
160
- /**
161
- * Any logs sent out by the worker
162
- */
163
- logs: {
164
- message: unknown[];
165
- level: string; // TODO: make this a union of possible values
166
- timestamp: number;
167
- }[];
168
-
169
- /**
170
- * When the event was triggered
171
- */
172
- eventTimestamp: number;
173
-
174
- /**
175
- * The event that triggered the worker. In the case of an HTTP request,
176
- * this will be a RequestEvent. If it's a cron trigger, it'll be a
177
- * ScheduledEvent. If it's a durable object alarm, it's an AlarmEvent.
178
- *
179
- * Until workers-types exposes individual types for export, we'll have
180
- * to just re-define these types ourselves.
181
- */
182
- event: RequestEvent | ScheduledEvent | AlarmEvent | undefined | null;
183
- };
184
-
185
- /**
186
- * A request that triggered worker execution
187
- */
188
-
189
- export type RequestEvent = {
190
- request: Pick<Request, "url" | "method" | "headers"> & {
191
- /**
192
- * Cloudflare-specific properties
193
- * https://developers.cloudflare.com/workers/runtime-apis/request#incomingrequestcfproperties
194
- */
195
- cf: {
196
- /**
197
- * How long (in ms) it took for the client's TCP connection to make a
198
- * round trip to the worker and back. For all my gamers out there,
199
- * this is the request's ping
200
- */
201
- clientTcpRtt?: number;
202
-
203
- /**
204
- * Longitude and Latitude of where the request originated from
205
- */
206
- longitude?: string;
207
- latitude?: string;
208
-
209
- /**
210
- * What cipher was used to establish the TLS connection
211
- */
212
- tlsCipher: string;
213
-
214
- /**
215
- * Which continent the request came from.
216
- */
217
- continent?: "NA";
218
-
219
- /**
220
- * ASN of the incoming request
221
- */
222
- asn: number;
223
-
224
- /**
225
- * The country the incoming request is coming from
226
- */
227
- country?: string;
228
-
229
- /**
230
- * The TLS version the connection used
231
- */
232
- tlsVersion: string;
233
-
234
- /**
235
- * The colo that processed the request (i.e. the airport code
236
- * of the closest city to the server that spun up the worker)
237
- */
238
- colo: string;
239
-
240
- /**
241
- * The timezone where the request came from
242
- */
243
- timezone?: string;
244
-
245
- /**
246
- * The city where the request came from
247
- */
248
- city?: string;
249
-
250
- /**
251
- * The browser-requested prioritization information in the request object
252
- */
253
- requestPriority?: string;
254
-
255
- /**
256
- * Which version of HTTP the request came over e.g. "HTTP/2"
257
- */
258
- httpProtocol: string;
259
-
260
- /**
261
- * The region where the request originated from
262
- */
263
- region?: string;
264
- regionCode?: string;
265
-
266
- /**
267
- * The organization which owns the ASN of the incoming request, for example, Google Cloud.
268
- */
269
- asOrganization: string;
270
-
271
- /**
272
- * Metro code (DMA) of the incoming request, for example, "635".
273
- */
274
- metroCode?: string;
275
-
276
- /**
277
- * Postal code of the incoming request, for example, "78701".
278
- */
279
- postalCode?: string;
280
- };
281
- };
282
- };
283
-
284
- /**
285
- * An event that was triggered at a certain time
286
- */
287
- export type ScheduledEvent = {
288
- /**
289
- * The cron pattern that matched when this event fired
290
- */
291
- cron: string;
292
-
293
- /**
294
- * The time this worker was scheduled to run.
295
- * For some reason, this doesn't...work correctly when we
296
- * do it directly as a Date. So parse it later on your own.
297
- */
298
- scheduledTime: number;
299
- };
300
-
301
- /**
302
- * A event that was triggered from a durable object alarm
303
- */
304
- export type AlarmEvent = {
305
- /**
306
- * The datetime the alarm was scheduled for.
307
- *
308
- * This is sent as an ISO timestamp string (different than ScheduledEvent.scheduledTime),
309
- * you should parse it later on on your own.
310
- */
311
- scheduledTime: string;
312
- };
@@ -1,107 +0,0 @@
1
- import { logger } from "../logger";
2
- import type { Outcome } from "./filters";
3
- import type {
4
- AlarmEvent,
5
- RequestEvent,
6
- ScheduledEvent,
7
- TailEventMessage,
8
- } from "./index";
9
- import type WebSocket from "ws";
10
-
11
- export function prettyPrintLogs(data: WebSocket.RawData): void {
12
- const eventMessage: TailEventMessage = JSON.parse(data.toString());
13
-
14
- if (isScheduledEvent(eventMessage.event)) {
15
- const cronPattern = eventMessage.event.cron;
16
- const datetime = new Date(
17
- eventMessage.event.scheduledTime
18
- ).toLocaleString();
19
- const outcome = prettifyOutcome(eventMessage.outcome);
20
-
21
- logger.log(`"${cronPattern}" @ ${datetime} - ${outcome}`);
22
- } else if (isRequestEvent(eventMessage.event)) {
23
- const requestMethod = eventMessage.event?.request.method.toUpperCase();
24
- const url = eventMessage.event?.request.url;
25
- const outcome = prettifyOutcome(eventMessage.outcome);
26
- const datetime = new Date(eventMessage.eventTimestamp).toLocaleString();
27
-
28
- logger.log(
29
- url
30
- ? `${requestMethod} ${url} - ${outcome} @ ${datetime}`
31
- : `[missing request] - ${outcome} @ ${datetime}`
32
- );
33
- } else if (isAlarmEvent(eventMessage.event)) {
34
- const outcome = prettifyOutcome(eventMessage.outcome);
35
- const datetime = new Date(
36
- eventMessage.event.scheduledTime
37
- ).toLocaleString();
38
-
39
- logger.log(`Alarm @ ${datetime} - ${outcome}`);
40
- } else {
41
- // Unknown event type
42
- const outcome = prettifyOutcome(eventMessage.outcome);
43
- const datetime = new Date(eventMessage.eventTimestamp).toLocaleString();
44
-
45
- logger.log(`Unknown Event - ${outcome} @ ${datetime}`);
46
- }
47
-
48
- if (eventMessage.logs.length > 0) {
49
- eventMessage.logs.forEach(({ level, message }) => {
50
- logger.log(` (${level})`, ...message);
51
- });
52
- }
53
-
54
- if (eventMessage.exceptions.length > 0) {
55
- eventMessage.exceptions.forEach(({ name, message }) => {
56
- logger.error(` ${name}:`, message);
57
- });
58
- }
59
- }
60
-
61
- export function jsonPrintLogs(data: WebSocket.RawData): void {
62
- console.log(JSON.stringify(JSON.parse(data.toString()), null, 2));
63
- }
64
-
65
- function isRequestEvent(
66
- event: TailEventMessage["event"]
67
- ): event is RequestEvent {
68
- return Boolean(event && "request" in event);
69
- }
70
-
71
- function isScheduledEvent(
72
- event: TailEventMessage["event"]
73
- ): event is ScheduledEvent {
74
- return Boolean(event && "cron" in event);
75
- }
76
-
77
- /**
78
- * Check to see if an event sent from a worker is an AlarmEvent.
79
- *
80
- * Because the only property on `AlarmEvent` is "scheduledTime", which it
81
- * shares with `ScheduledEvent`, `isAlarmEvent` checks if there's _not_
82
- * a "cron" property in `event` to confirm it's an alarm event.
83
- *
84
- * @param event An event
85
- * @returns true if the event is an AlarmEvent
86
- */
87
- function isAlarmEvent(event: TailEventMessage["event"]): event is AlarmEvent {
88
- return Boolean(event && "scheduledTime" in event && !("cron" in event));
89
- }
90
-
91
- function prettifyOutcome(outcome: Outcome): string {
92
- switch (outcome) {
93
- case "ok":
94
- return "Ok";
95
- case "canceled":
96
- return "Canceled";
97
- case "exceededCpu":
98
- return "Exceeded CPU Limit";
99
- case "exceededMemory":
100
- return "Exceeded Memory Limit";
101
- case "exception":
102
- return "Exception Thrown";
103
- case "unknown":
104
- default:
105
- return "Unknown";
106
- }
107
- }
@@ -1,19 +0,0 @@
1
- import chalk from "chalk";
2
- import checkForUpdate from "update-check";
3
- import pkg from "../package.json";
4
-
5
- export async function updateCheck(): Promise<string> {
6
- let update = null;
7
- try {
8
- // default cache for update check is 1 day
9
- update = await checkForUpdate(pkg, {
10
- distTag: pkg.version.startsWith("0.0.0") ? "beta" : "latest",
11
- });
12
- } catch (err) {
13
- // ignore error
14
- }
15
-
16
- if (update) return `(update available ${chalk.green(update.latest)})`;
17
-
18
- return "";
19
- }