wrangler 0.0.0-e9a1820 → 0.0.0-e9ab55a
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/package.json +12 -5
- package/pages/functions/buildWorker.ts +62 -0
- package/pages/functions/filepath-routing.test.ts +39 -0
- package/pages/functions/filepath-routing.ts +228 -0
- package/pages/functions/identifiers.ts +78 -0
- package/pages/functions/routes.ts +158 -0
- package/pages/functions/template-worker.ts +136 -0
- package/src/__tests__/dev.test.tsx +67 -0
- package/src/__tests__/jest.setup.ts +5 -1
- package/src/__tests__/kv.test.ts +849 -45
- package/src/__tests__/mock-cfetch.ts +137 -29
- package/src/__tests__/publish.test.ts +102 -0
- package/src/api/form_data.ts +1 -1
- package/src/api/preview.ts +4 -4
- package/src/api/worker.ts +6 -6
- package/src/cfetch/index.ts +102 -0
- package/src/cfetch/internal.ts +69 -0
- package/src/config.ts +633 -118
- package/src/dev.tsx +114 -209
- package/src/index.tsx +265 -239
- package/src/inspect.ts +543 -0
- package/src/kv.tsx +49 -30
- package/src/pages.tsx +431 -242
- package/src/proxy.ts +275 -76
- package/src/publish.ts +79 -47
- package/src/sites.tsx +10 -7
- package/src/tail.tsx +5 -3
- package/src/user.tsx +22 -17
- package/wrangler-dist/cli.js +42319 -36190
- package/wrangler-dist/cli.js.map +3 -3
- package/src/api/inspect.ts +0 -430
- package/src/cfetch.ts +0 -72
package/src/inspect.ts
ADDED
|
@@ -0,0 +1,543 @@
|
|
|
1
|
+
import assert from "assert";
|
|
2
|
+
import type { MessageEvent } from "ws";
|
|
3
|
+
import WebSocket, { WebSocketServer } from "ws";
|
|
4
|
+
import type { IncomingMessage, Server, ServerResponse } from "http";
|
|
5
|
+
import { createServer } from "http";
|
|
6
|
+
import { useEffect, useRef, useState } from "react";
|
|
7
|
+
import { version } from "../package.json";
|
|
8
|
+
|
|
9
|
+
import type Protocol from "devtools-protocol";
|
|
10
|
+
|
|
11
|
+
/**
|
|
12
|
+
* `useInspector` is a hook for debugging Workers applications
|
|
13
|
+
* when using `wrangler dev`.
|
|
14
|
+
*
|
|
15
|
+
* When we start a session with `wrangler dev`, the Workers platform
|
|
16
|
+
* also exposes a debugging websocket that implements the DevTools
|
|
17
|
+
* Protocol. While we could just start up DevTools and connect to this
|
|
18
|
+
* URL, that URL changes every time we make a change to the
|
|
19
|
+
* worker, or when the session expires. Instead, we start up a proxy
|
|
20
|
+
* server locally that acts as a bridge between the remote DevTools
|
|
21
|
+
* server and the local DevTools instance. So whenever the URL changes,
|
|
22
|
+
* we can can silently connect to it and keep the local DevTools instance
|
|
23
|
+
* up to date. Further, we also intercept these messages and selectively
|
|
24
|
+
* log them directly to the terminal (namely, calls to `console.<x>`,
|
|
25
|
+
* and exceptions)
|
|
26
|
+
*/
|
|
27
|
+
|
|
28
|
+
/**
|
|
29
|
+
* TODO:
|
|
30
|
+
* - clear devtools whenever we save changes to the worker
|
|
31
|
+
* - clear devtools when we switch between local/remote modes
|
|
32
|
+
* - handle more methods from console
|
|
33
|
+
*/
|
|
34
|
+
|
|
35
|
+
interface InspectorProps {
|
|
36
|
+
/**
|
|
37
|
+
* The port that the local proxy server should listen on.
|
|
38
|
+
*/
|
|
39
|
+
port: number;
|
|
40
|
+
/**
|
|
41
|
+
* The websocket URL exposed by Workers that the inspector should connect to.
|
|
42
|
+
*/
|
|
43
|
+
inspectorUrl: undefined | string;
|
|
44
|
+
/**
|
|
45
|
+
* Whether console statements and exceptions should be logged to the terminal.
|
|
46
|
+
* (We don't log them in local mode because they're already getting
|
|
47
|
+
* logged to the terminal by nature of them actually running in node locally.)
|
|
48
|
+
*/
|
|
49
|
+
logToTerminal: boolean;
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export default function useInspector(props: InspectorProps) {
|
|
53
|
+
/** A unique ID for this session. */
|
|
54
|
+
const inspectorIdRef = useRef(randomId());
|
|
55
|
+
|
|
56
|
+
/** The websocket from the devtools instance. */
|
|
57
|
+
const [localWebSocket, setLocalWebSocket] = useState<WebSocket>();
|
|
58
|
+
/** The websocket from the edge */
|
|
59
|
+
const [remoteWebSocket, setRemoteWebSocket] = useState<WebSocket>();
|
|
60
|
+
|
|
61
|
+
/**
|
|
62
|
+
* The local proxy server that acts as the bridge between
|
|
63
|
+
* the remote websocket and the local DevTools instance.
|
|
64
|
+
*/
|
|
65
|
+
const serverRef = useRef<Server>();
|
|
66
|
+
if (serverRef.current === undefined) {
|
|
67
|
+
serverRef.current = createServer(
|
|
68
|
+
(req: IncomingMessage, res: ServerResponse) => {
|
|
69
|
+
switch (req.url) {
|
|
70
|
+
// We implement a couple of well known end points
|
|
71
|
+
// that are queried for metadata by chrome://inspect
|
|
72
|
+
case "/json/version":
|
|
73
|
+
res.setHeader("Content-Type", "application/json");
|
|
74
|
+
res.end(
|
|
75
|
+
JSON.stringify({
|
|
76
|
+
Browser: `wrangler/v${version}`,
|
|
77
|
+
// TODO: (someday): The DevTools protocol should match that of Edge Worker.
|
|
78
|
+
// This could be exposed by the preview API.
|
|
79
|
+
"Protocol-Version": "1.3",
|
|
80
|
+
})
|
|
81
|
+
);
|
|
82
|
+
return;
|
|
83
|
+
case "/json":
|
|
84
|
+
case "/json/list":
|
|
85
|
+
{
|
|
86
|
+
res.setHeader("Content-Type", "application/json");
|
|
87
|
+
const localHost = `localhost:${props.port}/ws`;
|
|
88
|
+
const devtoolsFrontendUrl = `devtools://devtools/bundled/js_app.html?experiments=true&v8only=true&ws=${localHost}`;
|
|
89
|
+
const devtoolsFrontendUrlCompat = `devtools://devtools/bundled/inspector.html?experiments=true&v8only=true&ws=${localHost}`;
|
|
90
|
+
res.end(
|
|
91
|
+
JSON.stringify([
|
|
92
|
+
{
|
|
93
|
+
id: inspectorIdRef.current,
|
|
94
|
+
type: "node",
|
|
95
|
+
description: "workers",
|
|
96
|
+
webSocketDebuggerUrl: `ws://${localHost}`,
|
|
97
|
+
devtoolsFrontendUrl,
|
|
98
|
+
devtoolsFrontendUrlCompat,
|
|
99
|
+
// Below are fields that are visible in the DevTools UI.
|
|
100
|
+
title: "Cloudflare Worker",
|
|
101
|
+
faviconUrl: "https://workers.cloudflare.com/favicon.ico",
|
|
102
|
+
url:
|
|
103
|
+
"https://" +
|
|
104
|
+
(remoteWebSocket
|
|
105
|
+
? new URL(remoteWebSocket.url).host
|
|
106
|
+
: "workers.dev"),
|
|
107
|
+
},
|
|
108
|
+
])
|
|
109
|
+
);
|
|
110
|
+
}
|
|
111
|
+
return;
|
|
112
|
+
default:
|
|
113
|
+
break;
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
);
|
|
117
|
+
}
|
|
118
|
+
const server = serverRef.current;
|
|
119
|
+
|
|
120
|
+
/**
|
|
121
|
+
* The websocket server that runs on top of the proxy server.
|
|
122
|
+
*/
|
|
123
|
+
const wsServerRef = useRef<WebSocketServer>();
|
|
124
|
+
if (wsServerRef.current === undefined) {
|
|
125
|
+
wsServerRef.current = new WebSocketServer({
|
|
126
|
+
server,
|
|
127
|
+
clientTracking: true,
|
|
128
|
+
});
|
|
129
|
+
}
|
|
130
|
+
const wsServer = wsServerRef.current;
|
|
131
|
+
|
|
132
|
+
wsServer.on("connection", (ws: WebSocket) => {
|
|
133
|
+
if (wsServer.clients.size > 1) {
|
|
134
|
+
/** We only want to have one active Devtools instance at a time. */
|
|
135
|
+
console.error(
|
|
136
|
+
"Tried to open a new devtools window when a previous one was already open."
|
|
137
|
+
);
|
|
138
|
+
ws.close(1013, "Too many clients; only one can be connected at a time");
|
|
139
|
+
} else {
|
|
140
|
+
// As promised, save the created websocket in a state hook
|
|
141
|
+
setLocalWebSocket(ws);
|
|
142
|
+
|
|
143
|
+
ws.addEventListener("close", () => {
|
|
144
|
+
// And and cleanup when devtools closes
|
|
145
|
+
setLocalWebSocket(undefined);
|
|
146
|
+
});
|
|
147
|
+
}
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
/**
|
|
151
|
+
* We start and stop the server in an effect to take advantage
|
|
152
|
+
* of the component lifecycle. Convenient.
|
|
153
|
+
*/
|
|
154
|
+
useEffect(() => {
|
|
155
|
+
server.listen(props.port);
|
|
156
|
+
return () => {
|
|
157
|
+
server.close();
|
|
158
|
+
// Also disconnect any open websockets/devtools connections
|
|
159
|
+
wsServer.clients.forEach((ws) => ws.close());
|
|
160
|
+
wsServer.close();
|
|
161
|
+
};
|
|
162
|
+
}, [props.port, server, wsServer]);
|
|
163
|
+
|
|
164
|
+
/**
|
|
165
|
+
* When connecting to the remote websocket, if we don't start either
|
|
166
|
+
* the devtools instance or make an actual request to the worker in time,
|
|
167
|
+
* then the connecting process can error out. When this happens, we
|
|
168
|
+
* want to simply retry the connection. We use a state hook to trigger retries
|
|
169
|
+
* of the effect that connects to the remote websocket.
|
|
170
|
+
*/
|
|
171
|
+
const [
|
|
172
|
+
retryRemoteWebSocketConnectionSigil,
|
|
173
|
+
setRetryRemoteWebSocketConnectionSigil,
|
|
174
|
+
] = useState<number>(0);
|
|
175
|
+
function retryRemoteWebSocketConnection() {
|
|
176
|
+
setRetryRemoteWebSocketConnectionSigil((x) => x + 1);
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/** A simple incrementing id to attach to messages we send to devtools */
|
|
180
|
+
const messageCounterRef = useRef(1);
|
|
181
|
+
|
|
182
|
+
// This effect tracks the connection to the remote websocket
|
|
183
|
+
// (stored in, no surprises here, `remoteWebSocket`)
|
|
184
|
+
useEffect(() => {
|
|
185
|
+
if (!props.inspectorUrl) {
|
|
186
|
+
return;
|
|
187
|
+
}
|
|
188
|
+
// The actual websocket instance
|
|
189
|
+
const ws = new WebSocket(props.inspectorUrl);
|
|
190
|
+
setRemoteWebSocket(ws);
|
|
191
|
+
|
|
192
|
+
/**
|
|
193
|
+
* A handle to the interval we run to keep the websocket alive
|
|
194
|
+
*/
|
|
195
|
+
let keepAliveInterval: NodeJS.Timer;
|
|
196
|
+
|
|
197
|
+
/**
|
|
198
|
+
* Test if the websocket is closed
|
|
199
|
+
*/
|
|
200
|
+
function isClosed() {
|
|
201
|
+
return (
|
|
202
|
+
ws.readyState === WebSocket.CLOSED ||
|
|
203
|
+
ws.readyState === WebSocket.CLOSING
|
|
204
|
+
);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
/**
|
|
208
|
+
* Send a message to the remote websocket
|
|
209
|
+
*/
|
|
210
|
+
function send(event: Record<string, unknown>): void {
|
|
211
|
+
if (!isClosed()) {
|
|
212
|
+
ws.send(JSON.stringify(event));
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
|
|
216
|
+
/**
|
|
217
|
+
* Closes the inspector.
|
|
218
|
+
*/
|
|
219
|
+
function close(): void {
|
|
220
|
+
if (!isClosed()) {
|
|
221
|
+
try {
|
|
222
|
+
ws.close();
|
|
223
|
+
} catch (err) {
|
|
224
|
+
// Closing before the websocket is ready will throw an error.
|
|
225
|
+
}
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* Since we have a handle on the remote websocket, we can tap
|
|
231
|
+
* into its events, and log any pertinent ones directly to
|
|
232
|
+
* the terminal (which means you have insight into your worker
|
|
233
|
+
* without having to open the devtools).
|
|
234
|
+
*/
|
|
235
|
+
if (props.logToTerminal) {
|
|
236
|
+
ws.addEventListener("message", (event: MessageEvent) => {
|
|
237
|
+
if (typeof event.data === "string") {
|
|
238
|
+
const evt = JSON.parse(event.data);
|
|
239
|
+
if (evt.method === "Runtime.exceptionThrown") {
|
|
240
|
+
const params = evt.params as Protocol.Runtime.ExceptionThrownEvent;
|
|
241
|
+
console.error(
|
|
242
|
+
"🚨", // cheesy, but it works
|
|
243
|
+
// maybe we could use color here too.
|
|
244
|
+
params.exceptionDetails.text,
|
|
245
|
+
params.exceptionDetails.exception?.description ?? ""
|
|
246
|
+
);
|
|
247
|
+
}
|
|
248
|
+
if (evt.method === "Runtime.consoleAPICalled") {
|
|
249
|
+
logConsoleMessage(
|
|
250
|
+
evt.params as Protocol.Runtime.ConsoleAPICalledEvent
|
|
251
|
+
);
|
|
252
|
+
}
|
|
253
|
+
} else {
|
|
254
|
+
// We should never get here, but who know is 2022...
|
|
255
|
+
console.error("unrecognised devtools event:", event);
|
|
256
|
+
}
|
|
257
|
+
});
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
ws.addEventListener("open", () => {
|
|
261
|
+
send({ method: "Runtime.enable", id: messageCounterRef.current });
|
|
262
|
+
// TODO: This doesn't actually work. Must fix.
|
|
263
|
+
send({ method: "Network.enable", id: messageCounterRef.current++ });
|
|
264
|
+
|
|
265
|
+
keepAliveInterval = setInterval(() => {
|
|
266
|
+
send({
|
|
267
|
+
method: "Runtime.getIsolateId",
|
|
268
|
+
id: messageCounterRef.current++,
|
|
269
|
+
});
|
|
270
|
+
}, 10_000);
|
|
271
|
+
});
|
|
272
|
+
|
|
273
|
+
ws.on("unexpected-response", () => {
|
|
274
|
+
console.log("waiting for connection...");
|
|
275
|
+
/**
|
|
276
|
+
* This usually means the worker is not "ready" yet
|
|
277
|
+
* so we'll just retry the connection process
|
|
278
|
+
*/
|
|
279
|
+
retryRemoteWebSocketConnection();
|
|
280
|
+
});
|
|
281
|
+
|
|
282
|
+
ws.addEventListener("close", () => {
|
|
283
|
+
clearInterval(keepAliveInterval);
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
return () => {
|
|
287
|
+
// clean up! Let's first stop the heartbeat interval
|
|
288
|
+
clearInterval(keepAliveInterval);
|
|
289
|
+
// Then we'll send a message to the devtools instance to
|
|
290
|
+
// tell it to clear the console.
|
|
291
|
+
wsServer.clients.forEach((client) => {
|
|
292
|
+
// We could've used `localSocket` here, but
|
|
293
|
+
// then we would have had to add it to the effect
|
|
294
|
+
// change detection array, which would have made a
|
|
295
|
+
// bunch of other stuff complicated. So we'll just
|
|
296
|
+
// cycle through all of the server's connected clients
|
|
297
|
+
// (in practice, there should only be one or zero) and send
|
|
298
|
+
// the Log.clear message.
|
|
299
|
+
client.send(
|
|
300
|
+
JSON.stringify({
|
|
301
|
+
// TODO: This doesn't actually work. Must fix.
|
|
302
|
+
method: "Log.clear",
|
|
303
|
+
// we can disable the next eslint warning since
|
|
304
|
+
// we're referencing a ref that stays alive
|
|
305
|
+
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
306
|
+
id: messageCounterRef.current++,
|
|
307
|
+
params: {},
|
|
308
|
+
})
|
|
309
|
+
);
|
|
310
|
+
});
|
|
311
|
+
// Finally, we'll close the websocket
|
|
312
|
+
close();
|
|
313
|
+
// And we'll clear `remoteWebsocket`
|
|
314
|
+
setRemoteWebSocket(undefined);
|
|
315
|
+
};
|
|
316
|
+
}, [
|
|
317
|
+
props.inspectorUrl,
|
|
318
|
+
retryRemoteWebSocketConnectionSigil,
|
|
319
|
+
props.logToTerminal,
|
|
320
|
+
wsServer,
|
|
321
|
+
]);
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* We want to make sure we don't lose any messages we receive from the
|
|
325
|
+
* remote websocket before devtools connects. So we use a ref to buffer
|
|
326
|
+
* messages, and flush them whenever devtools connects.
|
|
327
|
+
*/
|
|
328
|
+
const messageBufferRef = useRef<MessageEvent[]>([]);
|
|
329
|
+
|
|
330
|
+
// This effect tracks the state changes _between_ the local
|
|
331
|
+
// and remote websockets, and handles how messages flow between them.
|
|
332
|
+
useEffect(() => {
|
|
333
|
+
/**
|
|
334
|
+
* This event listener is used for buffering messages from
|
|
335
|
+
* the remote websocket, and flushing them
|
|
336
|
+
* when the local websocket connects.
|
|
337
|
+
*/
|
|
338
|
+
function bufferMessageFromRemoteSocket(event: MessageEvent) {
|
|
339
|
+
messageBufferRef.current.push(event);
|
|
340
|
+
// TODO: maybe we should have a max limit on this?
|
|
341
|
+
// if so, we should be careful when removing messages
|
|
342
|
+
// from the front, because they could be critical for
|
|
343
|
+
// devtools (like execution context creation, etc)
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
if (remoteWebSocket && !localWebSocket) {
|
|
347
|
+
// The local websocket hasn't connected yet, so we'll
|
|
348
|
+
// buffer messages until it does.
|
|
349
|
+
remoteWebSocket.addEventListener(
|
|
350
|
+
"message",
|
|
351
|
+
bufferMessageFromRemoteSocket
|
|
352
|
+
);
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
/** Send a message from the local websocket to the remote websocket */
|
|
356
|
+
function sendMessageToRemoteWebSocket(event: MessageEvent) {
|
|
357
|
+
try {
|
|
358
|
+
assert(
|
|
359
|
+
remoteWebSocket,
|
|
360
|
+
"Trying to send a message to an undefined `remoteWebSocket`"
|
|
361
|
+
);
|
|
362
|
+
remoteWebSocket.send(event.data);
|
|
363
|
+
} catch (e) {
|
|
364
|
+
if (e.message !== "WebSocket is not open: readyState 0 (CONNECTING)") {
|
|
365
|
+
/**
|
|
366
|
+
* ^ this just means we haven't opened a websocket yet
|
|
367
|
+
* usually happens until there's at least one request
|
|
368
|
+
* which is weird, because we may miss something that
|
|
369
|
+
* happens on the first request. Maybe we should buffer
|
|
370
|
+
* these messages too?
|
|
371
|
+
*/
|
|
372
|
+
console.error(e);
|
|
373
|
+
}
|
|
374
|
+
}
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
/** Send a message from the local websocket to the remote websocket */
|
|
378
|
+
function sendMessageToLocalWebSocket(event: MessageEvent) {
|
|
379
|
+
assert(
|
|
380
|
+
localWebSocket,
|
|
381
|
+
"Trying to send a message to an undefined `localWebSocket`"
|
|
382
|
+
);
|
|
383
|
+
localWebSocket.send(event.data);
|
|
384
|
+
}
|
|
385
|
+
|
|
386
|
+
if (localWebSocket && remoteWebSocket) {
|
|
387
|
+
// Both the remote and local websockets are connected, so let's
|
|
388
|
+
// start sending messages between them.
|
|
389
|
+
localWebSocket.addEventListener("message", sendMessageToRemoteWebSocket);
|
|
390
|
+
remoteWebSocket.addEventListener("message", sendMessageToLocalWebSocket);
|
|
391
|
+
|
|
392
|
+
// Also, let's flush any buffered messages
|
|
393
|
+
messageBufferRef.current.forEach(sendMessageToLocalWebSocket);
|
|
394
|
+
messageBufferRef.current = [];
|
|
395
|
+
}
|
|
396
|
+
|
|
397
|
+
return () => {
|
|
398
|
+
// Cleanup like good citizens
|
|
399
|
+
if (remoteWebSocket) {
|
|
400
|
+
remoteWebSocket.removeEventListener(
|
|
401
|
+
"message",
|
|
402
|
+
bufferMessageFromRemoteSocket
|
|
403
|
+
);
|
|
404
|
+
remoteWebSocket.removeEventListener(
|
|
405
|
+
"message",
|
|
406
|
+
sendMessageToLocalWebSocket
|
|
407
|
+
);
|
|
408
|
+
}
|
|
409
|
+
if (localWebSocket) {
|
|
410
|
+
localWebSocket.removeEventListener(
|
|
411
|
+
"message",
|
|
412
|
+
sendMessageToRemoteWebSocket
|
|
413
|
+
);
|
|
414
|
+
}
|
|
415
|
+
};
|
|
416
|
+
}, [localWebSocket, remoteWebSocket]);
|
|
417
|
+
}
|
|
418
|
+
|
|
419
|
+
// Credit: https://stackoverflow.com/a/2117523
|
|
420
|
+
function randomId(): string {
|
|
421
|
+
return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, function (c) {
|
|
422
|
+
const r = (Math.random() * 16) | 0,
|
|
423
|
+
v = c == "x" ? r : (r & 0x3) | 0x8;
|
|
424
|
+
return v.toString(16);
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
|
|
428
|
+
/**
|
|
429
|
+
* This function converts a message serialised as a devtools event
|
|
430
|
+
* into arguments suitable to be called by a console method, and
|
|
431
|
+
* then actually calls the method with those arguments. Effectively,
|
|
432
|
+
* we're just doing a little bit of the work of the devtools console,
|
|
433
|
+
* directly in the terminal.
|
|
434
|
+
*/
|
|
435
|
+
function logConsoleMessage(evt: Protocol.Runtime.ConsoleAPICalledEvent): void {
|
|
436
|
+
const args: string[] = [];
|
|
437
|
+
for (const ro of evt.args) {
|
|
438
|
+
switch (ro.type) {
|
|
439
|
+
case "string":
|
|
440
|
+
case "number":
|
|
441
|
+
case "boolean":
|
|
442
|
+
case "undefined":
|
|
443
|
+
case "symbol":
|
|
444
|
+
case "bigint":
|
|
445
|
+
args.push(ro.value);
|
|
446
|
+
break;
|
|
447
|
+
case "function":
|
|
448
|
+
args.push(`[Function: ${ro.description ?? "<no-description>"}]`);
|
|
449
|
+
break;
|
|
450
|
+
case "object":
|
|
451
|
+
if (!ro.preview) {
|
|
452
|
+
args.push(ro.description ?? "<no-description>");
|
|
453
|
+
} else {
|
|
454
|
+
args.push(ro.preview.description ?? "<no-description>");
|
|
455
|
+
|
|
456
|
+
switch (ro.preview.subtype) {
|
|
457
|
+
case "array":
|
|
458
|
+
args.push(
|
|
459
|
+
"[ " +
|
|
460
|
+
ro.preview.properties
|
|
461
|
+
.map(({ value }) => {
|
|
462
|
+
return value;
|
|
463
|
+
})
|
|
464
|
+
.join(", ") +
|
|
465
|
+
(ro.preview.overflow ? "..." : "") +
|
|
466
|
+
" ]"
|
|
467
|
+
);
|
|
468
|
+
|
|
469
|
+
break;
|
|
470
|
+
case "map":
|
|
471
|
+
args.push(
|
|
472
|
+
"{\n" +
|
|
473
|
+
// Maps always have entries
|
|
474
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
475
|
+
ro.preview
|
|
476
|
+
.entries!.map(({ key, value }) => {
|
|
477
|
+
return ` ${key?.description ?? "<unknown>"} => ${
|
|
478
|
+
value.description
|
|
479
|
+
}`;
|
|
480
|
+
})
|
|
481
|
+
.join(",\n") +
|
|
482
|
+
(ro.preview.overflow ? "\n ..." : "") +
|
|
483
|
+
"\n}"
|
|
484
|
+
);
|
|
485
|
+
|
|
486
|
+
break;
|
|
487
|
+
case "set":
|
|
488
|
+
args.push(
|
|
489
|
+
"{ " +
|
|
490
|
+
// Sets always have entries
|
|
491
|
+
// eslint-disable-next-line @typescript-eslint/no-non-null-assertion
|
|
492
|
+
ro.preview
|
|
493
|
+
.entries!.map(({ value }) => {
|
|
494
|
+
return `${value.description}`;
|
|
495
|
+
})
|
|
496
|
+
.join(", ") +
|
|
497
|
+
(ro.preview.overflow ? ", ..." : "") +
|
|
498
|
+
" }"
|
|
499
|
+
);
|
|
500
|
+
|
|
501
|
+
break;
|
|
502
|
+
case "null":
|
|
503
|
+
args.push("null");
|
|
504
|
+
break;
|
|
505
|
+
case "node":
|
|
506
|
+
case "regexp":
|
|
507
|
+
case "date":
|
|
508
|
+
case "weakmap":
|
|
509
|
+
case "weakset":
|
|
510
|
+
case "iterator":
|
|
511
|
+
case "generator":
|
|
512
|
+
case "error":
|
|
513
|
+
case "proxy":
|
|
514
|
+
case "promise":
|
|
515
|
+
case "typedarray":
|
|
516
|
+
case "arraybuffer":
|
|
517
|
+
case "dataview":
|
|
518
|
+
case "webassemblymemory":
|
|
519
|
+
case "wasmvalue":
|
|
520
|
+
break;
|
|
521
|
+
default:
|
|
522
|
+
// just a pojo
|
|
523
|
+
args.push(
|
|
524
|
+
"{\n" +
|
|
525
|
+
ro.preview.properties
|
|
526
|
+
.map(({ name, value }) => {
|
|
527
|
+
return ` ${name}: ${value}`;
|
|
528
|
+
})
|
|
529
|
+
.join(",\n") +
|
|
530
|
+
(ro.preview.overflow ? "\n ..." : "") +
|
|
531
|
+
"\n}"
|
|
532
|
+
);
|
|
533
|
+
}
|
|
534
|
+
}
|
|
535
|
+
break;
|
|
536
|
+
default:
|
|
537
|
+
args.push(ro.description || ro.unserializableValue || "🦋");
|
|
538
|
+
break;
|
|
539
|
+
}
|
|
540
|
+
}
|
|
541
|
+
|
|
542
|
+
console[evt.type](...args);
|
|
543
|
+
}
|
package/src/kv.tsx
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
|
+
import { URLSearchParams } from "node:url";
|
|
1
2
|
import type { Config } from "./config";
|
|
2
|
-
import
|
|
3
|
-
import qs from "node:querystring";
|
|
3
|
+
import { fetchListResult, fetchResult } from "./cfetch";
|
|
4
4
|
|
|
5
5
|
type KvArgs = {
|
|
6
6
|
binding?: string;
|
|
@@ -19,7 +19,7 @@ export async function createNamespace(
|
|
|
19
19
|
accountId: string,
|
|
20
20
|
title: string
|
|
21
21
|
): Promise<string> {
|
|
22
|
-
const response = await
|
|
22
|
+
const response = await fetchResult<{ id: string }>(
|
|
23
23
|
`/accounts/${accountId}/storage/kv/namespaces`,
|
|
24
24
|
{
|
|
25
25
|
method: "POST",
|
|
@@ -54,8 +54,15 @@ export async function listNamespaces(
|
|
|
54
54
|
let page = 1;
|
|
55
55
|
const results: KVNamespaceInfo[] = [];
|
|
56
56
|
while (results.length % pageSize === 0) {
|
|
57
|
-
const json = await
|
|
58
|
-
`/accounts/${accountId}/storage/kv/namespaces
|
|
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
|
+
})
|
|
59
66
|
);
|
|
60
67
|
page++;
|
|
61
68
|
results.push(...json);
|
|
@@ -66,19 +73,21 @@ export async function listNamespaces(
|
|
|
66
73
|
return results;
|
|
67
74
|
}
|
|
68
75
|
|
|
76
|
+
export interface NamespaceKeyInfo {
|
|
77
|
+
name: string;
|
|
78
|
+
expiration?: number;
|
|
79
|
+
metadata?: { [key: string]: unknown };
|
|
80
|
+
}
|
|
81
|
+
|
|
69
82
|
export async function listNamespaceKeys(
|
|
70
83
|
accountId: string,
|
|
71
84
|
namespaceId: string,
|
|
72
|
-
prefix
|
|
73
|
-
limit?: number
|
|
85
|
+
prefix = ""
|
|
74
86
|
) {
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
{
|
|
78
|
-
|
|
79
|
-
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys?${qs.stringify(
|
|
80
|
-
{ prefix, limit }
|
|
81
|
-
)}`
|
|
87
|
+
return await fetchListResult<NamespaceKeyInfo>(
|
|
88
|
+
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/keys`,
|
|
89
|
+
{},
|
|
90
|
+
new URLSearchParams({ prefix })
|
|
82
91
|
);
|
|
83
92
|
}
|
|
84
93
|
|
|
@@ -89,16 +98,20 @@ export async function putKeyValue(
|
|
|
89
98
|
value: string,
|
|
90
99
|
args?: { expiration?: number; expiration_ttl?: number }
|
|
91
100
|
) {
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
}
|
|
101
|
-
|
|
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
|
|
102
115
|
);
|
|
103
116
|
}
|
|
104
117
|
|
|
@@ -107,7 +120,7 @@ export async function putBulkKeyValue(
|
|
|
107
120
|
namespaceId: string,
|
|
108
121
|
keyvalueStr: string
|
|
109
122
|
) {
|
|
110
|
-
return await
|
|
123
|
+
return await fetchResult(
|
|
111
124
|
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
|
|
112
125
|
{
|
|
113
126
|
method: "PUT",
|
|
@@ -122,7 +135,7 @@ export async function deleteBulkKeyValue(
|
|
|
122
135
|
namespaceId: string,
|
|
123
136
|
keyStr: string
|
|
124
137
|
) {
|
|
125
|
-
return await
|
|
138
|
+
return await fetchResult(
|
|
126
139
|
`/accounts/${accountId}/storage/kv/namespaces/${namespaceId}/bulk`,
|
|
127
140
|
{
|
|
128
141
|
method: "DELETE",
|
|
@@ -186,7 +199,7 @@ export function getNamespaceId({
|
|
|
186
199
|
// there's no KV namespaces
|
|
187
200
|
if (!config.kv_namespaces || config.kv_namespaces.length === 0) {
|
|
188
201
|
throw new Error(
|
|
189
|
-
"No KV
|
|
202
|
+
"No KV Namespaces configured! Either use --namespace-id to upload directly or add a KV namespace to your wrangler config file."
|
|
190
203
|
);
|
|
191
204
|
}
|
|
192
205
|
|
|
@@ -194,7 +207,9 @@ export function getNamespaceId({
|
|
|
194
207
|
|
|
195
208
|
// we couldn't find a namespace with that binding
|
|
196
209
|
if (!namespace) {
|
|
197
|
-
throw new Error(
|
|
210
|
+
throw new Error(
|
|
211
|
+
`A namespace with binding name "${binding}" was not found in the configured "kv_namespaces".`
|
|
212
|
+
);
|
|
198
213
|
}
|
|
199
214
|
|
|
200
215
|
// end pre-flight checks
|
|
@@ -252,6 +267,10 @@ export function getNamespaceId({
|
|
|
252
267
|
/**
|
|
253
268
|
* KV namespace binding names must be valid JS identifiers.
|
|
254
269
|
*/
|
|
255
|
-
export function isValidNamespaceBinding(
|
|
256
|
-
|
|
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
|
+
);
|
|
257
276
|
}
|