wrangler 0.0.0-ece06ea → 0.0.0-ed08df4
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.
- package/Cloudflare_CA.pem +18 -0
- package/README.md +27 -14
- package/bin/wrangler.js +34 -2
- package/miniflare-dist/index.mjs +4886 -0
- package/package.json +71 -36
- package/pages/functions/buildPlugin.ts +92 -0
- package/pages/functions/buildWorker.ts +138 -0
- package/pages/functions/filepath-routing.test.ts +234 -0
- package/pages/functions/filepath-routing.ts +189 -0
- package/pages/functions/identifiers.ts +78 -0
- package/pages/functions/routes.ts +156 -0
- package/pages/functions/template-plugin.ts +147 -0
- package/pages/functions/template-worker.ts +143 -0
- package/src/__tests__/config-cache.test.ts +36 -0
- package/src/__tests__/configuration.test.ts +3125 -0
- package/src/__tests__/dev.test.tsx +829 -0
- package/src/__tests__/guess-worker-format.test.ts +85 -0
- package/src/__tests__/{clipboardy-mock.js → helpers/clipboardy-mock.js} +0 -0
- package/src/__tests__/helpers/cmd-shim.d.ts +11 -0
- package/src/__tests__/helpers/faye-websocket.d.ts +6 -0
- package/src/__tests__/helpers/mock-account-id.ts +48 -0
- package/src/__tests__/helpers/mock-bin.ts +36 -0
- package/src/__tests__/helpers/mock-cfetch.ts +211 -0
- package/src/__tests__/helpers/mock-console.ts +87 -0
- package/src/__tests__/helpers/mock-dialogs.ts +90 -0
- package/src/__tests__/helpers/mock-http-server.ts +46 -0
- package/src/__tests__/helpers/mock-istty.ts +27 -0
- package/src/__tests__/helpers/mock-kv.ts +33 -0
- package/src/__tests__/helpers/mock-oauth-flow.ts +255 -0
- package/src/__tests__/helpers/mock-stdin.ts +103 -0
- package/src/__tests__/helpers/mock-web-socket.ts +29 -0
- package/src/__tests__/helpers/run-in-tmp.ts +39 -0
- package/src/__tests__/helpers/run-wrangler.ts +16 -0
- package/src/__tests__/helpers/write-worker-source.ts +31 -0
- package/src/__tests__/helpers/write-wrangler-toml.ts +17 -0
- package/src/__tests__/https-options.test.ts +130 -0
- package/src/__tests__/index.test.ts +221 -132
- package/src/__tests__/init.test.ts +1516 -0
- package/src/__tests__/jest.setup.ts +77 -0
- package/src/__tests__/kv.test.ts +1481 -0
- package/src/__tests__/logger.test.ts +115 -0
- package/src/__tests__/package-manager.test.ts +206 -0
- package/src/__tests__/pages.test.ts +327 -0
- package/src/__tests__/parse.test.ts +326 -0
- package/src/__tests__/publish.test.ts +4996 -0
- package/src/__tests__/r2.test.ts +210 -0
- package/src/__tests__/route.test.ts +45 -0
- package/src/__tests__/secret.test.ts +446 -0
- package/src/__tests__/tail.test.ts +690 -0
- package/src/__tests__/user.test.ts +131 -0
- package/src/__tests__/whoami.test.tsx +105 -0
- package/src/bundle.ts +169 -0
- package/src/cfetch/index.ts +104 -0
- package/src/cfetch/internal.ts +140 -0
- package/src/cli.ts +10 -7
- package/src/config/README.md +107 -0
- package/src/config/config.ts +234 -0
- package/src/config/diagnostics.ts +80 -0
- package/src/config/environment.ts +394 -0
- package/src/config/index.ts +63 -0
- package/src/config/validation-helpers.ts +575 -0
- package/src/config/validation.ts +1424 -0
- package/src/config-cache.ts +45 -0
- package/src/create-worker-preview.ts +175 -0
- package/src/create-worker-upload-form.ts +240 -0
- package/src/dev/dev-vars.ts +36 -0
- package/src/dev/dev.tsx +421 -0
- package/src/dev/local.tsx +312 -0
- package/src/dev/remote.tsx +213 -0
- package/src/dev/use-esbuild.ts +118 -0
- package/src/dialogs.tsx +22 -20
- package/src/entry.ts +322 -0
- package/src/environment-variables.ts +35 -0
- package/src/errors.ts +11 -0
- package/src/https-options.ts +123 -0
- package/src/index.tsx +1869 -1020
- package/src/inspect.ts +623 -0
- package/src/intl-polyfill.d.ts +139 -0
- package/src/kv.ts +344 -0
- package/src/logger.ts +66 -0
- package/src/miniflare-cli/README.md +30 -0
- package/src/miniflare-cli/enum-keys.ts +17 -0
- package/src/miniflare-cli/index.ts +41 -0
- package/src/miniflare-cli/request-context.ts +40 -0
- package/src/module-collection.ts +258 -0
- package/src/open-in-browser.ts +26 -0
- package/src/package-manager.ts +127 -0
- package/src/pages.tsx +1756 -218
- package/src/parse.ts +185 -0
- package/src/paths.ts +26 -0
- package/src/proxy.ts +449 -0
- package/src/publish.ts +377 -262
- package/src/r2.ts +50 -0
- package/src/selfsigned.d.ts +29 -0
- package/src/sites.tsx +237 -59
- package/src/tail/filters.ts +279 -0
- package/src/tail/index.ts +299 -0
- package/src/tail/printing.ts +67 -0
- package/src/update-check.ts +19 -0
- package/src/user.tsx +395 -221
- package/src/whoami.tsx +70 -0
- package/src/worker.ts +172 -0
- package/templates/gitignore +171 -0
- package/templates/new-worker.js +15 -0
- package/templates/new-worker.ts +15 -0
- package/{static-asset-facade.js → templates/static-asset-facade.js} +1 -1
- package/templates/tsconfig.json +105 -0
- package/wrangler-dist/cli.js +108921 -132528
- package/src/__tests__/fixtures/init/.gitkeep +0 -0
- package/src/__tests__/mock-cfetch.js +0 -46
- package/src/api/form_data.ts +0 -158
- package/src/api/inspect.ts +0 -441
- package/src/api/preview.ts +0 -123
- package/src/api/worker.ts +0 -161
- package/src/cfetch.ts +0 -72
- package/src/config.ts +0 -124
- package/src/dev.tsx +0 -736
- package/src/kv.tsx +0 -211
- package/src/tail.tsx +0 -71
- package/src/util/fetch.ts +0 -74
- 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,344 @@
|
|
|
1
|
+
import { URLSearchParams } from "node:url";
|
|
2
|
+
import { fetchListResult, fetchResult, fetchKVGetValue } from "./cfetch";
|
|
3
|
+
import type { Config } from "./config";
|
|
4
|
+
|
|
5
|
+
/** The largest number of kv items we can pass to the API in a single request. */
|
|
6
|
+
const API_MAX = 10000;
|
|
7
|
+
// The const below are halved from the API's true capacity to help avoid
|
|
8
|
+
// hammering it with large requests.
|
|
9
|
+
const BATCH_KEY_MAX = API_MAX / 2;
|
|
10
|
+
|
|
11
|
+
type KvArgs = {
|
|
12
|
+
binding?: string;
|
|
13
|
+
"namespace-id"?: string;
|
|
14
|
+
preview?: boolean;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Create a new namespace under the given `accountId` with the given `title`.
|
|
19
|
+
*
|
|
20
|
+
* @returns the generated id of the created namespace.
|
|
21
|
+
*/
|
|
22
|
+
export async function createKVNamespace(
|
|
23
|
+
accountId: string,
|
|
24
|
+
title: string
|
|
25
|
+
): Promise<string> {
|
|
26
|
+
const response = await fetchResult<{ id: string }>(
|
|
27
|
+
`/accounts/${accountId}/storage/kv/namespaces`,
|
|
28
|
+
{
|
|
29
|
+
method: "POST",
|
|
30
|
+
headers: {
|
|
31
|
+
"Content-Type": "application/json",
|
|
32
|
+
},
|
|
33
|
+
body: JSON.stringify({
|
|
34
|
+
title,
|
|
35
|
+
}),
|
|
36
|
+
}
|
|
37
|
+
);
|
|
38
|
+
|
|
39
|
+
return response.id;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
/**
|
|
43
|
+
* The information about a namespace that is returned from `listNamespaces()`.
|
|
44
|
+
*/
|
|
45
|
+
export interface KVNamespaceInfo {
|
|
46
|
+
id: string;
|
|
47
|
+
title: string;
|
|
48
|
+
supports_url_encoding?: boolean;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/**
|
|
52
|
+
* Fetch a list of all the namespaces under the given `accountId`.
|
|
53
|
+
*/
|
|
54
|
+
export async function listKVNamespaces(
|
|
55
|
+
accountId: string
|
|
56
|
+
): Promise<KVNamespaceInfo[]> {
|
|
57
|
+
const pageSize = 100;
|
|
58
|
+
let page = 1;
|
|
59
|
+
const results: KVNamespaceInfo[] = [];
|
|
60
|
+
while (results.length % pageSize === 0) {
|
|
61
|
+
const json = await fetchResult<KVNamespaceInfo[]>(
|
|
62
|
+
`/accounts/${accountId}/storage/kv/namespaces`,
|
|
63
|
+
{},
|
|
64
|
+
new URLSearchParams({
|
|
65
|
+
per_page: pageSize.toString(),
|
|
66
|
+
order: "title",
|
|
67
|
+
direction: "asc",
|
|
68
|
+
page: page.toString(),
|
|
69
|
+
})
|
|
70
|
+
);
|
|
71
|
+
page++;
|
|
72
|
+
results.push(...json);
|
|
73
|
+
if (json.length < pageSize) {
|
|
74
|
+
break;
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
return results;
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export interface NamespaceKeyInfo {
|
|
81
|
+
name: string;
|
|
82
|
+
expiration?: number;
|
|
83
|
+
metadata?: { [key: string]: unknown };
|
|
84
|
+
}
|
|
85
|
+
|
|
86
|
+
export async function listKVNamespaceKeys(
|
|
87
|
+
accountId: string,
|
|
88
|
+
namespaceId: string,
|
|
89
|
+
prefix = ""
|
|
90
|
+
) {
|
|
91
|
+
return await fetchListResult<NamespaceKeyInfo>(
|
|
92
|
+
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys`,
|
|
93
|
+
{},
|
|
94
|
+
new URLSearchParams({ prefix })
|
|
95
|
+
);
|
|
96
|
+
}
|
|
97
|
+
|
|
98
|
+
export async function deleteKVNamespace(
|
|
99
|
+
accountId: string,
|
|
100
|
+
namespaceId: string
|
|
101
|
+
) {
|
|
102
|
+
return await fetchResult<{ id: string }>(
|
|
103
|
+
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}`,
|
|
104
|
+
{ method: "DELETE" }
|
|
105
|
+
);
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Information about a key-value pair, including its "metadata" fields.
|
|
110
|
+
*/
|
|
111
|
+
export interface KeyValue {
|
|
112
|
+
key: string;
|
|
113
|
+
value: string;
|
|
114
|
+
expiration?: number;
|
|
115
|
+
expiration_ttl?: number;
|
|
116
|
+
metadata?: object;
|
|
117
|
+
base64?: boolean;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const KeyValueKeys = new Set([
|
|
121
|
+
"key",
|
|
122
|
+
"value",
|
|
123
|
+
"expiration",
|
|
124
|
+
"expiration_ttl",
|
|
125
|
+
"metadata",
|
|
126
|
+
"base64",
|
|
127
|
+
]);
|
|
128
|
+
|
|
129
|
+
/**
|
|
130
|
+
* Is the given object a valid `KeyValue` type?
|
|
131
|
+
*/
|
|
132
|
+
export function isKVKeyValue(keyValue: object): keyValue is KeyValue {
|
|
133
|
+
const props = Object.keys(keyValue);
|
|
134
|
+
if (!props.includes("key") || !props.includes("value")) {
|
|
135
|
+
return false;
|
|
136
|
+
}
|
|
137
|
+
return true;
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
/**
|
|
141
|
+
* Get all the properties on the `keyValue` that are not expected.
|
|
142
|
+
*/
|
|
143
|
+
export function unexpectedKVKeyValueProps(keyValue: KeyValue): string[] {
|
|
144
|
+
const props = Object.keys(keyValue);
|
|
145
|
+
return props.filter((prop) => !KeyValueKeys.has(prop));
|
|
146
|
+
}
|
|
147
|
+
|
|
148
|
+
export async function putKVKeyValue(
|
|
149
|
+
accountId: string,
|
|
150
|
+
namespaceId: string,
|
|
151
|
+
keyValue: KeyValue
|
|
152
|
+
) {
|
|
153
|
+
let searchParams: URLSearchParams | undefined;
|
|
154
|
+
if (keyValue.expiration || keyValue.expiration_ttl) {
|
|
155
|
+
searchParams = new URLSearchParams();
|
|
156
|
+
if (keyValue.expiration) {
|
|
157
|
+
searchParams.set("expiration", `${keyValue.expiration}`);
|
|
158
|
+
}
|
|
159
|
+
if (keyValue.expiration_ttl) {
|
|
160
|
+
searchParams.set("expiration_ttl", `${keyValue.expiration_ttl}`);
|
|
161
|
+
}
|
|
162
|
+
}
|
|
163
|
+
return await fetchResult(
|
|
164
|
+
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${encodeURIComponent(
|
|
165
|
+
keyValue.key
|
|
166
|
+
)}`,
|
|
167
|
+
{ method: "PUT", body: keyValue.value },
|
|
168
|
+
searchParams
|
|
169
|
+
);
|
|
170
|
+
}
|
|
171
|
+
|
|
172
|
+
export async function getKVKeyValue(
|
|
173
|
+
accountId: string,
|
|
174
|
+
namespaceId: string,
|
|
175
|
+
key: string
|
|
176
|
+
): Promise<string> {
|
|
177
|
+
return await fetchKVGetValue(accountId, namespaceId, encodeURIComponent(key));
|
|
178
|
+
}
|
|
179
|
+
|
|
180
|
+
export async function deleteKVKeyValue(
|
|
181
|
+
accountId: string,
|
|
182
|
+
namespaceId: string,
|
|
183
|
+
key: string
|
|
184
|
+
) {
|
|
185
|
+
return await fetchResult(
|
|
186
|
+
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/values/${encodeURIComponent(
|
|
187
|
+
key
|
|
188
|
+
)}`,
|
|
189
|
+
{ method: "DELETE" }
|
|
190
|
+
);
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
export async function putKVBulkKeyValue(
|
|
194
|
+
accountId: string,
|
|
195
|
+
namespaceId: string,
|
|
196
|
+
keyValues: KeyValue[],
|
|
197
|
+
progressCallback: (index: number, total: number) => void
|
|
198
|
+
) {
|
|
199
|
+
for (let index = 0; index < keyValues.length; index += BATCH_KEY_MAX) {
|
|
200
|
+
if (progressCallback && keyValues.length > BATCH_KEY_MAX) {
|
|
201
|
+
progressCallback(index, keyValues.length);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
await fetchResult(
|
|
205
|
+
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
|
|
206
|
+
{
|
|
207
|
+
method: "PUT",
|
|
208
|
+
body: JSON.stringify(keyValues.slice(index, index + BATCH_KEY_MAX)),
|
|
209
|
+
headers: { "Content-Type": "application/json" },
|
|
210
|
+
}
|
|
211
|
+
);
|
|
212
|
+
}
|
|
213
|
+
if (progressCallback && keyValues.length > BATCH_KEY_MAX) {
|
|
214
|
+
progressCallback(keyValues.length, keyValues.length);
|
|
215
|
+
}
|
|
216
|
+
}
|
|
217
|
+
|
|
218
|
+
export async function deleteKVBulkKeyValue(
|
|
219
|
+
accountId: string,
|
|
220
|
+
namespaceId: string,
|
|
221
|
+
keys: string[],
|
|
222
|
+
progressCallback: (index: number, total: number) => void
|
|
223
|
+
) {
|
|
224
|
+
for (let index = 0; index < keys.length; index += BATCH_KEY_MAX) {
|
|
225
|
+
if (progressCallback && keys.length > BATCH_KEY_MAX) {
|
|
226
|
+
progressCallback(index, keys.length);
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
await fetchResult(
|
|
230
|
+
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
|
|
231
|
+
{
|
|
232
|
+
method: "DELETE",
|
|
233
|
+
body: JSON.stringify(keys.slice(index, index + BATCH_KEY_MAX)),
|
|
234
|
+
headers: { "Content-Type": "application/json" },
|
|
235
|
+
}
|
|
236
|
+
);
|
|
237
|
+
}
|
|
238
|
+
if (progressCallback && keys.length > BATCH_KEY_MAX) {
|
|
239
|
+
progressCallback(keys.length, keys.length);
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
export function getKVNamespaceId(
|
|
244
|
+
{ preview, binding, "namespace-id": namespaceId }: KvArgs,
|
|
245
|
+
config: Config
|
|
246
|
+
): string {
|
|
247
|
+
// nice
|
|
248
|
+
if (namespaceId) {
|
|
249
|
+
return namespaceId;
|
|
250
|
+
}
|
|
251
|
+
|
|
252
|
+
// begin pre-flight checks
|
|
253
|
+
|
|
254
|
+
// `--binding` is only valid if there's a wrangler configuration.
|
|
255
|
+
if (binding && !config) {
|
|
256
|
+
throw new Error("--binding specified, but no config file was found.");
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
// there's no config. abort here
|
|
260
|
+
if (!config) {
|
|
261
|
+
throw new Error(
|
|
262
|
+
"Failed to find a config file.\n" +
|
|
263
|
+
"Either use --namespace-id to upload directly or create a configuration file with a binding."
|
|
264
|
+
);
|
|
265
|
+
}
|
|
266
|
+
|
|
267
|
+
// there's no KV namespaces
|
|
268
|
+
if (!config.kv_namespaces || config.kv_namespaces.length === 0) {
|
|
269
|
+
throw new Error(
|
|
270
|
+
"No KV Namespaces configured! Either use --namespace-id to upload directly or add a KV namespace to your wrangler config file."
|
|
271
|
+
);
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const namespace = config.kv_namespaces.find((ns) => ns.binding === binding);
|
|
275
|
+
|
|
276
|
+
// we couldn't find a namespace with that binding
|
|
277
|
+
if (!namespace) {
|
|
278
|
+
throw new Error(
|
|
279
|
+
`A namespace with binding name "${binding}" was not found in the configured "kv_namespaces".`
|
|
280
|
+
);
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
// end pre-flight checks
|
|
284
|
+
|
|
285
|
+
// we're in preview mode, `--preview true` or `--preview` was passed
|
|
286
|
+
if (preview && namespace.preview_id) {
|
|
287
|
+
namespaceId = namespace.preview_id;
|
|
288
|
+
// We don't want to execute code below if preview is set to true, so we just return. Otherwise we will get errors!
|
|
289
|
+
return namespaceId;
|
|
290
|
+
} else if (preview) {
|
|
291
|
+
throw new Error(
|
|
292
|
+
`No preview ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
|
|
293
|
+
);
|
|
294
|
+
}
|
|
295
|
+
|
|
296
|
+
// either `--preview false`, or preview wasn't passed
|
|
297
|
+
// TODO: should we care? or should we just treat false and undefined the same
|
|
298
|
+
const previewIsDefined = typeof preview !== "undefined";
|
|
299
|
+
|
|
300
|
+
// --preview false was passed
|
|
301
|
+
if (previewIsDefined && namespace.id) {
|
|
302
|
+
namespaceId = namespace.id;
|
|
303
|
+
// We don't want to execute code below if preview is set to true, so we just return. Otherwise we can get error!
|
|
304
|
+
return namespaceId;
|
|
305
|
+
} else if (previewIsDefined) {
|
|
306
|
+
throw new Error(
|
|
307
|
+
`No namespace ID found for ${binding}. Add one to your wrangler config file to use a separate namespace for previewing your worker.`
|
|
308
|
+
);
|
|
309
|
+
}
|
|
310
|
+
|
|
311
|
+
// `--preview` wasn't passed
|
|
312
|
+
const bindingHasOnlyOneId =
|
|
313
|
+
(namespace.id && !namespace.preview_id) ||
|
|
314
|
+
(!namespace.id && namespace.preview_id);
|
|
315
|
+
if (bindingHasOnlyOneId) {
|
|
316
|
+
namespaceId = namespace.id || namespace.preview_id;
|
|
317
|
+
} else {
|
|
318
|
+
throw new Error(
|
|
319
|
+
`${binding} has both a namespace ID and a preview ID. Specify "--preview" or "--preview false" to avoid writing data to the wrong namespace.`
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
// shouldn't happen. we should be able to prove this with strong typing.
|
|
324
|
+
// TODO: when we add strongly typed commands, rewrite these checks so they're exhaustive
|
|
325
|
+
if (!namespaceId) {
|
|
326
|
+
throw Error(
|
|
327
|
+
"Something went wrong trying to determine which namespace to upload to.\n" +
|
|
328
|
+
"Please create a github issue with the command you just ran along with your wrangler configuration."
|
|
329
|
+
);
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
return namespaceId;
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
/**
|
|
336
|
+
* KV namespace binding names must be valid JS identifiers.
|
|
337
|
+
*/
|
|
338
|
+
export function isValidKVNamespaceBinding(
|
|
339
|
+
binding: string | undefined
|
|
340
|
+
): binding is string {
|
|
341
|
+
return (
|
|
342
|
+
typeof binding === "string" && /^[a-zA-Z_][a-zA-Z0-9_]*$/.test(binding)
|
|
343
|
+
);
|
|
344
|
+
}
|
package/src/logger.ts
ADDED
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { format } from "node:util";
|
|
2
|
+
import { formatMessagesSync } from "esbuild";
|
|
3
|
+
|
|
4
|
+
const LOGGER_LEVELS = {
|
|
5
|
+
error: 0,
|
|
6
|
+
warn: 1,
|
|
7
|
+
log: 2,
|
|
8
|
+
debug: 3,
|
|
9
|
+
} as const;
|
|
10
|
+
|
|
11
|
+
type LoggerLevel = keyof typeof LOGGER_LEVELS;
|
|
12
|
+
|
|
13
|
+
/** A map from LOGGER_LEVEL to the error `kind` needed by `formatMessagesSync()`. */
|
|
14
|
+
const LOGGER_LEVEL_FORMAT_TYPE_MAP = {
|
|
15
|
+
error: "error",
|
|
16
|
+
warn: "warning",
|
|
17
|
+
log: undefined,
|
|
18
|
+
debug: undefined,
|
|
19
|
+
} as const;
|
|
20
|
+
|
|
21
|
+
class Logger {
|
|
22
|
+
constructor(public loggerLevel: LoggerLevel = "log") {}
|
|
23
|
+
|
|
24
|
+
columns = process.stdout.columns;
|
|
25
|
+
|
|
26
|
+
debug = (...args: unknown[]) => this.doLog("debug", args);
|
|
27
|
+
log = (...args: unknown[]) => this.doLog("log", args);
|
|
28
|
+
warn = (...args: unknown[]) => this.doLog("warn", args);
|
|
29
|
+
error = (...args: unknown[]) => this.doLog("error", args);
|
|
30
|
+
|
|
31
|
+
private doLog(messageLevel: LoggerLevel, args: unknown[]) {
|
|
32
|
+
if (LOGGER_LEVELS[this.loggerLevel] >= LOGGER_LEVELS[messageLevel]) {
|
|
33
|
+
console[messageLevel](this.formatMessage(messageLevel, format(...args)));
|
|
34
|
+
}
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
private formatMessage(level: LoggerLevel, message: string): string {
|
|
38
|
+
const kind = LOGGER_LEVEL_FORMAT_TYPE_MAP[level];
|
|
39
|
+
if (kind) {
|
|
40
|
+
// Format the message using the esbuild formatter.
|
|
41
|
+
// The first line of the message is the main `text`,
|
|
42
|
+
// subsequent lines are put into the `notes`.
|
|
43
|
+
const [firstLine, ...otherLines] = message.split("\n");
|
|
44
|
+
const notes =
|
|
45
|
+
otherLines.length > 0
|
|
46
|
+
? otherLines.map((text) => ({ text }))
|
|
47
|
+
: undefined;
|
|
48
|
+
return formatMessagesSync([{ text: firstLine, notes }], {
|
|
49
|
+
color: true,
|
|
50
|
+
kind,
|
|
51
|
+
terminalWidth: this.columns,
|
|
52
|
+
})[0];
|
|
53
|
+
} else {
|
|
54
|
+
return message;
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
}
|
|
58
|
+
|
|
59
|
+
/**
|
|
60
|
+
* A drop-in replacement for `console` for outputting logging messages.
|
|
61
|
+
*
|
|
62
|
+
* Errors and Warnings will get additional formatting to highlight them to the user.
|
|
63
|
+
* You can also set a `logger.loggerLevel` value to one of "debug", "log", "warn" or "error",
|
|
64
|
+
* to filter out logging messages.
|
|
65
|
+
*/
|
|
66
|
+
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
|
+
};
|
|
@@ -0,0 +1,41 @@
|
|
|
1
|
+
import { Log, LogLevel, Miniflare } from "miniflare";
|
|
2
|
+
import yargs from "yargs";
|
|
3
|
+
import { hideBin } from "yargs/helpers";
|
|
4
|
+
import { enumKeys } from "./enum-keys";
|
|
5
|
+
import { getRequestContextCheckOptions } from "./request-context";
|
|
6
|
+
|
|
7
|
+
async function main() {
|
|
8
|
+
const args = await yargs(hideBin(process.argv))
|
|
9
|
+
.help(false)
|
|
10
|
+
.version(false)
|
|
11
|
+
.option("log", {
|
|
12
|
+
choices: enumKeys(LogLevel),
|
|
13
|
+
}).argv;
|
|
14
|
+
|
|
15
|
+
const logLevel = LogLevel[args.log ?? "INFO"];
|
|
16
|
+
const requestContextCheckOptions = await getRequestContextCheckOptions();
|
|
17
|
+
const config = {
|
|
18
|
+
...JSON.parse((args._[0] as string) ?? "{}"),
|
|
19
|
+
...requestContextCheckOptions,
|
|
20
|
+
log: new Log(logLevel),
|
|
21
|
+
};
|
|
22
|
+
|
|
23
|
+
if (logLevel > LogLevel.INFO) {
|
|
24
|
+
console.log("OPTIONS:\n", JSON.stringify(config, null, 2));
|
|
25
|
+
}
|
|
26
|
+
|
|
27
|
+
const mf = new Miniflare(config);
|
|
28
|
+
|
|
29
|
+
try {
|
|
30
|
+
// Start Miniflare development server
|
|
31
|
+
await mf.startServer();
|
|
32
|
+
await mf.startScheduler();
|
|
33
|
+
} catch (e) {
|
|
34
|
+
mf.log.error(e as Error);
|
|
35
|
+
process.exitCode = 1;
|
|
36
|
+
// Unmount any mounted workers
|
|
37
|
+
await mf.dispose();
|
|
38
|
+
}
|
|
39
|
+
}
|
|
40
|
+
|
|
41
|
+
await main();
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import type { MiniflareOptions } from "miniflare";
|
|
2
|
+
|
|
3
|
+
/**
|
|
4
|
+
* Certain runtime APIs are only available to workers during the "request context",
|
|
5
|
+
* which is any code that returns after receiving a request and before returning
|
|
6
|
+
* a response.
|
|
7
|
+
*
|
|
8
|
+
* Miniflare emulates this behavior by using an [`AsyncLocalStorage`](https://nodejs.org/api/async_context.html#class-asynclocalstorage) and
|
|
9
|
+
* [checking at runtime](https://github.com/cloudflare/miniflare/blob/master/packages/shared/src/context.ts#L21-L36)
|
|
10
|
+
* to see if you're using those APIs during the request context.
|
|
11
|
+
*
|
|
12
|
+
* In certain environments `AsyncLocalStorage` is unavailable, such as in a
|
|
13
|
+
* [webcontainer](https://github.com/stackblitz/webcontainer-core).
|
|
14
|
+
* This function figures out if we're able to run those "request context" checks
|
|
15
|
+
* and returns [a set of options](https://miniflare.dev/core/standards#global-functionality-limits)
|
|
16
|
+
* that indicate to miniflare whether to run the checks or not.
|
|
17
|
+
*/
|
|
18
|
+
export const getRequestContextCheckOptions = async (): Promise<
|
|
19
|
+
Pick<MiniflareOptions, "globalAsyncIO" | "globalTimers" | "globalRandom">
|
|
20
|
+
> => {
|
|
21
|
+
// check that there's an implementation of AsyncLocalStorage
|
|
22
|
+
let hasAsyncLocalStorage = true;
|
|
23
|
+
try {
|
|
24
|
+
// ripped from the example here https://nodejs.org/api/async_context.html#class-asynclocalstorage
|
|
25
|
+
const { AsyncLocalStorage } = await import("node:async_hooks");
|
|
26
|
+
const storage = new AsyncLocalStorage<string>();
|
|
27
|
+
|
|
28
|
+
hasAsyncLocalStorage = storage.run("some-value", () => {
|
|
29
|
+
return storage.getStore() === "some-value";
|
|
30
|
+
});
|
|
31
|
+
} catch (e) {
|
|
32
|
+
hasAsyncLocalStorage = false;
|
|
33
|
+
}
|
|
34
|
+
|
|
35
|
+
return {
|
|
36
|
+
globalAsyncIO: hasAsyncLocalStorage,
|
|
37
|
+
globalRandom: hasAsyncLocalStorage,
|
|
38
|
+
globalTimers: hasAsyncLocalStorage,
|
|
39
|
+
};
|
|
40
|
+
};
|