wrangler 0.0.0-ece06ea → 0.0.0-edc4b53

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 (41) hide show
  1. package/package.json +24 -15
  2. package/pages/functions/buildWorker.ts +62 -0
  3. package/pages/functions/filepath-routing.test.ts +39 -0
  4. package/pages/functions/filepath-routing.ts +221 -0
  5. package/pages/functions/identifiers.ts +78 -0
  6. package/pages/functions/routes.ts +158 -0
  7. package/pages/functions/template-worker.ts +144 -0
  8. package/src/__tests__/dev.test.tsx +66 -0
  9. package/src/__tests__/index.test.ts +254 -120
  10. package/src/__tests__/jest.setup.ts +22 -0
  11. package/src/__tests__/kv.test.ts +1106 -0
  12. package/src/__tests__/mock-cfetch.ts +171 -0
  13. package/src/__tests__/mock-dialogs.ts +65 -0
  14. package/src/__tests__/run-in-tmp.ts +19 -0
  15. package/src/__tests__/run-wrangler.ts +32 -0
  16. package/src/api/form_data.ts +71 -98
  17. package/src/api/preview.ts +29 -24
  18. package/src/api/worker.ts +38 -44
  19. package/src/cfetch/index.ts +102 -0
  20. package/src/cfetch/internal.ts +65 -0
  21. package/src/cli.ts +6 -7
  22. package/src/config.ts +476 -113
  23. package/src/dev.tsx +291 -256
  24. package/src/dialogs.tsx +4 -12
  25. package/src/index.tsx +381 -252
  26. package/src/inspect.ts +524 -0
  27. package/src/kv.tsx +110 -45
  28. package/src/module-collection.ts +64 -0
  29. package/src/pages.tsx +900 -213
  30. package/src/proxy.ts +294 -0
  31. package/src/publish.ts +67 -63
  32. package/src/sites.tsx +10 -7
  33. package/src/tail.tsx +5 -3
  34. package/src/user.tsx +31 -33
  35. package/wrangler-dist/cli.js +43444 -56347
  36. package/wrangler-dist/cli.js.map +3 -3
  37. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  38. package/src/__tests__/mock-cfetch.js +0 -46
  39. package/src/api/inspect.ts +0 -441
  40. package/src/cfetch.ts +0 -72
  41. package/src/util/fetch.ts +0 -74
package/src/kv.tsx CHANGED
@@ -1,6 +1,6 @@
1
+ import { URLSearchParams } from "node:url";
1
2
  import type { Config } from "./config";
2
- import cfetch from "./cfetch";
3
- import qs from "node:querystring";
3
+ import { fetchListResult, fetchResult } from "./cfetch";
4
4
 
5
5
  type KvArgs = {
6
6
  binding?: string;
@@ -10,38 +10,84 @@ type KvArgs = {
10
10
  config?: Config;
11
11
  };
12
12
 
13
- export async function listNamespaces(accountId: string) {
14
- let page = 1,
15
- done = false,
16
- results = [];
17
- while (!(done || results.length % 100 !== 0)) {
18
- const json = await cfetch<
19
- { id: string; title: string; supports_url_encoding: boolean }[]
20
- >(
21
- `/accounts/${accountId}/storage/kv/namespaces?per_page=100&order=title&direction=asc&page=${page}`
13
+ /**
14
+ * Create a new namespace under the given `accountId` with the given `title`.
15
+ *
16
+ * @returns the generated id of the created namespace.
17
+ */
18
+ export async function createNamespace(
19
+ accountId: string,
20
+ title: string
21
+ ): Promise<string> {
22
+ const response = await fetchResult<{ id: string }>(
23
+ `/accounts/${accountId}/storage/kv/namespaces`,
24
+ {
25
+ method: "POST",
26
+ headers: {
27
+ "Content-Type": "application/json",
28
+ },
29
+ body: JSON.stringify({
30
+ title,
31
+ }),
32
+ }
33
+ );
34
+
35
+ return response.id;
36
+ }
37
+
38
+ /**
39
+ * The information about a namespace that is returned from `listNamespaces()`.
40
+ */
41
+ export interface KVNamespaceInfo {
42
+ id: string;
43
+ title: string;
44
+ supports_url_encoding?: boolean;
45
+ }
46
+
47
+ /**
48
+ * Fetch a list of all the namespaces under the given `accountId`.
49
+ */
50
+ export async function listNamespaces(
51
+ accountId: string
52
+ ): Promise<KVNamespaceInfo[]> {
53
+ const pageSize = 100;
54
+ let page = 1;
55
+ const results: KVNamespaceInfo[] = [];
56
+ while (results.length % pageSize === 0) {
57
+ const json = await fetchResult<KVNamespaceInfo[]>(
58
+ `/accounts/${accountId}/storage/kv/namespaces`,
59
+ {},
60
+ new URLSearchParams({
61
+ per_page: pageSize.toString(),
62
+ order: "title",
63
+ direction: "asc",
64
+ page: page.toString(),
65
+ })
22
66
  );
23
67
  page++;
24
- results = [...results, ...json];
25
- if (json.length === 0) {
26
- done = true;
68
+ results.push(...json);
69
+ if (json.length < pageSize) {
70
+ break;
27
71
  }
28
72
  }
29
73
  return results;
30
74
  }
31
75
 
76
+ export interface NamespaceKeyInfo {
77
+ name: string;
78
+ expiration?: number;
79
+ metadata?: { [key: string]: unknown };
80
+ }
81
+
32
82
  export async function listNamespaceKeys(
33
83
  accountId: string,
34
84
  namespaceId: string,
35
- prefix?: string,
36
- limit?: number
85
+ prefix = ""
37
86
  ) {
38
- // TODO: this doesn't appear to do pagination
39
- return await cfetch<
40
- { name: string; expiration: number; metadata: { [key: string]: unknown } }[]
41
- >(
42
- `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys?${qs.stringify(
43
- { prefix, limit }
44
- )}`
87
+ return await fetchListResult<NamespaceKeyInfo>(
88
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys`,
89
+ {},
90
+ new URLSearchParams({ prefix })
45
91
  );
46
92
  }
47
93
 
@@ -52,16 +98,20 @@ export async function putKeyValue(
52
98
  value: string,
53
99
  args?: { expiration?: number; expiration_ttl?: number }
54
100
  ) {
55
- return await cfetch(
56
- `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}?${
57
- args
58
- ? qs.stringify({
59
- expiration: args.expiration,
60
- expiration_ttl: args.expiration_ttl,
61
- })
62
- : ""
63
- }`,
64
- { method: "PUT", body: value }
101
+ let searchParams: URLSearchParams | undefined;
102
+ if (args) {
103
+ searchParams = new URLSearchParams();
104
+ if (args.expiration) {
105
+ searchParams.set("expiration", `${args.expiration}`);
106
+ }
107
+ if (args.expiration_ttl) {
108
+ searchParams.set("expiration_ttl", `${args.expiration_ttl}`);
109
+ }
110
+ }
111
+ return await fetchResult(
112
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${key}`,
113
+ { method: "PUT", body: value },
114
+ searchParams
65
115
  );
66
116
  }
67
117
 
@@ -70,7 +120,7 @@ export async function putBulkKeyValue(
70
120
  namespaceId: string,
71
121
  keyvalueStr: string
72
122
  ) {
73
- return await cfetch(
123
+ return await fetchResult(
74
124
  `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
75
125
  {
76
126
  method: "PUT",
@@ -85,7 +135,7 @@ export async function deleteBulkKeyValue(
85
135
  namespaceId: string,
86
136
  keyStr: string
87
137
  ) {
88
- return await cfetch(
138
+ return await fetchResult(
89
139
  `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
90
140
  {
91
141
  method: "DELETE",
@@ -118,7 +168,7 @@ export function getNamespaceId({
118
168
  if (!config) {
119
169
  throw new Error(
120
170
  "Failed to find a config file.\n" +
121
- "Either use --namespace to upload directly or create a configuration file with a binding."
171
+ "Either use --namespace-id to upload directly or create a configuration file with a binding."
122
172
  );
123
173
  }
124
174
 
@@ -130,7 +180,7 @@ export function getNamespaceId({
130
180
  );
131
181
  }
132
182
 
133
- // TODO: either a bespoke arg type for this function to avoid undefineds or a EnvOrConfig type
183
+ // TODO: either a bespoke arg type for this function to avoid `undefined`s or an `EnvOrConfig` type
134
184
  return getNamespaceId({
135
185
  binding,
136
186
  "namespace-id": namespaceId,
@@ -149,25 +199,27 @@ export function getNamespaceId({
149
199
  // there's no KV namespaces
150
200
  if (!config.kv_namespaces || config.kv_namespaces.length === 0) {
151
201
  throw new Error(
152
- "No KV Namespace to upload to! Either use --namespace to upload directly or add a KV namespace to your wrangler config file."
202
+ "No KV Namespaces configured! Either use --namespace-id to upload directly or add a KV namespace to your wrangler config file."
153
203
  );
154
204
  }
155
205
 
156
- const namespace = config.kv_namespaces.find(
157
- (namespace) => namespace.binding === binding
158
- );
206
+ const namespace = config.kv_namespaces.find((ns) => ns.binding === binding);
159
207
 
160
208
  // we couldn't find a namespace with that binding
161
209
  if (!namespace) {
162
- throw new Error(`No KV Namespaces found with binding ${binding}!`);
210
+ throw new Error(
211
+ `A namespace with binding name "${binding}" was not found in the configured "kv_namespaces".`
212
+ );
163
213
  }
164
214
 
165
215
  // end pre-flight checks
166
216
 
167
- // we're in preview mode, `--preview true` or `--preivew` was passed
217
+ // we're in preview mode, `--preview true` or `--preview` was passed
168
218
  if (preview && namespace.preview_id) {
169
219
  namespaceId = namespace.preview_id;
170
- } else {
220
+ // We don't want to execute code below if preview is set to true, so we just return. Otherwise we will get errors!
221
+ return namespaceId;
222
+ } else if (preview) {
171
223
  throw new Error(
172
224
  `No preview ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
173
225
  );
@@ -180,7 +232,9 @@ export function getNamespaceId({
180
232
  // --preview false was passed
181
233
  if (previewIsDefined && namespace.id) {
182
234
  namespaceId = namespace.id;
183
- } else {
235
+ // We don't want to execute code below if preview is set to true, so we just return. Otherwise we can get error!
236
+ return namespaceId;
237
+ } else if (previewIsDefined) {
184
238
  throw new Error(
185
239
  `No namespace ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
186
240
  );
@@ -209,3 +263,14 @@ export function getNamespaceId({
209
263
 
210
264
  return namespaceId;
211
265
  }
266
+
267
+ /**
268
+ * KV namespace binding names must be valid JS identifiers.
269
+ */
270
+ export function isValidNamespaceBinding(
271
+ binding: string | undefined
272
+ ): binding is string {
273
+ return (
274
+ typeof binding === "string" && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(binding)
275
+ );
276
+ }
@@ -0,0 +1,64 @@
1
+ import type { CfModule } from "./api/worker";
2
+ import type esbuild from "esbuild";
3
+ import path from "node:path";
4
+ import { readFile } from "node:fs/promises";
5
+ import crypto from "node:crypto";
6
+
7
+ // This is a combination of an esbuild plugin and a mutable array
8
+ // that we use to collect module references from source code.
9
+ // There will be modules that _shouldn't_ be inlined directly into
10
+ // the bundle. (eg. wasm modules, some text files, etc). We can include
11
+ // those files as modules in the multi part forker form upload. This
12
+ // plugin+array is used to collect references to these modules, reference
13
+ // them correctly in the bundle, and add them to the form upload.
14
+
15
+ export default function makeModuleCollector(): {
16
+ modules: CfModule[];
17
+ plugin: esbuild.Plugin;
18
+ } {
19
+ const modules: CfModule[] = [];
20
+ return {
21
+ modules,
22
+ plugin: {
23
+ name: "wrangler-module-collector",
24
+ setup(build) {
25
+ build.onStart(() => {
26
+ // reset the moduels collection
27
+ modules.splice(0);
28
+ });
29
+
30
+ build.onResolve(
31
+ // filter on "known" file types,
32
+ // we can expand this list later
33
+ { filter: /.*\.(pem|txt|html|wasm)$/ },
34
+ async (args: esbuild.OnResolveArgs) => {
35
+ // take the file and massage it to a
36
+ // transportable/manageable format
37
+ const fileExt = path.extname(args.path);
38
+ const filePath = path.join(args.resolveDir, args.path);
39
+ const fileContent = await readFile(filePath);
40
+ const fileHash = crypto
41
+ .createHash("sha1")
42
+ .update(fileContent)
43
+ .digest("hex");
44
+ const fileName = `${fileHash}-${path.basename(args.path)}`;
45
+
46
+ // add the module to the array
47
+ modules.push({
48
+ name: fileName,
49
+ content: fileContent,
50
+ type: fileExt === ".wasm" ? "compiled-wasm" : "text",
51
+ });
52
+
53
+ return {
54
+ path: fileName, // change the reference to the changed module
55
+ external: true, // mark it as external in the bundle
56
+ namespace: "wrangler-module-collector-ns", // just a tag, this isn't strictly necessary
57
+ watchFiles: [filePath], // we also add the file to esbuild's watch list
58
+ };
59
+ }
60
+ );
61
+ },
62
+ },
63
+ };
64
+ }