wrangler 0.0.0-e88a54e → 0.0.0-e89ee2a5

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 (174) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +47 -16
  3. package/bin/wrangler.js +123 -32
  4. package/kv-asset-handler.js +1 -0
  5. package/package.json +168 -86
  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 +17 -0
  11. package/templates/gitignore +167 -0
  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 +136 -0
  17. package/templates/middleware/loader-sw.ts +229 -0
  18. package/templates/middleware/middleware-d1-beta.d.ts +3 -0
  19. package/templates/middleware/middleware-ensure-req-body-drained.ts +19 -0
  20. package/templates/middleware/middleware-miniflare3-json-error.ts +33 -0
  21. package/templates/middleware/middleware-multiworker-dev.d.ts +4 -0
  22. package/templates/middleware/middleware-multiworker-dev.ts +68 -0
  23. package/templates/middleware/middleware-pretty-error.ts +40 -0
  24. package/templates/middleware/middleware-scheduled.ts +15 -0
  25. package/templates/middleware/middleware-serve-static-assets.d.ts +6 -0
  26. package/templates/middleware/middleware-serve-static-assets.ts +56 -0
  27. package/templates/modules-watch-stub.js +4 -0
  28. package/templates/new-worker-scheduled.js +17 -0
  29. package/templates/new-worker-scheduled.ts +32 -0
  30. package/templates/new-worker.js +3 -3
  31. package/templates/new-worker.ts +22 -4
  32. package/templates/no-op-worker.js +10 -0
  33. package/templates/pages-dev-pipeline.ts +32 -0
  34. package/templates/pages-dev-util.ts +55 -0
  35. package/templates/pages-shim.ts +9 -0
  36. package/templates/pages-template-plugin.ts +190 -0
  37. package/templates/pages-template-worker.ts +198 -0
  38. package/templates/startDevWorker/InspectorProxyWorker.ts +661 -0
  39. package/templates/startDevWorker/ProxyWorker.ts +326 -0
  40. package/templates/tsconfig-sanity.ts +11 -0
  41. package/templates/tsconfig.init.json +105 -0
  42. package/templates/tsconfig.json +6 -103
  43. package/wrangler-dist/InspectorProxyWorker.js +464 -0
  44. package/wrangler-dist/InspectorProxyWorker.js.map +6 -0
  45. package/wrangler-dist/ProxyWorker.js +237 -0
  46. package/wrangler-dist/ProxyWorker.js.map +6 -0
  47. package/wrangler-dist/cli.d.ts +23948 -0
  48. package/wrangler-dist/cli.js +164439 -134006
  49. package/wrangler-dist/wasm-sync.wasm +0 -0
  50. package/import_meta_url.js +0 -3
  51. package/miniflare-config-stubs/.env.empty +0 -0
  52. package/miniflare-config-stubs/package.empty.json +0 -1
  53. package/miniflare-config-stubs/wrangler.empty.toml +0 -0
  54. package/miniflare-dist/index.mjs +0 -79
  55. package/miniflare-dist/index.mjs.map +0 -7
  56. package/pages/functions/buildWorker.ts +0 -62
  57. package/pages/functions/filepath-routing.test.ts +0 -223
  58. package/pages/functions/filepath-routing.ts +0 -181
  59. package/pages/functions/identifiers.ts +0 -78
  60. package/pages/functions/routes.ts +0 -151
  61. package/pages/functions/template-worker.ts +0 -130
  62. package/src/__tests__/configuration.test.ts +0 -2796
  63. package/src/__tests__/dev.test.tsx +0 -496
  64. package/src/__tests__/dev2.test.tsx +0 -154
  65. package/src/__tests__/guess-worker-format.test.ts +0 -58
  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 -207
  72. package/src/__tests__/helpers/mock-console.ts +0 -70
  73. package/src/__tests__/helpers/mock-dialogs.ts +0 -65
  74. package/src/__tests__/helpers/mock-kv.ts +0 -33
  75. package/src/__tests__/helpers/mock-stdin.ts +0 -103
  76. package/src/__tests__/helpers/mock-web-socket.ts +0 -29
  77. package/src/__tests__/helpers/run-in-tmp.ts +0 -32
  78. package/src/__tests__/helpers/run-wrangler.ts +0 -16
  79. package/src/__tests__/helpers/write-wrangler-toml.ts +0 -17
  80. package/src/__tests__/https-options.test.ts +0 -127
  81. package/src/__tests__/index.test.ts +0 -991
  82. package/src/__tests__/jest.setup.ts +0 -69
  83. package/src/__tests__/kv.test.ts +0 -1382
  84. package/src/__tests__/logout.test.ts +0 -52
  85. package/src/__tests__/package-manager.test.ts +0 -206
  86. package/src/__tests__/pages.test.ts +0 -44
  87. package/src/__tests__/parse.test.ts +0 -322
  88. package/src/__tests__/publish.test.ts +0 -2704
  89. package/src/__tests__/r2.test.ts +0 -198
  90. package/src/__tests__/route.test.ts +0 -45
  91. package/src/__tests__/secret.test.ts +0 -425
  92. package/src/__tests__/sentry.test.ts +0 -146
  93. package/src/__tests__/tail.test.ts +0 -564
  94. package/src/__tests__/whoami.test.tsx +0 -100
  95. package/src/bundle.ts +0 -142
  96. package/src/cfetch/index.ts +0 -104
  97. package/src/cfetch/internal.ts +0 -139
  98. package/src/cli.ts +0 -19
  99. package/src/config/README.md +0 -107
  100. package/src/config/config.ts +0 -218
  101. package/src/config/diagnostics.ts +0 -80
  102. package/src/config/environment.ts +0 -366
  103. package/src/config/index.ts +0 -62
  104. package/src/config/validation-helpers.ts +0 -486
  105. package/src/config/validation.ts +0 -1090
  106. package/src/create-worker-preview.ts +0 -166
  107. package/src/create-worker-upload-form.ts +0 -217
  108. package/src/dev/dev.tsx +0 -364
  109. package/src/dev/local.tsx +0 -232
  110. package/src/dev/remote.tsx +0 -203
  111. package/src/dev/use-esbuild.ts +0 -100
  112. package/src/dialogs.tsx +0 -77
  113. package/src/entry.ts +0 -208
  114. package/src/environment-variables.ts +0 -33
  115. package/src/https-options.ts +0 -122
  116. package/src/index.tsx +0 -2373
  117. package/src/inspect.ts +0 -617
  118. package/src/kv.ts +0 -319
  119. package/src/miniflare-cli/README.md +0 -30
  120. package/src/miniflare-cli/enum-keys.ts +0 -17
  121. package/src/miniflare-cli/index.ts +0 -37
  122. package/src/module-collection.ts +0 -258
  123. package/src/open-in-browser.ts +0 -25
  124. package/src/package-manager.ts +0 -126
  125. package/src/pages.tsx +0 -1047
  126. package/src/parse.ts +0 -183
  127. package/src/paths.ts +0 -26
  128. package/src/proxy.ts +0 -440
  129. package/src/publish.ts +0 -347
  130. package/src/r2.ts +0 -50
  131. package/src/reporting.ts +0 -131
  132. package/src/selfsigned.d.ts +0 -29
  133. package/src/sites.tsx +0 -280
  134. package/src/tail/filters.ts +0 -279
  135. package/src/tail/index.ts +0 -299
  136. package/src/tail/printing.ts +0 -62
  137. package/src/user.tsx +0 -1118
  138. package/src/whoami.tsx +0 -69
  139. package/src/worker.ts +0 -163
  140. package/templates/static-asset-facade.js +0 -47
  141. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  142. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  143. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  144. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  145. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  146. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  147. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  148. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  149. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  150. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  151. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  152. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  153. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  154. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  155. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  156. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  157. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  158. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  159. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  160. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  161. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  162. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  163. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  164. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  165. package/vendor/wrangler-mime/LICENSE +0 -21
  166. package/vendor/wrangler-mime/Mime.js +0 -97
  167. package/vendor/wrangler-mime/README.md +0 -187
  168. package/vendor/wrangler-mime/cli.js +0 -46
  169. package/vendor/wrangler-mime/index.js +0 -4
  170. package/vendor/wrangler-mime/lite.js +0 -4
  171. package/vendor/wrangler-mime/package.json +0 -52
  172. package/vendor/wrangler-mime/types/other.js +0 -1
  173. package/vendor/wrangler-mime/types/standard.js +0 -1
  174. package/wrangler-dist/cli.js.map +0 -7
package/src/sites.tsx DELETED
@@ -1,280 +0,0 @@
1
- import { readdir, readFile, stat } from "node:fs/promises";
2
- import * as path from "node:path";
3
- import ignore from "ignore";
4
- import xxhash from "xxhash-wasm";
5
- import {
6
- createNamespace,
7
- listNamespaceKeys,
8
- listNamespaces,
9
- putBulkKeyValue,
10
- deleteBulkKeyValue,
11
- } from "./kv";
12
- import type { Config } from "./config";
13
- import type { KeyValue } from "./kv";
14
- import type { XXHashAPI } from "xxhash-wasm";
15
-
16
- /** Paths to always ignore. */
17
- const ALWAYS_IGNORE = new Set(["node_modules"]);
18
- const HIDDEN_FILES_TO_INCLUDE = new Set([
19
- ".well-known", // See https://datatracker.ietf.org/doc/html/rfc8615
20
- ]);
21
-
22
- async function* getFilesInFolder(dirPath: string): AsyncIterable<string> {
23
- const files = await readdir(dirPath, { withFileTypes: true });
24
- for (const file of files) {
25
- // Skip files that we never want to process.
26
- if (ALWAYS_IGNORE.has(file.name)) {
27
- continue;
28
- }
29
- // Skip hidden files (starting with .) except for some special ones
30
- if (file.name.startsWith(".") && !HIDDEN_FILES_TO_INCLUDE.has(file.name)) {
31
- continue;
32
- }
33
- // TODO: follow symlinks??
34
- if (file.isDirectory()) {
35
- yield* await getFilesInFolder(path.join(dirPath, file.name));
36
- } else {
37
- yield path.join(dirPath, file.name);
38
- }
39
- }
40
- }
41
-
42
- /**
43
- * Create a hash key for the given content using the xxhash algorithm.
44
- *
45
- * Note we only return the first 10 characters, since we will also include the file name in the asset manifest key
46
- * the most important thing here is to detect changes of a single file to invalidate the cache and
47
- * it's impossible to serve two different files with the same name
48
- */
49
- function hashFileContent(hasher: XXHashAPI, content: string): string {
50
- return hasher.h64ToString(content).substring(0, 10);
51
- }
52
-
53
- /**
54
- * Create a hashed asset key for the given asset.
55
- *
56
- * The key will change if the file path or content of the asset changes.
57
- * The algorithm used here matches that of Wrangler 1.
58
- */
59
- function hashAsset(
60
- hasher: XXHashAPI,
61
- filePath: string,
62
- content: string
63
- ): string {
64
- const extName = path.extname(filePath) || "";
65
- const baseName = path.basename(filePath, extName);
66
- const directory = path.dirname(filePath);
67
- const hash = hashFileContent(hasher, content);
68
- return urlSafe(path.join(directory, `${baseName}.${hash}${extName}`));
69
- }
70
-
71
- async function createKVNamespaceIfNotAlreadyExisting(
72
- title: string,
73
- accountId: string
74
- ) {
75
- // check if it already exists
76
- // TODO: this is super inefficient, should be made better
77
- const namespaces = await listNamespaces(accountId);
78
- const found = namespaces.find((x) => x.title === title);
79
- if (found) {
80
- return { created: false, id: found.id };
81
- }
82
-
83
- // else we make the namespace
84
- const id = await createNamespace(accountId, title);
85
- console.log(`🌀 Created namespace for Workers Site "${title}"`);
86
-
87
- return {
88
- created: true,
89
- id,
90
- };
91
- }
92
-
93
- /**
94
- * Upload the assets found within the `dirPath` directory to the sites assets KV namespace for
95
- * the worker given by `scriptName`.
96
- *
97
- * @param accountId the account to upload to.
98
- * @param scriptName the name of the worker whose assets we are uploading.
99
- * @param siteAssets an objects describing what assets to upload, or undefined if there are no assets to upload.
100
- * @param preview if true then upload to a "preview" KV namespace.
101
- * @returns a promise for an object mapping the relative paths of the assets to the key of that
102
- * asset in the KV namespace.
103
- */
104
- export async function syncAssets(
105
- accountId: string,
106
- scriptName: string,
107
- siteAssets: AssetPaths | undefined,
108
- preview: boolean
109
- ): Promise<{
110
- manifest: { [filePath: string]: string } | undefined;
111
- namespace: string | undefined;
112
- }> {
113
- if (siteAssets === undefined) {
114
- return { manifest: undefined, namespace: undefined };
115
- }
116
-
117
- const title = `__${scriptName}-workers_sites_assets${
118
- preview ? "_preview" : ""
119
- }`;
120
- const { id: namespace } = await createKVNamespaceIfNotAlreadyExisting(
121
- title,
122
- accountId
123
- );
124
-
125
- // let's get all the keys in this namespace
126
- const result = await listNamespaceKeys(accountId, namespace);
127
- const keys = new Set(result.map((x) => x.name));
128
-
129
- const manifest: Record<string, string> = {};
130
- const toUpload: KeyValue[] = [];
131
-
132
- const include = createPatternMatcher(siteAssets.includePatterns, false);
133
- const exclude = createPatternMatcher(siteAssets.excludePatterns, true);
134
- const hasher = await xxhash();
135
-
136
- const assetDirectory = path.join(
137
- siteAssets.baseDirectory,
138
- siteAssets.assetDirectory
139
- );
140
- for await (const absAssetFile of getFilesInFolder(assetDirectory)) {
141
- const assetFile = path.relative(siteAssets.baseDirectory, absAssetFile);
142
- if (!include(assetFile)) {
143
- continue;
144
- }
145
- if (exclude(assetFile)) {
146
- continue;
147
- }
148
-
149
- await validateAssetSize(absAssetFile, assetFile);
150
- console.log(`reading ${assetFile}...`);
151
- const content = await readFile(absAssetFile, "base64");
152
-
153
- const assetKey = hashAsset(hasher, assetFile, content);
154
- validateAssetKey(assetKey);
155
-
156
- // now put each of the files into kv
157
- if (!keys.has(assetKey)) {
158
- console.log(`uploading as ${assetKey}...`);
159
- toUpload.push({
160
- key: assetKey,
161
- value: content,
162
- base64: true,
163
- });
164
- } else {
165
- console.log(`skipping - already uploaded`);
166
- }
167
-
168
- // remove the key from the set so we know what we've already uploaded
169
- keys.delete(assetKey);
170
- manifest[path.relative(siteAssets.assetDirectory, absAssetFile)] = assetKey;
171
- }
172
-
173
- // keys now contains all the files we're deleting
174
- for (const key of keys) {
175
- console.log(`deleting ${key} from the asset store...`);
176
- }
177
-
178
- await Promise.all([
179
- // upload all the new assets
180
- putBulkKeyValue(accountId, namespace, toUpload, () => {}),
181
- // delete all the unused assets
182
- deleteBulkKeyValue(accountId, namespace, Array.from(keys), () => {}),
183
- ]);
184
-
185
- console.log("↗️ Done syncing assets");
186
-
187
- return { manifest, namespace };
188
- }
189
-
190
- function createPatternMatcher(
191
- patterns: string[],
192
- exclude: boolean
193
- ): (filePath: string) => boolean {
194
- if (patterns.length === 0) {
195
- return (_filePath) => !exclude;
196
- } else {
197
- const ignorer = ignore().add(patterns);
198
- return (filePath) => ignorer.test(filePath).ignored;
199
- }
200
- }
201
-
202
- async function validateAssetSize(
203
- absFilePath: string,
204
- relativeFilePath: string
205
- ) {
206
- const { size } = await stat(absFilePath);
207
- if (size > 25 * 1024 * 1024) {
208
- throw new Error(
209
- `File ${relativeFilePath} is too big, it should be under 25 MiB. See https://developers.cloudflare.com/workers/platform/limits#kv-limits`
210
- );
211
- }
212
- }
213
-
214
- function validateAssetKey(assetKey: string) {
215
- if (assetKey.length > 512) {
216
- throw new Error(
217
- `The asset path key "${assetKey}" exceeds the maximum key size limit of 512. See https://developers.cloudflare.com/workers/platform/limits#kv-limits",`
218
- );
219
- }
220
- }
221
-
222
- /**
223
- * Convert a filePath to be safe to use as a relative URL.
224
- *
225
- * Primarily this involves converting Windows backslashes to forward slashes.
226
- */
227
- function urlSafe(filePath: string): string {
228
- return filePath.replace(/\\/g, "/");
229
- }
230
-
231
- /**
232
- * Information about the assets that should be uploaded
233
- */
234
- export interface AssetPaths {
235
- /**
236
- * Absolute path to the root of the project.
237
- *
238
- * This is the directory containing wrangler.toml or cwd if no config.
239
- */
240
- baseDirectory: string;
241
- /**
242
- * The path to the assets directory, relative to the `baseDirectory`.
243
- */
244
- assetDirectory: string;
245
- /**
246
- * An array of patterns that match files that should be uploaded.
247
- */
248
- includePatterns: string[];
249
- /**
250
- * An array of patterns that match files that should not be uploaded.
251
- */
252
- excludePatterns: string[];
253
- }
254
-
255
- /**
256
- * Get an object that describes what assets to upload, if any.
257
- *
258
- * Uses the args (passed from the command line) if available,
259
- * falling back to those defined in the config.
260
- *
261
- */
262
- export function getAssetPaths(
263
- config: Config,
264
- assetDirectory = config.site?.bucket,
265
- includePatterns = config.site?.include ?? [],
266
- excludePatterns = config.site?.exclude ?? []
267
- ): undefined | AssetPaths {
268
- const baseDirectory = path.resolve(
269
- path.dirname(config.configPath ?? "wrangler.toml")
270
- );
271
-
272
- return assetDirectory
273
- ? {
274
- baseDirectory,
275
- assetDirectory,
276
- includePatterns,
277
- excludePatterns,
278
- }
279
- : undefined;
280
- }
@@ -1,279 +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, and unknown) are considered errors
62
- */
63
- export type Outcome =
64
- | "ok"
65
- | "canceled"
66
- | "exception"
67
- | "exceededCpu"
68
- | "unknown";
69
-
70
- /**
71
- * Filters logs based on the HTTP method used for the request
72
- * that triggered the worker.
73
- */
74
- type MethodFilter = {
75
- method: string[];
76
- };
77
-
78
- /**
79
- * Filters logs based on an HTTP header on the request that
80
- * triggered the worker.
81
- */
82
- type HeaderFilter = {
83
- header: {
84
- /**
85
- * Filters on the header "key", e.g. "X-CLOUDFLARE-HEADER"
86
- * or "X-CUSTOM-HEADER"
87
- */
88
- key: string;
89
-
90
- /**
91
- * Filters on the header "value", e.g. if this is set to
92
- * "filter-for-me" and the "key" is "X-SHOULD-LOG", only
93
- * events triggered by requests with the header
94
- * "X-SHOULD-LOG:filter-for-me" will be logged.
95
- */
96
- query?: string;
97
- };
98
- };
99
-
100
- /**
101
- * Filters on the IP address the request came from that triggered
102
- * the worker. A value of "self" will be replaced with the IP
103
- * address that is running `wrangler tail`
104
- */
105
- type ClientIPFilter = {
106
- client_ip: string[];
107
- };
108
-
109
- /**
110
- * Filters logs by a query string. This means only logs that
111
- * contain the given string will be sent to wrangler, and any
112
- * that don't will be discarded by the tail worker.
113
- */
114
- type QueryFilter = {
115
- query: string;
116
- };
117
-
118
- /**
119
- * The full message we send to the tail worker includes our
120
- * filters and a debug flag.
121
- */
122
- export type TailFilterMessage = {
123
- filters: TailAPIFilter[];
124
- debug: boolean;
125
- };
126
-
127
- /**
128
- * Translate the flags passed in via a CLI invokation of wrangler
129
- * into a message that we can send to the tail worker.
130
- *
131
- * @param cliFilters An object containing all the filters passed in from the CLI
132
- * @param debug Whether or not we should be in debug mode
133
- * @returns A filter message ready to be sent to the tail worker
134
- */
135
- export function translateCLICommandToFilterMessage(
136
- cliFilters: TailCLIFilters,
137
- debug: boolean
138
- ): TailFilterMessage {
139
- const apiFilters: TailAPIFilter[] = [];
140
-
141
- if (cliFilters.samplingRate) {
142
- apiFilters.push(parseSamplingRate(cliFilters.samplingRate));
143
- }
144
-
145
- if (cliFilters.status) {
146
- apiFilters.push(parseOutcome(cliFilters.status));
147
- }
148
-
149
- if (cliFilters.method) {
150
- apiFilters.push(parseMethod(cliFilters.method));
151
- }
152
-
153
- if (cliFilters.header) {
154
- apiFilters.push(parseHeader(cliFilters.header));
155
- }
156
-
157
- if (cliFilters.clientIp) {
158
- apiFilters.push(parseIP(cliFilters.clientIp));
159
- }
160
-
161
- if (cliFilters.search) {
162
- apiFilters.push(parseQuery(cliFilters.search));
163
- }
164
-
165
- return {
166
- filters: apiFilters,
167
- debug,
168
- };
169
- }
170
-
171
- /**
172
- * Parse the sampling rate passed in via command line
173
- *
174
- * @param sampling_rate the sampling rate passed in via CLI
175
- * @throws an Error if the rate doesn't make sense
176
- * @returns a SamplingRateFilter for use with the API
177
- */
178
- function parseSamplingRate(sampling_rate: number): SamplingRateFilter {
179
- if (sampling_rate <= 0 || sampling_rate >= 1) {
180
- throw new Error(
181
- "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."
182
- );
183
- }
184
-
185
- return { sampling_rate };
186
- }
187
-
188
- /**
189
- * Translate from CLI "status"es to API "outcome"s, including
190
- * broadening "error" into "exception", "exceededCpu", and "unknown".
191
- *
192
- * @param statuses statuses passed in via CLI
193
- * @returns an OutcomeFilter for use with the API
194
- */
195
- function parseOutcome(
196
- statuses: ("ok" | "error" | "canceled")[]
197
- ): OutcomeFilter {
198
- const outcomes = new Set<Outcome>();
199
-
200
- for (const status of statuses) {
201
- switch (status) {
202
- case "ok":
203
- outcomes.add("ok");
204
- break;
205
-
206
- case "canceled":
207
- outcomes.add("canceled");
208
- break;
209
-
210
- case "error":
211
- outcomes.add("exception");
212
- outcomes.add("exceededCpu");
213
- outcomes.add("unknown");
214
- break;
215
-
216
- default:
217
- break;
218
- }
219
- }
220
-
221
- return {
222
- outcome: Array.from(outcomes),
223
- };
224
- }
225
-
226
- /**
227
- * We just send silly methods through to the API anyway, since they don't
228
- * cause any harm.
229
- *
230
- * @param method an array of HTTP request methods passed in via CLI
231
- * @returns a MethodFilter for use with the API
232
- */
233
- function parseMethod(method: string[]): MethodFilter {
234
- return { method };
235
- }
236
-
237
- /**
238
- * Header filters can contain either just a key ("X-HEADER-KEY") or both
239
- * a key and a value ("X-HEADER-KEY:some-value"). This function parses
240
- * a given string according to that pattern.
241
- *
242
- * @param header a header string, "X-HEADER-KEY" or "X-HEADER-KEY:some-value"
243
- * @returns a HeaderFilter for use with the API
244
- */
245
- function parseHeader(header: string): HeaderFilter {
246
- const [headerKey, headerQuery] = header.split(":", 2);
247
-
248
- return {
249
- header: {
250
- key: headerKey.trim(),
251
- query: headerQuery?.trim(),
252
- },
253
- };
254
- }
255
-
256
- /**
257
- * A list of IPs can be passed in to filter for messages that come from
258
- * a worker triggered by a request originating from one of those IPs.
259
- * You can also pass in the string "self" to filter for the IP of the
260
- * machine running `wrangler tail`.
261
- *
262
- * @param client_ip an array of IP addresses to filter
263
- * @returns a ClientIPFilter for use with the API
264
- */
265
- function parseIP(client_ip: string[]): ClientIPFilter {
266
- return { client_ip };
267
- }
268
-
269
- /**
270
- * Users can filter for logs that contain a "search" or a "query string".
271
- * For example, if `--search findme` is passed to then we will only
272
- * receive logs that contain the string "findme".
273
- *
274
- * @param query a query string to search for
275
- * @returns a QueryFilter for use with the API
276
- */
277
- function parseQuery(query: string): QueryFilter {
278
- return { query };
279
- }