wrangler 0.0.0-ece06ea → 0.0.0-ecfbb0c

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 (190) hide show
  1. package/Cloudflare_CA.pem +18 -0
  2. package/README.md +33 -14
  3. package/bin/wrangler.js +123 -25
  4. package/kv-asset-handler.js +1 -0
  5. package/miniflare-dist/index.mjs +4893 -0
  6. package/package.json +157 -116
  7. package/src/__tests__/config-cache.test.ts +36 -0
  8. package/src/__tests__/configuration.test.ts +3829 -0
  9. package/src/__tests__/dev.test.tsx +1159 -0
  10. package/src/__tests__/guess-worker-format.test.ts +85 -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 +48 -0
  15. package/src/__tests__/helpers/mock-bin.ts +36 -0
  16. package/src/__tests__/helpers/mock-cfetch.ts +211 -0
  17. package/src/__tests__/helpers/mock-console.ts +97 -0
  18. package/src/__tests__/helpers/mock-dialogs.ts +153 -0
  19. package/src/__tests__/helpers/mock-http-server.ts +46 -0
  20. package/src/__tests__/helpers/mock-istty.ts +74 -0
  21. package/src/__tests__/helpers/mock-kv.ts +33 -0
  22. package/src/__tests__/helpers/mock-oauth-flow.ts +250 -0
  23. package/src/__tests__/helpers/mock-process.ts +39 -0
  24. package/src/__tests__/helpers/mock-stdin.ts +108 -0
  25. package/src/__tests__/helpers/mock-web-socket.ts +29 -0
  26. package/src/__tests__/helpers/run-in-tmp.ts +39 -0
  27. package/src/__tests__/helpers/run-wrangler.ts +16 -0
  28. package/src/__tests__/helpers/write-worker-source.ts +31 -0
  29. package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
  30. package/src/__tests__/https-options.test.ts +130 -0
  31. package/src/__tests__/index.test.ts +255 -148
  32. package/src/__tests__/init.test.ts +1992 -0
  33. package/src/__tests__/jest.setup.ts +107 -0
  34. package/src/__tests__/kv.test.ts +1619 -0
  35. package/src/__tests__/logger.test.ts +141 -0
  36. package/src/__tests__/package-manager.test.ts +353 -0
  37. package/src/__tests__/pages.test.ts +1254 -0
  38. package/src/__tests__/parse.test.ts +330 -0
  39. package/src/__tests__/publish.test.ts +6513 -0
  40. package/src/__tests__/pubsub.test.ts +276 -0
  41. package/src/__tests__/r2.test.ts +233 -0
  42. package/src/__tests__/route.test.ts +45 -0
  43. package/src/__tests__/secret.test.ts +486 -0
  44. package/src/__tests__/tail.test.ts +690 -0
  45. package/src/__tests__/user.test.ts +143 -0
  46. package/src/__tests__/whoami.test.tsx +220 -0
  47. package/src/abort.d.ts +3 -0
  48. package/src/api/dev.ts +39 -0
  49. package/src/api/index.ts +1 -0
  50. package/src/bundle-reporter.tsx +29 -0
  51. package/src/bundle.ts +212 -0
  52. package/src/cfetch/index.ts +121 -0
  53. package/src/cfetch/internal.ts +149 -0
  54. package/src/cli.ts +25 -8
  55. package/src/config/README.md +107 -0
  56. package/src/config/config.ts +243 -0
  57. package/src/config/diagnostics.ts +80 -0
  58. package/src/config/environment.ts +430 -0
  59. package/src/config/index.ts +225 -0
  60. package/src/config/validation-helpers.ts +584 -0
  61. package/src/config/validation.ts +1693 -0
  62. package/src/config-cache.ts +44 -0
  63. package/src/create-worker-preview.ts +199 -0
  64. package/src/create-worker-upload-form.ts +254 -0
  65. package/src/dev/dev-vars.ts +36 -0
  66. package/src/dev/dev.tsx +417 -0
  67. package/src/dev/local.tsx +350 -0
  68. package/src/dev/remote.tsx +294 -0
  69. package/src/dev/use-esbuild.ts +150 -0
  70. package/src/dev.tsx +517 -727
  71. package/src/dialogs.tsx +116 -66
  72. package/src/durable.ts +102 -0
  73. package/src/entry.ts +328 -0
  74. package/src/environment-variables.ts +35 -0
  75. package/src/errors.ts +11 -0
  76. package/src/generate.ts +33 -0
  77. package/src/git-client.ts +42 -0
  78. package/src/https-options.ts +123 -0
  79. package/src/index.tsx +1845 -1828
  80. package/src/init.ts +549 -0
  81. package/src/inspect.ts +662 -0
  82. package/src/intl-polyfill.d.ts +139 -0
  83. package/src/kv.ts +408 -0
  84. package/src/logger.ts +73 -0
  85. package/src/miniflare-cli/README.md +30 -0
  86. package/src/miniflare-cli/enum-keys.ts +17 -0
  87. package/src/miniflare-cli/index.ts +52 -0
  88. package/src/miniflare-cli/request-context.ts +40 -0
  89. package/src/module-collection.ts +258 -0
  90. package/src/open-in-browser.ts +17 -0
  91. package/src/package-manager.ts +174 -0
  92. package/src/pages/build.tsx +202 -0
  93. package/src/pages/constants.ts +7 -0
  94. package/src/pages/deployments.tsx +101 -0
  95. package/src/pages/dev.tsx +964 -0
  96. package/src/pages/functions/buildPlugin.ts +105 -0
  97. package/src/pages/functions/buildWorker.ts +151 -0
  98. package/src/pages/functions/filepath-routing.test.ts +234 -0
  99. package/src/pages/functions/filepath-routing.ts +189 -0
  100. package/src/pages/functions/identifiers.ts +78 -0
  101. package/src/pages/functions/routes.ts +151 -0
  102. package/src/pages/index.tsx +84 -0
  103. package/src/pages/projects.tsx +157 -0
  104. package/src/pages/publish.tsx +335 -0
  105. package/src/pages/types.ts +40 -0
  106. package/src/pages/upload.tsx +384 -0
  107. package/src/pages/utils.ts +12 -0
  108. package/src/parse.ts +286 -0
  109. package/src/paths.ts +26 -0
  110. package/src/preview.ts +31 -0
  111. package/src/proxy.ts +476 -0
  112. package/src/publish.ts +755 -343
  113. package/src/pubsub/index.ts +286 -0
  114. package/src/pubsub/pubsub-commands.tsx +594 -0
  115. package/src/r2.ts +50 -0
  116. package/src/selfsigned.d.ts +29 -0
  117. package/src/sites.tsx +357 -100
  118. package/src/tail/filters.ts +279 -0
  119. package/src/tail/index.ts +299 -0
  120. package/src/tail/printing.ts +67 -0
  121. package/src/update-check.ts +19 -0
  122. package/src/user/choose-account.tsx +60 -0
  123. package/src/user/env-vars.ts +46 -0
  124. package/src/user/generate-auth-url.ts +33 -0
  125. package/src/user/generate-random-state.ts +16 -0
  126. package/src/user/index.ts +3 -0
  127. package/src/user/user.tsx +1130 -0
  128. package/src/whoami.tsx +90 -0
  129. package/src/worker.ts +185 -0
  130. package/src/zones.ts +76 -0
  131. package/templates/checked-fetch.js +17 -0
  132. package/templates/gitignore +171 -0
  133. package/templates/new-worker-scheduled.js +17 -0
  134. package/templates/new-worker-scheduled.ts +32 -0
  135. package/templates/new-worker.js +15 -0
  136. package/templates/new-worker.ts +30 -0
  137. package/templates/no-op-worker.js +10 -0
  138. package/templates/pages-template-plugin.ts +155 -0
  139. package/templates/pages-template-worker.ts +161 -0
  140. package/templates/static-asset-facade.js +43 -0
  141. package/templates/tsconfig.json +105 -0
  142. package/wrangler-dist/cli.js +104118 -113381
  143. package/src/__tests__/fixtures/init/.gitkeep +0 -0
  144. package/src/__tests__/mock-cfetch.js +0 -46
  145. package/src/api/form_data.ts +0 -158
  146. package/src/api/inspect.ts +0 -441
  147. package/src/api/preview.ts +0 -123
  148. package/src/api/worker.ts +0 -161
  149. package/src/cfetch.ts +0 -72
  150. package/src/config.ts +0 -124
  151. package/src/kv.tsx +0 -211
  152. package/src/pages.tsx +0 -344
  153. package/src/tail.tsx +0 -71
  154. package/src/user.tsx +0 -1029
  155. package/src/util/fetch.ts +0 -74
  156. package/static-asset-facade.js +0 -47
  157. package/vendor/@cloudflare/kv-asset-handler/CHANGELOG.md +0 -332
  158. package/vendor/@cloudflare/kv-asset-handler/LICENSE_APACHE +0 -176
  159. package/vendor/@cloudflare/kv-asset-handler/LICENSE_MIT +0 -25
  160. package/vendor/@cloudflare/kv-asset-handler/README.md +0 -245
  161. package/vendor/@cloudflare/kv-asset-handler/dist/index.d.ts +0 -32
  162. package/vendor/@cloudflare/kv-asset-handler/dist/index.js +0 -354
  163. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.d.ts +0 -13
  164. package/vendor/@cloudflare/kv-asset-handler/dist/mocks.js +0 -148
  165. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.d.ts +0 -1
  166. package/vendor/@cloudflare/kv-asset-handler/dist/test/getAssetFromKV.js +0 -436
  167. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.d.ts +0 -1
  168. package/vendor/@cloudflare/kv-asset-handler/dist/test/mapRequestToAsset.js +0 -40
  169. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.d.ts +0 -1
  170. package/vendor/@cloudflare/kv-asset-handler/dist/test/serveSinglePageApp.js +0 -42
  171. package/vendor/@cloudflare/kv-asset-handler/dist/types.d.ts +0 -26
  172. package/vendor/@cloudflare/kv-asset-handler/dist/types.js +0 -31
  173. package/vendor/@cloudflare/kv-asset-handler/package.json +0 -52
  174. package/vendor/@cloudflare/kv-asset-handler/src/index.ts +0 -296
  175. package/vendor/@cloudflare/kv-asset-handler/src/mocks.ts +0 -136
  176. package/vendor/@cloudflare/kv-asset-handler/src/test/getAssetFromKV.ts +0 -464
  177. package/vendor/@cloudflare/kv-asset-handler/src/test/mapRequestToAsset.ts +0 -33
  178. package/vendor/@cloudflare/kv-asset-handler/src/test/serveSinglePageApp.ts +0 -42
  179. package/vendor/@cloudflare/kv-asset-handler/src/types.ts +0 -39
  180. package/vendor/wrangler-mime/CHANGELOG.md +0 -289
  181. package/vendor/wrangler-mime/LICENSE +0 -21
  182. package/vendor/wrangler-mime/Mime.js +0 -97
  183. package/vendor/wrangler-mime/README.md +0 -187
  184. package/vendor/wrangler-mime/cli.js +0 -46
  185. package/vendor/wrangler-mime/index.js +0 -4
  186. package/vendor/wrangler-mime/lite.js +0 -4
  187. package/vendor/wrangler-mime/package.json +0 -52
  188. package/vendor/wrangler-mime/types/other.js +0 -1
  189. package/vendor/wrangler-mime/types/standard.js +0 -1
  190. package/wrangler-dist/cli.js.map +0 -7
@@ -0,0 +1,139 @@
1
+ /**
2
+ * TODO Remove once https://github.com/microsoft/TypeScript/pull/47254 lands
3
+ */
4
+ declare namespace Intl {
5
+ interface DateTimeFormatOptions {
6
+ formatMatcher?: "basic" | "best fit" | "best fit" | undefined;
7
+ dateStyle?: "full" | "long" | "medium" | "short" | undefined;
8
+ timeStyle?: "full" | "long" | "medium" | "short" | undefined;
9
+ dayPeriod?: "narrow" | "short" | "long" | undefined;
10
+ fractionalSecondDigits?: 0 | 1 | 2 | 3 | undefined;
11
+ }
12
+
13
+ interface ResolvedDateTimeFormatOptions {
14
+ formatMatcher?: "basic" | "best fit" | "best fit";
15
+ dateStyle?: "full" | "long" | "medium" | "short";
16
+ timeStyle?: "full" | "long" | "medium" | "short";
17
+ hourCycle?: "h11" | "h12" | "h23" | "h24";
18
+ dayPeriod?: "narrow" | "short" | "long";
19
+ fractionalSecondDigits?: 0 | 1 | 2 | 3;
20
+ }
21
+
22
+ interface NumberFormat {
23
+ formatRange(startDate: number | bigint, endDate: number | bigint): string;
24
+ formatRangeToParts(
25
+ startDate: number | bigint,
26
+ endDate: number | bigint
27
+ ): NumberFormatPart[];
28
+ }
29
+
30
+ /**
31
+ * The locale matching algorithm to use.
32
+ *
33
+ * [MDN](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation).
34
+ */
35
+ type ListFormatLocaleMatcher = "lookup" | "best fit";
36
+
37
+ /**
38
+ * The format of output message.
39
+ *
40
+ * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
41
+ */
42
+ type ListFormatType = "conjunction" | "disjunction" | "unit";
43
+
44
+ /**
45
+ * The length of the formatted message.
46
+ *
47
+ * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
48
+ */
49
+ type ListFormatStyle = "long" | "short" | "narrow";
50
+
51
+ /**
52
+ * An object with some or all properties of the `Intl.ListFormat` constructor `options` parameter.
53
+ *
54
+ * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters).
55
+ */
56
+ interface ListFormatOptions {
57
+ /** The locale matching algorithm to use. For information about this option, see [Intl page](https://developer.mozilla.org/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_negotiation). */
58
+ localeMatcher?: ListFormatLocaleMatcher;
59
+ /** The format of output message. */
60
+ type?: ListFormatType;
61
+ /** The length of the internationalized message. */
62
+ style?: ListFormatStyle;
63
+ }
64
+
65
+ interface ListFormat {
66
+ /**
67
+ * Returns a string with a language-specific representation of the list.
68
+ *
69
+ * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array).
70
+ *
71
+ * @throws `TypeError` if `list` includes something other than the possible values.
72
+ *
73
+ * @returns {string} A language-specific formatted string representing the elements of the list.
74
+ *
75
+ * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/format).
76
+ */
77
+ format(list: Iterable<string>): string;
78
+
79
+ /**
80
+ * Returns an Array of objects representing the different components that can be used to format a list of values in a locale-aware fashion.
81
+ *
82
+ * @param list - An iterable object, such as an [Array](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array), to be formatted according to a locale.
83
+ *
84
+ * @throws `TypeError` if `list` includes something other than the possible values.
85
+ *
86
+ * @returns {{ type: "element" | "literal", value: string; }[]} An Array of components which contains the formatted parts from the list.
87
+ *
88
+ * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/formatToParts).
89
+ */
90
+ formatToParts(
91
+ list: Iterable<string>
92
+ ): { type: "element" | "literal"; value: string }[];
93
+ }
94
+
95
+ const ListFormat: {
96
+ prototype: ListFormat;
97
+
98
+ /**
99
+ * Creates [Intl.ListFormat](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) objects that
100
+ * enable language-sensitive list formatting.
101
+ *
102
+ * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
103
+ * For the general form and interpretation of the `locales` argument,
104
+ * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
105
+ *
106
+ * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/ListFormat#parameters)
107
+ * with some or all options of `ListFormatOptions`.
108
+ *
109
+ * @returns [Intl.ListFormatOptions](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat) object.
110
+ *
111
+ * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat).
112
+ */
113
+ new (
114
+ locales?: BCP47LanguageTag | BCP47LanguageTag[],
115
+ options?: ListFormatOptions
116
+ ): ListFormat;
117
+
118
+ /**
119
+ * Returns an array containing those of the provided locales that are
120
+ * supported in list formatting without having to fall back to the runtime's default locale.
121
+ *
122
+ * @param locales - A string with a [BCP 47 language tag](http://tools.ietf.org/html/rfc5646), or an array of such strings.
123
+ * For the general form and interpretation of the `locales` argument,
124
+ * see the [`Intl` page](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl#Locale_identification_and_negotiation).
125
+ *
126
+ * @param options - An [object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf#parameters).
127
+ * with some or all possible options.
128
+ *
129
+ * @returns An array of strings representing a subset of the given locale tags that are supported in list
130
+ * formatting without having to fall back to the runtime's default locale.
131
+ *
132
+ * [MDN](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/ListFormat/supportedLocalesOf).
133
+ */
134
+ supportedLocalesOf(
135
+ locales: BCP47LanguageTag | BCP47LanguageTag[],
136
+ options?: Pick<ListFormatOptions, "localeMatcher">
137
+ ): BCP47LanguageTag[];
138
+ };
139
+ }
package/src/kv.ts ADDED
@@ -0,0 +1,408 @@
1
+ import { URLSearchParams } from "node:url";
2
+ import { fetchListResult, fetchResult, fetchKVGetValue } from "./cfetch";
3
+ import { logger } from "./logger";
4
+ import type { Config } from "./config";
5
+
6
+ /** The largest number of kv items we can pass to the API in a single request. */
7
+ const API_MAX = 10000;
8
+ // The const below are halved from the API's true capacity to help avoid
9
+ // hammering it with large requests.
10
+ const BATCH_KEY_MAX = API_MAX / 2;
11
+
12
+ type KvArgs = {
13
+ binding?: string;
14
+ "namespace-id"?: string;
15
+ preview?: boolean;
16
+ };
17
+
18
+ /**
19
+ * Create a new namespace under the given `accountId` with the given `title`.
20
+ *
21
+ * @returns the generated id of the created namespace.
22
+ */
23
+ export async function createKVNamespace(
24
+ accountId: string,
25
+ title: string
26
+ ): Promise<string> {
27
+ const response = await fetchResult<{ id: string }>(
28
+ `/accounts/${accountId}/storage/kv/namespaces`,
29
+ {
30
+ method: "POST",
31
+ headers: {
32
+ "Content-Type": "application/json",
33
+ },
34
+ body: JSON.stringify({
35
+ title,
36
+ }),
37
+ }
38
+ );
39
+
40
+ return response.id;
41
+ }
42
+
43
+ /**
44
+ * The information about a namespace that is returned from `listNamespaces()`.
45
+ */
46
+ export interface KVNamespaceInfo {
47
+ id: string;
48
+ title: string;
49
+ supports_url_encoding?: boolean;
50
+ }
51
+
52
+ /**
53
+ * Fetch a list of all the namespaces under the given `accountId`.
54
+ */
55
+ export async function listKVNamespaces(
56
+ accountId: string
57
+ ): Promise<KVNamespaceInfo[]> {
58
+ const pageSize = 100;
59
+ let page = 1;
60
+ const results: KVNamespaceInfo[] = [];
61
+ while (results.length % pageSize === 0) {
62
+ const json = await fetchResult<KVNamespaceInfo[]>(
63
+ `/accounts/${accountId}/storage/kv/namespaces`,
64
+ {},
65
+ new URLSearchParams({
66
+ per_page: pageSize.toString(),
67
+ order: "title",
68
+ direction: "asc",
69
+ page: page.toString(),
70
+ })
71
+ );
72
+ page++;
73
+ results.push(...json);
74
+ if (json.length < pageSize) {
75
+ break;
76
+ }
77
+ }
78
+ return results;
79
+ }
80
+
81
+ export interface NamespaceKeyInfo {
82
+ name: string;
83
+ expiration?: number;
84
+ metadata?: { [key: string]: unknown };
85
+ }
86
+
87
+ export async function listKVNamespaceKeys(
88
+ accountId: string,
89
+ namespaceId: string,
90
+ prefix = ""
91
+ ) {
92
+ return await fetchListResult<NamespaceKeyInfo>(
93
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys`,
94
+ {},
95
+ new URLSearchParams({ prefix })
96
+ );
97
+ }
98
+
99
+ export async function deleteKVNamespace(
100
+ accountId: string,
101
+ namespaceId: string
102
+ ) {
103
+ return await fetchResult<{ id: string }>(
104
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}`,
105
+ { method: "DELETE" }
106
+ );
107
+ }
108
+
109
+ /**
110
+ * Information about a key-value pair, including its "metadata" fields.
111
+ */
112
+ export interface KeyValue {
113
+ key: string;
114
+ value: string | Buffer;
115
+ expiration?: number;
116
+ expiration_ttl?: number;
117
+ metadata?: object;
118
+ base64?: boolean;
119
+ }
120
+
121
+ const KeyValueKeys = new Set([
122
+ "key",
123
+ "value",
124
+ "expiration",
125
+ "expiration_ttl",
126
+ "metadata",
127
+ "base64",
128
+ ]);
129
+
130
+ /**
131
+ * The object has the specified property.
132
+ */
133
+ function hasProperty<T extends object>(
134
+ obj: object,
135
+ property: keyof T
136
+ ): obj is T {
137
+ return property in obj;
138
+ }
139
+
140
+ /**
141
+ * The object has a required property of the specified type.
142
+ */
143
+ function hasTypedProperty<T extends object>(
144
+ obj: object,
145
+ property: keyof T,
146
+ type: string
147
+ ): obj is T {
148
+ return hasProperty(obj, property) && typeof obj[property] === type;
149
+ }
150
+
151
+ /**
152
+ * The object an optional property, of the specified type.
153
+ */
154
+ function hasOptionalTypedProperty<T extends object>(
155
+ obj: object,
156
+ property: keyof T,
157
+ type: string
158
+ ): obj is Omit<T, typeof property> | T {
159
+ return !hasProperty(obj, property) || typeof obj[property] === type;
160
+ }
161
+
162
+ /**
163
+ * Is the given object a valid `KeyValue` type?
164
+ */
165
+ export function isKVKeyValue(keyValue: unknown): keyValue is KeyValue {
166
+ if (
167
+ keyValue === null ||
168
+ typeof keyValue !== "object" ||
169
+ !hasTypedProperty(keyValue, "key", "string") ||
170
+ !hasTypedProperty(keyValue, "value", "string") ||
171
+ !hasOptionalTypedProperty(keyValue, "expiration", "number") ||
172
+ !hasOptionalTypedProperty(keyValue, "expiration_ttl", "number") ||
173
+ !hasOptionalTypedProperty(keyValue, "base64", "boolean") ||
174
+ !hasOptionalTypedProperty(keyValue, "metadata", "object")
175
+ ) {
176
+ return false;
177
+ }
178
+ return true;
179
+ }
180
+
181
+ /**
182
+ * Get all the properties on the `keyValue` that are not expected.
183
+ */
184
+ export function unexpectedKVKeyValueProps(keyValue: KeyValue): string[] {
185
+ const props = Object.keys(keyValue);
186
+ return props.filter((prop) => !KeyValueKeys.has(prop));
187
+ }
188
+
189
+ export async function putKVKeyValue(
190
+ accountId: string,
191
+ namespaceId: string,
192
+ keyValue: KeyValue
193
+ ) {
194
+ let searchParams: URLSearchParams | undefined;
195
+ if (keyValue.expiration || keyValue.expiration_ttl) {
196
+ searchParams = new URLSearchParams();
197
+ if (keyValue.expiration) {
198
+ searchParams.set("expiration", `${keyValue.expiration}`);
199
+ }
200
+ if (keyValue.expiration_ttl) {
201
+ searchParams.set("expiration_ttl", `${keyValue.expiration_ttl}`);
202
+ }
203
+ }
204
+ return await fetchResult(
205
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${encodeURIComponent(
206
+ keyValue.key
207
+ )}`,
208
+ { method: "PUT", body: keyValue.value },
209
+ searchParams
210
+ );
211
+ }
212
+
213
+ export async function getKVKeyValue(
214
+ accountId: string,
215
+ namespaceId: string,
216
+ key: string
217
+ ): Promise<ArrayBuffer> {
218
+ return await fetchKVGetValue(accountId, namespaceId, encodeURIComponent(key));
219
+ }
220
+
221
+ export async function deleteKVKeyValue(
222
+ accountId: string,
223
+ namespaceId: string,
224
+ key: string
225
+ ) {
226
+ return await fetchResult(
227
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${encodeURIComponent(
228
+ key
229
+ )}`,
230
+ { method: "DELETE" }
231
+ );
232
+ }
233
+
234
+ /**
235
+ * Formatter for converting e.g. 5328 --> 5,328
236
+ */
237
+ const formatNumber = new Intl.NumberFormat("en-US", {
238
+ notation: "standard",
239
+ }).format;
240
+
241
+ /**
242
+ * Helper function for bulk requests, logs ongoing output to console.
243
+ */
244
+ function logBulkProgress(
245
+ operation: "put" | "delete",
246
+ index: number,
247
+ total: number
248
+ ) {
249
+ logger.log(
250
+ `${operation === "put" ? "Uploaded" : "Deleted"} ${Math.floor(
251
+ (100 * index) / total
252
+ )}% (${formatNumber(index)} out of ${formatNumber(total)})`
253
+ );
254
+ }
255
+
256
+ export async function putKVBulkKeyValue(
257
+ accountId: string,
258
+ namespaceId: string,
259
+ keyValues: KeyValue[],
260
+ quiet = false
261
+ ) {
262
+ for (let index = 0; index < keyValues.length; index += BATCH_KEY_MAX) {
263
+ if (!quiet && keyValues.length > BATCH_KEY_MAX) {
264
+ logBulkProgress("put", index, keyValues.length);
265
+ }
266
+
267
+ await fetchResult(
268
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
269
+ {
270
+ method: "PUT",
271
+ body: JSON.stringify(keyValues.slice(index, index + BATCH_KEY_MAX)),
272
+ headers: { "Content-Type": "application/json" },
273
+ }
274
+ );
275
+ }
276
+
277
+ if (!quiet && keyValues.length > BATCH_KEY_MAX) {
278
+ logBulkProgress("put", keyValues.length, keyValues.length);
279
+ }
280
+ }
281
+
282
+ export async function deleteKVBulkKeyValue(
283
+ accountId: string,
284
+ namespaceId: string,
285
+ keys: string[],
286
+ quiet = false
287
+ ) {
288
+ for (let index = 0; index < keys.length; index += BATCH_KEY_MAX) {
289
+ if (!quiet && keys.length > BATCH_KEY_MAX) {
290
+ logBulkProgress("delete", index, keys.length);
291
+ }
292
+
293
+ await fetchResult(
294
+ `/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
295
+ {
296
+ method: "DELETE",
297
+ body: JSON.stringify(keys.slice(index, index + BATCH_KEY_MAX)),
298
+ headers: { "Content-Type": "application/json" },
299
+ }
300
+ );
301
+ }
302
+ if (!quiet && keys.length > BATCH_KEY_MAX) {
303
+ logBulkProgress("delete", keys.length, keys.length);
304
+ }
305
+ }
306
+
307
+ export function getKVNamespaceId(
308
+ { preview, binding, "namespace-id": namespaceId }: KvArgs,
309
+ config: Config
310
+ ): string {
311
+ // nice
312
+ if (namespaceId) {
313
+ return namespaceId;
314
+ }
315
+
316
+ // begin pre-flight checks
317
+
318
+ // `--binding` is only valid if there's a wrangler configuration.
319
+ if (binding && !config) {
320
+ throw new Error("--binding specified, but no config file was found.");
321
+ }
322
+
323
+ // there's no config. abort here
324
+ if (!config) {
325
+ throw new Error(
326
+ "Failed to find a config file.\n" +
327
+ "Either use --namespace-id to upload directly or create a configuration file with a binding."
328
+ );
329
+ }
330
+
331
+ // there's no KV namespaces
332
+ if (!config.kv_namespaces || config.kv_namespaces.length === 0) {
333
+ throw new Error(
334
+ "No KV Namespaces configured! Either use --namespace-id to upload directly or add a KV namespace to your wrangler config file."
335
+ );
336
+ }
337
+
338
+ const namespace = config.kv_namespaces.find((ns) => ns.binding === binding);
339
+
340
+ // we couldn't find a namespace with that binding
341
+ if (!namespace) {
342
+ throw new Error(
343
+ `A namespace with binding name "${binding}" was not found in the configured "kv_namespaces".`
344
+ );
345
+ }
346
+
347
+ // end pre-flight checks
348
+
349
+ // we're in preview mode, `--preview true` or `--preview` was passed
350
+ if (preview && namespace.preview_id) {
351
+ namespaceId = namespace.preview_id;
352
+ // We don't want to execute code below if preview is set to true, so we just return. Otherwise we will get errors!
353
+ return namespaceId;
354
+ } else if (preview) {
355
+ throw new Error(
356
+ `No preview ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
357
+ );
358
+ }
359
+
360
+ // either `--preview false`, or preview wasn't passed
361
+ // TODO: should we care? or should we just treat false and undefined the same
362
+ const previewIsDefined = typeof preview !== "undefined";
363
+
364
+ // --preview false was passed
365
+ if (previewIsDefined && namespace.id) {
366
+ namespaceId = namespace.id;
367
+ // We don't want to execute code below if preview is set to true, so we just return. Otherwise we can get error!
368
+ return namespaceId;
369
+ } else if (previewIsDefined) {
370
+ throw new Error(
371
+ `No namespace ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
372
+ );
373
+ }
374
+
375
+ // `--preview` wasn't passed
376
+ const bindingHasOnlyOneId =
377
+ (namespace.id && !namespace.preview_id) ||
378
+ (!namespace.id && namespace.preview_id);
379
+ if (bindingHasOnlyOneId) {
380
+ namespaceId = namespace.id || namespace.preview_id;
381
+ } else {
382
+ throw new Error(
383
+ `${binding} has both a namespace ID and a preview ID. Specify "--preview" or "--preview false" to avoid writing data to the wrong namespace.`
384
+ );
385
+ }
386
+
387
+ // shouldn't happen. we should be able to prove this with strong typing.
388
+ // TODO: when we add strongly typed commands, rewrite these checks so they're exhaustive
389
+ if (!namespaceId) {
390
+ throw Error(
391
+ "Something went wrong trying to determine which namespace to upload to.\n" +
392
+ "Please create a github issue with the command you just ran along with your wrangler configuration."
393
+ );
394
+ }
395
+
396
+ return namespaceId;
397
+ }
398
+
399
+ /**
400
+ * KV namespace binding names must be valid JS identifiers.
401
+ */
402
+ export function isValidKVNamespaceBinding(
403
+ binding: string | undefined
404
+ ): binding is string {
405
+ return (
406
+ typeof binding === "string" && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(binding)
407
+ );
408
+ }
package/src/logger.ts ADDED
@@ -0,0 +1,73 @@
1
+ import { format } from "node:util";
2
+ import { formatMessagesSync } from "esbuild";
3
+ import { getEnvironmentVariableFactory } from "./environment-variables";
4
+
5
+ const LOGGER_LEVELS = {
6
+ error: 0,
7
+ warn: 1,
8
+ log: 2,
9
+ debug: 3,
10
+ } as const;
11
+
12
+ type LoggerLevel = keyof typeof LOGGER_LEVELS;
13
+
14
+ /** A map from LOGGER_LEVEL to the error `kind` needed by `formatMessagesSync()`. */
15
+ const LOGGER_LEVEL_FORMAT_TYPE_MAP = {
16
+ error: "error",
17
+ warn: "warning",
18
+ log: undefined,
19
+ debug: undefined,
20
+ } as const;
21
+
22
+ const getLogLevelFromEnv = getEnvironmentVariableFactory({
23
+ variableName: "WRANGLER_LOG",
24
+ defaultValue: "log",
25
+ });
26
+
27
+ class Logger {
28
+ constructor() {}
29
+
30
+ loggerLevel: LoggerLevel = (getLogLevelFromEnv() as LoggerLevel) ?? "log";
31
+ columns = process.stdout.columns;
32
+
33
+ debug = (...args: unknown[]) => this.doLog("debug", args);
34
+ log = (...args: unknown[]) => this.doLog("log", args);
35
+ warn = (...args: unknown[]) => this.doLog("warn", args);
36
+ error = (...args: unknown[]) => this.doLog("error", args);
37
+
38
+ private doLog(messageLevel: LoggerLevel, args: unknown[]) {
39
+ if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[messageLevel]) {
40
+ console[messageLevel](this.formatMessage(messageLevel, format(...args)));
41
+ }
42
+ }
43
+
44
+ private formatMessage(level: LoggerLevel, message: string): string {
45
+ const kind = LOGGER_LEVEL_FORMAT_TYPE_MAP[level];
46
+ if (kind) {
47
+ // Format the message using the esbuild formatter.
48
+ // The first line of the message is the main `text`,
49
+ // subsequent lines are put into the `notes`.
50
+ const [firstLine, ...otherLines] = message.split("\n");
51
+ const notes =
52
+ otherLines.length > 0
53
+ ? otherLines.map((text) => ({ text }))
54
+ : undefined;
55
+ return formatMessagesSync([{ text: firstLine, notes }], {
56
+ color: true,
57
+ kind,
58
+ terminalWidth: this.columns,
59
+ })[0];
60
+ } else {
61
+ return message;
62
+ }
63
+ }
64
+ }
65
+
66
+ /**
67
+ * A drop-in replacement for `console` for outputting logging messages.
68
+ *
69
+ * Errors and Warnings will get additional formatting to highlight them to the user.
70
+ * You can also set a `logger.loggerLevel` value to one of "debug", "log", "warn" or "error",
71
+ * to filter out logging messages.
72
+ */
73
+ export const logger = new Logger();
@@ -0,0 +1,30 @@
1
+ # Custom Miniflare CLI
2
+
3
+ This directory contains a simple wrapper around the programmatic Miniflare API,
4
+ which Wrangler spawns when running `wrangler dev` in local mode.
5
+
6
+ ## Building
7
+
8
+ This CLI is built at the same time as Wrangler by running
9
+
10
+ ```
11
+ npm run -w wrangler build
12
+ ```
13
+
14
+ The output of the build is `miniflare-dist/index.mjs`.
15
+
16
+ ## Running
17
+
18
+ The CLI expects a single command line argument which is the Miniflare options formatted as a string of JSON.
19
+
20
+ ```bash
21
+ node --no-warnings ./packages/wrangler/miniflare-dist/index.mjs '{"watch": true, "script": ""}' --log VERBOSE
22
+ ```
23
+
24
+ The `--log` argument is optional and takes one of Miniflare's LogLevels: "NONE", "ERROR", "WARN", "INFO", "DEBUG", "VERBOSE".
25
+ It defaults to `INFO`.
26
+
27
+ ## Debugging
28
+
29
+ Simply place a breakpoint in the code and run the above command in the VS Code "JavaScript Debug Terminal".
30
+ The code will stop at the breakpoint as expected.
@@ -0,0 +1,17 @@
1
+ export type EnumKeys<Enum> = Exclude<keyof Enum, number>;
2
+
3
+ export const enumObject = <Enum extends Record<string, number | string>>(
4
+ e: Enum
5
+ ) => {
6
+ const copy = { ...e } as { [K in EnumKeys<Enum>]: Enum[K] };
7
+ Object.values(e).forEach(
8
+ (value) => typeof value === "number" && delete copy[value]
9
+ );
10
+ return copy;
11
+ };
12
+
13
+ export const enumKeys = <Enum extends Record<string, number | string>>(
14
+ e: Enum
15
+ ) => {
16
+ return Object.keys(enumObject(e)) as EnumKeys<Enum>[];
17
+ };