wrangler 0.0.0-e1c615f → 0.0.0-e3cab74

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 (85) hide show
  1. package/bin/wrangler.js +2 -2
  2. package/package.json +28 -13
  3. package/pages/functions/buildWorker.ts +6 -1
  4. package/pages/functions/filepath-routing.test.ts +112 -28
  5. package/pages/functions/filepath-routing.ts +88 -131
  6. package/pages/functions/routes.ts +11 -18
  7. package/pages/functions/template-worker.ts +21 -28
  8. package/src/__tests__/configuration.test.ts +2185 -0
  9. package/src/__tests__/dev.test.tsx +56 -9
  10. package/src/__tests__/guess-worker-format.test.ts +66 -0
  11. package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
  12. package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
  13. package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
  14. package/src/__tests__/helpers/mock-account-id.ts +30 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/{mock-cfetch.ts → helpers/mock-cfetch.ts} +53 -17
  17. package/src/__tests__/helpers/mock-console.ts +62 -0
  18. package/src/__tests__/{mock-dialogs.ts → helpers/mock-dialogs.ts} +1 -1
  19. package/src/__tests__/helpers/mock-kv.ts +40 -0
  20. package/src/__tests__/helpers/mock-user.ts +27 -0
  21. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  22. package/src/__tests__/helpers/run-in-tmp.ts +29 -0
  23. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  24. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  25. package/src/__tests__/index.test.ts +655 -76
  26. package/src/__tests__/jest.setup.ts +37 -2
  27. package/src/__tests__/kv.test.ts +441 -398
  28. package/src/__tests__/logout.test.ts +50 -0
  29. package/src/__tests__/package-manager.test.ts +206 -0
  30. package/src/__tests__/parse.test.ts +322 -0
  31. package/src/__tests__/publish.test.ts +2406 -0
  32. package/src/__tests__/r2.test.ts +198 -0
  33. package/src/__tests__/secret.test.ts +326 -0
  34. package/src/__tests__/sentry.test.ts +146 -0
  35. package/src/__tests__/tail.test.ts +564 -0
  36. package/src/__tests__/whoami.test.tsx +86 -0
  37. package/src/api/form_data.ts +112 -26
  38. package/src/api/preview.ts +34 -15
  39. package/src/api/worker.ts +58 -27
  40. package/src/bundle.ts +133 -0
  41. package/src/cfetch/index.ts +21 -19
  42. package/src/cfetch/internal.ts +85 -21
  43. package/src/cli.ts +10 -0
  44. package/src/config/README.md +107 -0
  45. package/src/config/config.ts +265 -0
  46. package/src/config/diagnostics.ts +80 -0
  47. package/src/config/environment.ts +305 -0
  48. package/src/config/index.ts +52 -0
  49. package/src/config/validation-helpers.ts +370 -0
  50. package/src/config/validation.ts +1017 -0
  51. package/src/dev.tsx +455 -368
  52. package/src/dialogs.tsx +2 -2
  53. package/src/entry.ts +57 -0
  54. package/src/environment-variables.ts +33 -0
  55. package/src/guess-worker-format.ts +68 -0
  56. package/src/index.tsx +1044 -646
  57. package/src/inspect.ts +609 -0
  58. package/src/kv.tsx +47 -39
  59. package/src/module-collection.ts +142 -36
  60. package/src/open-in-browser.ts +13 -0
  61. package/src/package-manager.ts +126 -0
  62. package/src/pages.tsx +139 -62
  63. package/src/parse.ts +183 -0
  64. package/src/paths.ts +26 -0
  65. package/src/proxy.ts +350 -77
  66. package/src/publish.ts +307 -289
  67. package/src/r2.ts +50 -0
  68. package/src/reporting.ts +115 -0
  69. package/src/sites.tsx +183 -56
  70. package/src/tail/filters.ts +279 -0
  71. package/src/tail/index.ts +299 -0
  72. package/src/tail/printing.ts +62 -0
  73. package/src/user.tsx +137 -110
  74. package/src/whoami.tsx +69 -0
  75. package/templates/new-worker.js +15 -0
  76. package/templates/new-worker.ts +15 -0
  77. package/{static-asset-facade.js → templates/static-asset-facade.js} +0 -0
  78. package/templates/tsconfig.json +105 -0
  79. package/wrangler-dist/cli.js +127861 -111486
  80. package/wrangler-dist/cli.js.map +3 -3
  81. package/src/__tests__/run-in-tmp.ts +0 -19
  82. package/src/__tests__/run-wrangler.ts +0 -32
  83. package/src/api/inspect.ts +0 -430
  84. package/src/config.ts +0 -131
  85. package/src/tail.tsx +0 -73
package/src/r2.ts ADDED
@@ -0,0 +1,50 @@
1
+ import { fetchResult } from "./cfetch";
2
+
3
+ /**
4
+ * Information about a bucket, returned from `listR2Buckets()`.
5
+ */
6
+ export interface R2BucketInfo {
7
+ name: string;
8
+ creation_date: string;
9
+ }
10
+
11
+ /**
12
+ * Fetch a list of all the buckets under the given `accountId`.
13
+ */
14
+ export async function listR2Buckets(
15
+ accountId: string
16
+ ): Promise<R2BucketInfo[]> {
17
+ const results = await fetchResult<{
18
+ buckets: R2BucketInfo[];
19
+ }>(`/accounts/${accountId}/r2/buckets`);
20
+ return results.buckets;
21
+ }
22
+
23
+ /**
24
+ * Create a bucket with the given `bucketName` within the account given by `accountId`.
25
+ *
26
+ * A 400 is returned if the account already owns a bucket with this name.
27
+ * A bucket must be explicitly deleted to be replaced.
28
+ */
29
+ export async function createR2Bucket(
30
+ accountId: string,
31
+ bucketName: string
32
+ ): Promise<void> {
33
+ return await fetchResult<void>(
34
+ `/accounts/${accountId}/r2/buckets/${bucketName}`,
35
+ { method: "PUT" }
36
+ );
37
+ }
38
+
39
+ /**
40
+ * Delete a bucket with the given name
41
+ */
42
+ export async function deleteR2Bucket(
43
+ accountId: string,
44
+ bucketName: string
45
+ ): Promise<void> {
46
+ return await fetchResult<void>(
47
+ `/accounts/${accountId}/r2/buckets/${bucketName}`,
48
+ { method: "DELETE" }
49
+ );
50
+ }
@@ -0,0 +1,115 @@
1
+ import { appendFile, readFile } from "fs/promises";
2
+ import * as fs from "node:fs";
3
+ import os from "node:os";
4
+ import path from "path/posix";
5
+ import TOML from "@iarna/toml";
6
+ import { RewriteFrames } from "@sentry/integrations";
7
+ import {
8
+ captureException,
9
+ getCurrentHub,
10
+ startTransaction,
11
+ init,
12
+ Integrations,
13
+ setContext,
14
+ } from "@sentry/node";
15
+ import { execaSync } from "execa";
16
+ import prompts from "prompts";
17
+ import * as pkj from "../package.json";
18
+
19
+ export function initReporting() {
20
+ init({
21
+ release: `${pkj.name}@${pkj.version}`,
22
+ initialScope: {
23
+ tags: { [pkj.name]: pkj.version },
24
+ },
25
+ dsn: "https://5089b76bf8a64a9c949bf5c2b5e8003c@o51786.ingest.sentry.io/6190959",
26
+ tracesSampleRate: 1.0,
27
+ integrations: [
28
+ new RewriteFrames({
29
+ root: "",
30
+ prefix: "/",
31
+ }),
32
+ new Integrations.Http({ tracing: true }),
33
+ ],
34
+ });
35
+
36
+ setContext("System Information", {
37
+ OS: process.platform,
38
+ node: process.version,
39
+ npm: execaSync("npm", ["--version"]).stdout,
40
+ wrangler: pkj.version,
41
+ });
42
+ }
43
+
44
+ async function appendReportingDecision(userInput: "true" | "false") {
45
+ const homePath = path.join(os.homedir(), ".wrangler/config/");
46
+ fs.mkdirSync(homePath, { recursive: true });
47
+ await appendFile(
48
+ path.join(homePath, "reporting.toml"),
49
+ `error_tracking_opt = ${userInput} # Sentry \nerror_tracking_opt_date = ${new Date().toISOString()} # Sentry Date Decision \n`,
50
+ { encoding: "utf-8" }
51
+ );
52
+ }
53
+
54
+ function exceptionTransaction(error: Error, origin = "") {
55
+ const transaction = startTransaction({
56
+ op: origin,
57
+ name: error.name,
58
+ });
59
+ captureException(error);
60
+ transaction.finish();
61
+ }
62
+
63
+ export async function reportError(err: Error, origin = "") {
64
+ if (!process.stdout.isTTY) return await appendReportingDecision("false");
65
+
66
+ const errorTrackingOpt = await reportingPermission();
67
+
68
+ if (errorTrackingOpt === undefined) {
69
+ const userInput = await prompts.prompt({
70
+ type: "select",
71
+ name: "sentryDecision",
72
+ message: "Would you like to submit a report when an error occurs?",
73
+ choices: [
74
+ { title: "Always", value: true },
75
+ { title: "Yes", value: "once" },
76
+ { title: "No", value: false },
77
+ ],
78
+ initial: 2,
79
+ });
80
+
81
+ if (userInput.sentryDecision === "once") {
82
+ exceptionTransaction(err, origin);
83
+ return;
84
+ }
85
+
86
+ userInput.sentryDecision
87
+ ? await appendReportingDecision("true")
88
+ : await appendReportingDecision("false");
89
+ }
90
+
91
+ if (!errorTrackingOpt) {
92
+ const sentryClient = getCurrentHub().getClient();
93
+ if (sentryClient !== undefined) sentryClient.getOptions().enabled = false;
94
+ }
95
+
96
+ exceptionTransaction(err, origin);
97
+ }
98
+
99
+ async function reportingPermission() {
100
+ if (
101
+ !fs.existsSync(path.join(os.homedir(), ".wrangler/config/reporting.toml"))
102
+ )
103
+ return undefined;
104
+
105
+ const reportingTOML = TOML.parse(
106
+ await readFile(path.join(os.homedir(), ".wrangler/config/reporting.toml"), {
107
+ encoding: "utf-8",
108
+ })
109
+ );
110
+ const { error_tracking_opt } = reportingTOML as {
111
+ error_tracking_opt: string | undefined;
112
+ };
113
+
114
+ return error_tracking_opt;
115
+ }
package/src/sites.tsx CHANGED
@@ -1,13 +1,37 @@
1
- import crypto from "node:crypto";
2
- import { createReadStream } from "node:fs";
1
+ import { readdir, readFile, stat } from "node:fs/promises";
3
2
  import * as path from "node:path";
4
- import { readdir, readFile } from "node:fs/promises";
5
- import { fetchResult } from "./cfetch";
6
- import { listNamespaceKeys, listNamespaces, putBulkKeyValue } from "./kv";
3
+ import ignore from "ignore";
4
+ import xxhash from "xxhash-wasm";
5
+ import {
6
+ createNamespace,
7
+ listNamespaceKeys,
8
+ listNamespaces,
9
+ putBulkKeyValue,
10
+ } from "./kv";
11
+ import type { Config } from "./config";
12
+ import type { XXHashAPI } from "xxhash-wasm";
13
+
14
+ /** Paths to always ignore. */
15
+ const ALWAYS_IGNORE = ["node_modules"];
16
+ const HIDDEN_FILES_TO_INCLUDE = [
17
+ ".well-known", // See https://datatracker.ietf.org/doc/html/rfc8615
18
+ ];
7
19
 
8
20
  async function* getFilesInFolder(dirPath: string): AsyncIterable<string> {
9
21
  const files = await readdir(dirPath, { withFileTypes: true });
10
22
  for (const file of files) {
23
+ // Skip files that we never want to process.
24
+ if (ALWAYS_IGNORE.some((p) => file.name === p)) {
25
+ continue;
26
+ }
27
+ // Skip hidden files (starting with .) except for some special ones
28
+ if (
29
+ file.name.startsWith(".") &&
30
+ !HIDDEN_FILES_TO_INCLUDE.some((p) => file.name === p)
31
+ ) {
32
+ continue;
33
+ }
34
+ // TODO: follow symlinks??
11
35
  if (file.isDirectory()) {
12
36
  yield* await getFilesInFolder(path.join(dirPath, file.name));
13
37
  } else {
@@ -16,27 +40,33 @@ async function* getFilesInFolder(dirPath: string): AsyncIterable<string> {
16
40
  }
17
41
  }
18
42
 
19
- async function hashFileContent(filePath: string): Promise<string> {
20
- return new Promise((resolve, reject) => {
21
- const hash = crypto.createHash("sha1");
22
- const rs = createReadStream(filePath);
23
- rs.on("error", reject);
24
- rs.on("data", (chunk) => hash.update(chunk));
25
- rs.on("end", () => resolve(hash.digest("hex")));
26
- });
43
+ /**
44
+ * Create a hash key for the given content using the xxhash algorithm.
45
+ *
46
+ * Note we only return the first 10 characters, since we will also include the file name in the asset manifest key
47
+ * the most important thing here is to detect changes of a single file to invalidate the cache and
48
+ * it's impossible to serve two different files with the same name
49
+ */
50
+ function hashFileContent(hasher: XXHashAPI, content: string): string {
51
+ return hasher.h64ToString(content).substring(0, 10);
27
52
  }
28
53
 
29
- async function hashFile(filePath: string): Promise<{
30
- filePath: string;
31
- hash: string;
32
- }> {
33
- const extName = path.extname(filePath);
54
+ /**
55
+ * Create a hashed asset key for the given asset.
56
+ *
57
+ * The key will change if the file path or content of the asset changes.
58
+ * The algorithm used here matches that of Wrangler 1.
59
+ */
60
+ function hashAsset(
61
+ hasher: XXHashAPI,
62
+ filePath: string,
63
+ content: string
64
+ ): string {
65
+ const extName = path.extname(filePath) || "";
34
66
  const baseName = path.basename(filePath, extName);
35
- const hash = await hashFileContent(filePath);
36
- return {
37
- filePath: `${baseName}.${hash}${extName || ""}`,
38
- hash,
39
- };
67
+ const directory = path.dirname(filePath);
68
+ const hash = hashFileContent(hasher, content);
69
+ return urlSafe(path.join(directory, `${baseName}.${hash}${extName}`));
40
70
  }
41
71
 
42
72
  async function createKVNamespaceIfNotAlreadyExisting(
@@ -52,63 +82,160 @@ async function createKVNamespaceIfNotAlreadyExisting(
52
82
  }
53
83
 
54
84
  // else we make the namespace
55
- // TODO: use an export from ./kv
56
- const json = await fetchResult<{ id: string }>(
57
- `/accounts/${accountId}/storage/kv/namespaces`,
58
- {
59
- method: "POST",
60
- headers: {
61
- "Content-Type": "application/json",
62
- },
63
- body: JSON.stringify({ title }),
64
- }
65
- );
85
+ const id = await createNamespace(accountId, title);
86
+ console.log(`🌀 Created namespace for Workers Site "${title}"`);
66
87
 
67
88
  return {
68
89
  created: true,
69
- id: json.id,
90
+ id,
70
91
  };
71
92
  }
72
93
 
94
+ /**
95
+ * Upload the assets found within the `dirPath` directory to the sites assets KV namespace for
96
+ * the worker given by `scriptName`.
97
+ *
98
+ * @param accountId the account to upload to.
99
+ * @param scriptName the name of the worker whose assets we are uploading.
100
+ * @param siteAssets an objects describing what assets to upload, or undefined if there are no assets to upload.
101
+ * @param preview if true then upload to a "preview" KV namespace.
102
+ * @returns a promise for an object mapping the relative paths of the assets to the key of that
103
+ * asset in the KV namespace.
104
+ */
73
105
  export async function syncAssets(
74
106
  accountId: string,
75
107
  scriptName: string,
76
- dirPath: string,
77
- preview: boolean,
78
- _env?: string
79
- ) {
80
- const title = `__${scriptName}_sites_assets${preview ? "_preview" : ""}`;
108
+ siteAssets: AssetPaths | undefined,
109
+ preview: boolean
110
+ ): Promise<{
111
+ manifest: { [filePath: string]: string } | undefined;
112
+ namespace: string | undefined;
113
+ }> {
114
+ if (siteAssets === undefined) {
115
+ return { manifest: undefined, namespace: undefined };
116
+ }
117
+
118
+ const title = `__${scriptName}-workers_sites_assets${
119
+ preview ? "_preview" : ""
120
+ }`;
81
121
  const { id: namespace } = await createKVNamespaceIfNotAlreadyExisting(
82
122
  title,
83
123
  accountId
84
124
  );
85
125
 
86
126
  // let's get all the keys in this namespace
87
- const keys = new Set(
88
- (await listNamespaceKeys(accountId, namespace)).map((x) => x.name)
89
- );
127
+ const result = await listNamespaceKeys(accountId, namespace);
128
+ const keys = new Set(result.map((x) => x.name));
129
+
130
+ const manifest: Record<string, string> = {};
131
+ const upload: {
132
+ key: string;
133
+ value: string;
134
+ base64: boolean;
135
+ }[] = [];
136
+
137
+ const include = createPatternMatcher(siteAssets.includePatterns, false);
138
+ const exclude = createPatternMatcher(siteAssets.excludePatterns, true);
139
+ const hasher = await xxhash();
90
140
 
91
- const manifest = {};
92
- const upload = [];
93
141
  // TODO: this can be more efficient by parallelising
94
- for await (const file of getFilesInFolder(dirPath)) {
95
- // TODO: "exclude:" config
96
- const { filePath } = await hashFile(file);
142
+ for await (const file of getFilesInFolder(siteAssets.baseDirectory)) {
143
+ if (!include(file)) {
144
+ continue;
145
+ }
146
+ if (exclude(file)) {
147
+ continue;
148
+ }
149
+
150
+ await validateAssetSize(file);
151
+ console.log(`reading ${file}...`);
152
+ const content = await readFile(file, "base64");
153
+
154
+ const assetKey = await hashAsset(hasher, file, content);
155
+ validateAssetKey(assetKey);
156
+
97
157
  // now put each of the files into kv
98
- if (!keys.has(filePath)) {
99
- console.log(`uploading ${file}...`);
100
- const content = await readFile(file, "base64");
101
- if (content.length > 25 * 1024 * 1024) {
102
- throw new Error(`File ${file} is too big, it should be under 25 mb.`);
103
- }
158
+ if (!keys.has(assetKey)) {
159
+ console.log(`uploading as ${assetKey}...`);
104
160
  upload.push({
105
- key: filePath,
161
+ key: assetKey,
106
162
  value: content,
107
163
  base64: true,
108
164
  });
165
+ } else {
166
+ console.log(`skipping - already uploaded`);
109
167
  }
110
- manifest[path.relative(dirPath, file)] = filePath;
168
+ manifest[path.relative(siteAssets.baseDirectory, file)] = assetKey;
111
169
  }
112
170
  await putBulkKeyValue(accountId, namespace, JSON.stringify(upload));
113
171
  return { manifest, namespace };
114
172
  }
173
+
174
+ function createPatternMatcher(
175
+ patterns: string[],
176
+ exclude: boolean
177
+ ): (filePath: string) => boolean {
178
+ if (patterns.length === 0) {
179
+ return (_filePath) => !exclude;
180
+ } else {
181
+ const ignorer = ignore().add(patterns);
182
+ return (filePath) => ignorer.test(filePath).ignored;
183
+ }
184
+ }
185
+
186
+ async function validateAssetSize(filePath: string) {
187
+ const { size } = await stat(filePath);
188
+ if (size > 25 * 1024 * 1024) {
189
+ throw new Error(
190
+ `File ${filePath} is too big, it should be under 25 MiB. See https://developers.cloudflare.com/workers/platform/limits#kv-limits`
191
+ );
192
+ }
193
+ }
194
+
195
+ function validateAssetKey(assetKey: string) {
196
+ if (assetKey.length > 512) {
197
+ throw new Error(
198
+ `The asset path key "${assetKey}" exceeds the maximum key size limit of 512. See https://developers.cloudflare.com/workers/platform/limits#kv-limits",`
199
+ );
200
+ }
201
+ }
202
+
203
+ /**
204
+ * Convert a filePath to be safe to use as a relative URL.
205
+ *
206
+ * Primarily this involves converting Windows backslashes to forward slashes.
207
+ */
208
+ function urlSafe(filePath: string): string {
209
+ return filePath.replace(/\\/g, "/");
210
+ }
211
+
212
+ /**
213
+ * Information about the assets that should be uploaded
214
+ */
215
+ export interface AssetPaths {
216
+ baseDirectory: string;
217
+ includePatterns: string[];
218
+ excludePatterns: string[];
219
+ }
220
+
221
+ /**
222
+ * Get an object that describes what assets to upload, if any.
223
+ *
224
+ * Uses the args (passed from the command line) if available,
225
+ * falling back to those defined in the config.
226
+ *
227
+ */
228
+ export function getAssetPaths(
229
+ config: Config,
230
+ baseDirectory = config.site?.bucket,
231
+ includePatterns = config.site?.include ?? [],
232
+ excludePatterns = config.site?.exclude ?? []
233
+ ): undefined | AssetPaths {
234
+ return baseDirectory
235
+ ? {
236
+ baseDirectory,
237
+ includePatterns,
238
+ excludePatterns,
239
+ }
240
+ : undefined;
241
+ }