hopwire 0.2.1 → 0.3.0
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/dist/bin.js +136 -6
- package/dist/cli.js +4 -12
- package/dist/commands/http.js +3 -2
- package/dist/commands/up.js +3 -2
- package/dist/commands/watch.js +3 -3
- package/dist/inspector/assets/{index-CIOfyIbK.js → index-CdyIIKdA.js} +1 -1
- package/dist/inspector/index.html +1 -1
- package/dist/live.js +226 -0
- package/dist/main.js +14 -3
- package/dist/output.js +19 -0
- package/dist/p2p.js +59 -1
- package/dist/serve.js +1 -0
- package/dist/shortcuts.js +217 -0
- package/dist/terminal.js +619 -0
- package/dist/version.js +12 -0
- package/dist/webhook.js +91 -0
- package/package.json +1 -1
package/dist/live.js
ADDED
|
@@ -0,0 +1,226 @@
|
|
|
1
|
+
import { PEER_LABEL } from './output.js';
|
|
2
|
+
/** Exchanges kept for the arrow keys, the details and the replay notes; older ones are let go. */
|
|
3
|
+
const KEPT = 500;
|
|
4
|
+
/** Durations the median and the slowest are taken from. */
|
|
5
|
+
const DURATIONS = 200;
|
|
6
|
+
/** The sparkline: one bar per 5 s over the last minute. */
|
|
7
|
+
const BUCKET_MS = 5_000;
|
|
8
|
+
const BUCKETS = 12;
|
|
9
|
+
/** How long the dot of the status line stays lit after a request. */
|
|
10
|
+
const PULSE_MS = 600;
|
|
11
|
+
/** Erases the line the cursor is on and puts the cursor at its start. */
|
|
12
|
+
const CLEAR_LINE = '\r\u001b[2K';
|
|
13
|
+
/**
|
|
14
|
+
* The bottom of the terminal while a tunnel runs: the rows of exchanges scroll above, and one status line stays under
|
|
15
|
+
* them, redrawn in place. Everything written to the terminal while it runs goes through `write`, which takes the status
|
|
16
|
+
* line away, writes, and draws it again, so no line is ever torn.
|
|
17
|
+
*/
|
|
18
|
+
export class LiveFeed {
|
|
19
|
+
screen;
|
|
20
|
+
output;
|
|
21
|
+
columns;
|
|
22
|
+
now;
|
|
23
|
+
kept = [];
|
|
24
|
+
durations = [];
|
|
25
|
+
arrivals = [];
|
|
26
|
+
requests = 0;
|
|
27
|
+
clientErrors = 0;
|
|
28
|
+
serverErrors = 0;
|
|
29
|
+
lastArrival = 0;
|
|
30
|
+
edge = null;
|
|
31
|
+
shared = false;
|
|
32
|
+
watcher = false;
|
|
33
|
+
teammates = new Map();
|
|
34
|
+
/** Index into `kept` of the picked row; null follows the newest */
|
|
35
|
+
picked = null;
|
|
36
|
+
footer = false;
|
|
37
|
+
timer = null;
|
|
38
|
+
constructor(screen, output, columns, now = Date.now) {
|
|
39
|
+
this.screen = screen;
|
|
40
|
+
this.output = output;
|
|
41
|
+
this.columns = columns;
|
|
42
|
+
this.now = now;
|
|
43
|
+
}
|
|
44
|
+
/** Lines above the status line; a text of several lines is written as one. */
|
|
45
|
+
write(text) {
|
|
46
|
+
this.observe(text);
|
|
47
|
+
this.output.write(`${this.footer ? CLEAR_LINE : ''}${text}\n${this.footerText()}`);
|
|
48
|
+
}
|
|
49
|
+
/** Something written around the status line by someone else (standard error): taken away before, drawn after. */
|
|
50
|
+
around(write) {
|
|
51
|
+
if (this.footer) {
|
|
52
|
+
this.output.write(CLEAR_LINE);
|
|
53
|
+
}
|
|
54
|
+
write();
|
|
55
|
+
if (this.footer) {
|
|
56
|
+
this.output.write(this.footerText());
|
|
57
|
+
}
|
|
58
|
+
}
|
|
59
|
+
/** One exchange: its row, and under a replay what changed against its original. */
|
|
60
|
+
exchange(exchange, label = '') {
|
|
61
|
+
this.count(exchange);
|
|
62
|
+
const original = exchange.source === 'replay' && exchange.replayOf !== undefined
|
|
63
|
+
? this.kept.find((entry) => entry.id === exchange.replayOf)
|
|
64
|
+
: undefined;
|
|
65
|
+
this.kept.push(exchange);
|
|
66
|
+
if (this.kept.length > KEPT) {
|
|
67
|
+
this.kept.shift();
|
|
68
|
+
this.picked = this.picked === null ? null : this.picked > 0 ? this.picked - 1 : null;
|
|
69
|
+
}
|
|
70
|
+
const row = this.screen.row(exchange, label);
|
|
71
|
+
this.write(original === undefined ? row : `${row}\n${this.screen.replayNote(original, exchange)}`);
|
|
72
|
+
}
|
|
73
|
+
/** The tunnel runs: the status line appears and keeps itself current. */
|
|
74
|
+
start() {
|
|
75
|
+
if (this.footer) {
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
this.footer = true;
|
|
79
|
+
this.output.write(this.footerText());
|
|
80
|
+
this.timer = setInterval(() => this.redraw(), 1000);
|
|
81
|
+
this.timer.unref();
|
|
82
|
+
}
|
|
83
|
+
/** Takes the status line away for good: the process is about to end. */
|
|
84
|
+
stop() {
|
|
85
|
+
if (this.timer !== null) {
|
|
86
|
+
clearInterval(this.timer);
|
|
87
|
+
this.timer = null;
|
|
88
|
+
}
|
|
89
|
+
if (this.footer) {
|
|
90
|
+
this.footer = false;
|
|
91
|
+
this.output.write(CLEAR_LINE);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
/** Moves the pick one row up (-1) or down (+1); down past the newest follows the newest again. */
|
|
95
|
+
move(step) {
|
|
96
|
+
if (this.kept.length === 0) {
|
|
97
|
+
return;
|
|
98
|
+
}
|
|
99
|
+
const at = this.picked ?? this.kept.length;
|
|
100
|
+
const next = at + step;
|
|
101
|
+
this.picked = next >= this.kept.length ? null : Math.max(next, 0);
|
|
102
|
+
this.redraw();
|
|
103
|
+
}
|
|
104
|
+
/** Follows the newest row again. */
|
|
105
|
+
unpick() {
|
|
106
|
+
this.picked = null;
|
|
107
|
+
this.redraw();
|
|
108
|
+
}
|
|
109
|
+
/** The picked row, else the newest one that is not itself a replay. */
|
|
110
|
+
target() {
|
|
111
|
+
if (this.picked !== null) {
|
|
112
|
+
return this.kept[this.picked] ?? null;
|
|
113
|
+
}
|
|
114
|
+
for (let index = this.kept.length - 1; index >= 0; index -= 1) {
|
|
115
|
+
const entry = this.kept[index];
|
|
116
|
+
if (entry !== undefined && entry.source !== 'replay') {
|
|
117
|
+
return entry;
|
|
118
|
+
}
|
|
119
|
+
}
|
|
120
|
+
return null;
|
|
121
|
+
}
|
|
122
|
+
/** Unfolds the target under the feed. */
|
|
123
|
+
details(inspector) {
|
|
124
|
+
const target = this.target();
|
|
125
|
+
if (target === null) {
|
|
126
|
+
return false;
|
|
127
|
+
}
|
|
128
|
+
this.write(this.screen.details(target, inspector));
|
|
129
|
+
return true;
|
|
130
|
+
}
|
|
131
|
+
/** What the status line shows now. */
|
|
132
|
+
stats() {
|
|
133
|
+
const now = this.now();
|
|
134
|
+
const sorted = [...this.durations].sort((a, b) => a - b);
|
|
135
|
+
const perBucket = Array.from({ length: BUCKETS }, () => 0);
|
|
136
|
+
for (const arrival of this.arrivals) {
|
|
137
|
+
const age = Math.floor((now - arrival) / BUCKET_MS);
|
|
138
|
+
if (age >= 0 && age < BUCKETS) {
|
|
139
|
+
perBucket[BUCKETS - 1 - age] = (perBucket[BUCKETS - 1 - age] ?? 0) + 1;
|
|
140
|
+
}
|
|
141
|
+
}
|
|
142
|
+
let teammates = 0;
|
|
143
|
+
for (const count of this.teammates.values()) {
|
|
144
|
+
teammates += count > 0 ? 1 : 0;
|
|
145
|
+
}
|
|
146
|
+
return {
|
|
147
|
+
requests: this.requests,
|
|
148
|
+
clientErrors: this.clientErrors,
|
|
149
|
+
serverErrors: this.serverErrors,
|
|
150
|
+
median: sorted.length === 0 ? null : (sorted[Math.floor((sorted.length - 1) / 2)] ?? null),
|
|
151
|
+
slowest: sorted.length === 0 ? null : (sorted[sorted.length - 1] ?? null),
|
|
152
|
+
perBucket,
|
|
153
|
+
pulse: now - this.lastArrival < PULSE_MS,
|
|
154
|
+
edge: this.edge,
|
|
155
|
+
teammates: this.shared ? teammates : null,
|
|
156
|
+
selected: this.picked === null ? null : (this.kept[this.picked] ?? null),
|
|
157
|
+
};
|
|
158
|
+
}
|
|
159
|
+
count(exchange) {
|
|
160
|
+
const now = this.now();
|
|
161
|
+
// A replay is no request that came in: it is not counted
|
|
162
|
+
if (exchange.source !== 'replay') {
|
|
163
|
+
this.requests += 1;
|
|
164
|
+
const { status } = exchange.response;
|
|
165
|
+
if (status >= 500) {
|
|
166
|
+
this.serverErrors += 1;
|
|
167
|
+
}
|
|
168
|
+
else if (status >= 400) {
|
|
169
|
+
this.clientErrors += 1;
|
|
170
|
+
}
|
|
171
|
+
this.durations.push(exchange.response.durationMs);
|
|
172
|
+
if (this.durations.length > DURATIONS) {
|
|
173
|
+
this.durations.shift();
|
|
174
|
+
}
|
|
175
|
+
this.arrivals.push(now);
|
|
176
|
+
while ((this.arrivals[0] ?? now) < now - BUCKET_MS * BUCKETS) {
|
|
177
|
+
this.arrivals.shift();
|
|
178
|
+
}
|
|
179
|
+
}
|
|
180
|
+
this.lastArrival = now;
|
|
181
|
+
}
|
|
182
|
+
/**
|
|
183
|
+
* The facts the status line needs, read from the plain lines of the command: a public URL, the edge's connection,
|
|
184
|
+
* sharing, and teammates coming and going. The lines say it already; nothing else has to report it twice.
|
|
185
|
+
*/
|
|
186
|
+
observe(text) {
|
|
187
|
+
for (const line of text.split('\n')) {
|
|
188
|
+
const plain = line.replace(ANSI, '');
|
|
189
|
+
if (plain.startsWith('Public URL ')) {
|
|
190
|
+
this.edge = true;
|
|
191
|
+
}
|
|
192
|
+
else if (plain.startsWith('Edge connection lost')) {
|
|
193
|
+
this.edge = false;
|
|
194
|
+
}
|
|
195
|
+
else if (plain.startsWith('Edge connected again')) {
|
|
196
|
+
this.edge = true;
|
|
197
|
+
}
|
|
198
|
+
else if (plain.startsWith('Watching ')) {
|
|
199
|
+
// hopwire watch: the teammate is the other side; the count is of the sharer's teammates
|
|
200
|
+
this.watcher = true;
|
|
201
|
+
this.shared = false;
|
|
202
|
+
}
|
|
203
|
+
else if (plain.startsWith('Peer key ') && !this.watcher) {
|
|
204
|
+
this.shared = true;
|
|
205
|
+
}
|
|
206
|
+
else if (plain.startsWith(PEER_LABEL)) {
|
|
207
|
+
const match = /^\S+ +(\S+) (is watching|stopped watching|connected|disconnected)/.exec(plain);
|
|
208
|
+
if (match !== null) {
|
|
209
|
+
const key = match[1] ?? '';
|
|
210
|
+
const here = match[2] === 'is watching' || match[2] === 'connected';
|
|
211
|
+
this.teammates.set(key, Math.max((this.teammates.get(key) ?? 0) + (here ? 1 : -1), 0));
|
|
212
|
+
}
|
|
213
|
+
}
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
footerText() {
|
|
217
|
+
return this.footer ? this.screen.statusLine(this.stats(), this.columns()) : '';
|
|
218
|
+
}
|
|
219
|
+
redraw() {
|
|
220
|
+
if (this.footer) {
|
|
221
|
+
this.output.write(`${CLEAR_LINE}${this.footerText()}`);
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
// eslint-disable-next-line no-control-regex
|
|
226
|
+
const ANSI = /\u001b\[[\d;?]*[A-Za-z]|\u001b\]8;;[^\u001b]*\u001b\\/g;
|
package/dist/main.js
CHANGED
|
@@ -1,5 +1,10 @@
|
|
|
1
1
|
import { HopwireError, UsageError, unexpectedFailure } from './errors.js';
|
|
2
|
+
import { DOCS_URL } from './output.js';
|
|
2
3
|
import { superviseProcess } from './supervisor.js';
|
|
4
|
+
/** The line after a wrong command line. */
|
|
5
|
+
const USAGE_HINT = 'Run "hopwire --help" for usage.';
|
|
6
|
+
/** The line a terminal shows under a failed start; plain output keeps the one sentence. */
|
|
7
|
+
export const TROUBLESHOOTING_HINT = `Troubleshooting: ${DOCS_URL}/troubleshooting`;
|
|
3
8
|
/**
|
|
4
9
|
* The whole run of the binary: the command under the signals of the process, and the exit code of a start that
|
|
5
10
|
* failed. A wrong command line exits with 2 and points to the help, every other failure with 1; each is one
|
|
@@ -14,7 +19,7 @@ export async function main(proc) {
|
|
|
14
19
|
// the rest
|
|
15
20
|
const { run } = await (proc.load ?? (() => import('./cli.js')))();
|
|
16
21
|
signal.throwIfAborted();
|
|
17
|
-
|
|
22
|
+
const running = await run(proc.argv, {
|
|
18
23
|
print: proc.print,
|
|
19
24
|
notice: proc.error,
|
|
20
25
|
env: proc.env,
|
|
@@ -23,17 +28,23 @@ export async function main(proc) {
|
|
|
23
28
|
promptLine: proc.promptLine,
|
|
24
29
|
openBrowser: proc.openBrowser,
|
|
25
30
|
input: proc.input,
|
|
31
|
+
exchange: proc.exchange,
|
|
26
32
|
});
|
|
33
|
+
if (running !== null && !signal.aborted) {
|
|
34
|
+
proc.started?.(running);
|
|
35
|
+
}
|
|
36
|
+
return running;
|
|
27
37
|
}, { on: proc.on, exit: proc.exit, error: proc.error });
|
|
28
38
|
}
|
|
29
39
|
catch (error) {
|
|
30
40
|
// UsageError is a HopwireError: it is asked for first
|
|
41
|
+
const fail = proc.failure ?? ((message, hint) => proc.error(hint === null ? message : `${message}\n${hint}`));
|
|
31
42
|
if (error instanceof UsageError) {
|
|
32
|
-
|
|
43
|
+
fail(error.message, USAGE_HINT);
|
|
33
44
|
proc.exit(2);
|
|
34
45
|
return;
|
|
35
46
|
}
|
|
36
|
-
|
|
47
|
+
fail(error instanceof HopwireError ? error.message : unexpectedFailure(error), proc.failure !== undefined && error instanceof HopwireError ? TROUBLESHOOTING_HINT : null);
|
|
37
48
|
proc.exit(1);
|
|
38
49
|
}
|
|
39
50
|
}
|
package/dist/output.js
CHANGED
|
@@ -84,6 +84,21 @@ export function logLines(logs, shared, cwd, services = 1) {
|
|
|
84
84
|
export function formatLogNotice(serviceName, line, services = 1) {
|
|
85
85
|
return `Logs ${services > 1 ? `${printable(serviceName)}/` : ''}${printable(line)}`;
|
|
86
86
|
}
|
|
87
|
+
/** The label of a line about a teammate coming or going. */
|
|
88
|
+
export const PEER_LABEL = 'Peer ';
|
|
89
|
+
/**
|
|
90
|
+
* One line for a teammate who starts or stops watching the log or reaching the service, by the start and end of the
|
|
91
|
+
* key of their machine (what "hopwire id" prints on their side).
|
|
92
|
+
*/
|
|
93
|
+
export function formatPeerEvent(event) {
|
|
94
|
+
const what = {
|
|
95
|
+
watching: 'is watching the log',
|
|
96
|
+
stopped_watching: 'stopped watching',
|
|
97
|
+
connected: 'connected (hopwire connect)',
|
|
98
|
+
disconnected: 'disconnected',
|
|
99
|
+
}[event.type];
|
|
100
|
+
return `${PEER_LABEL}${shortKey(event.key)} ${what}`;
|
|
101
|
+
}
|
|
87
102
|
/** One line for a change of the list of a tunnel shared with --team. */
|
|
88
103
|
export function formatTeamEvent(event, organisation) {
|
|
89
104
|
switch (event.type) {
|
|
@@ -120,6 +135,10 @@ export function formatExchange(exchange) {
|
|
|
120
135
|
const { request, response } = exchange;
|
|
121
136
|
return printable(`${request.method.padEnd(7)} ${request.path} ${response.status} ${response.durationMs}ms`);
|
|
122
137
|
}
|
|
138
|
+
/** The plain line of an exchange through `print`, or the terminal's row; `label` names the service of `hopwire up`. */
|
|
139
|
+
export function exchangeSink(print, exchange) {
|
|
140
|
+
return exchange ?? ((captured, label = '') => print(`${label}${formatExchange(captured)}`));
|
|
141
|
+
}
|
|
123
142
|
/** Control characters (C0, DEL, C1), invisible format characters and line separators as visible escapes. */
|
|
124
143
|
export function printable(text) {
|
|
125
144
|
return text.replace(/[\p{Cc}\p{Cf}\p{Zl}\p{Zp}]/gu, (character) => `\\u{${(character.codePointAt(0) ?? 0).toString(16).padStart(4, '0')}}`);
|
package/dist/p2p.js
CHANGED
|
@@ -36,6 +36,11 @@ const MAX_STREAMS = 64;
|
|
|
36
36
|
const MAX_STREAMS_PER_PEER = 16;
|
|
37
37
|
/** Keeps a relayed replication from being taken for idle by the edge while the log has nothing new. */
|
|
38
38
|
const RELAY_KEEPALIVE_MS = 30_000;
|
|
39
|
+
/**
|
|
40
|
+
* A teammate's `hopwire connect` opens and closes streams as its HTTP connections come and go; it counts as gone only
|
|
41
|
+
* when it held none for this long.
|
|
42
|
+
*/
|
|
43
|
+
const PEER_GONE_MS = 15_000;
|
|
39
44
|
/**
|
|
40
45
|
* `--share`: answers `hopwire connect` on the identity key (p2pConnect) and
|
|
41
46
|
* announces the traffic log for `hopwire watch` (logReplication). With an
|
|
@@ -95,6 +100,56 @@ export async function startSharing(options) {
|
|
|
95
100
|
/** Streams held, from their arrival to their close, refused ones not counted: in total and per public key */
|
|
96
101
|
let held = 0;
|
|
97
102
|
const heldPerPeer = new Map();
|
|
103
|
+
const onPeerEvent = options.onPeerEvent ?? (() => { });
|
|
104
|
+
/** Streams of `hopwire connect` per key, and the timers that say a key is gone */
|
|
105
|
+
const connected = new Map();
|
|
106
|
+
const goneTimers = new Map();
|
|
107
|
+
const connectedStream = (peer, socket) => {
|
|
108
|
+
const timer = goneTimers.get(peer);
|
|
109
|
+
if (timer !== undefined) {
|
|
110
|
+
clearTimeout(timer);
|
|
111
|
+
goneTimers.delete(peer);
|
|
112
|
+
}
|
|
113
|
+
const before = connected.get(peer) ?? 0;
|
|
114
|
+
connected.set(peer, before + 1);
|
|
115
|
+
if (before === 0 && timer === undefined) {
|
|
116
|
+
onPeerEvent({ type: 'connected', key: peer });
|
|
117
|
+
}
|
|
118
|
+
socket.once('close', () => {
|
|
119
|
+
const left = (connected.get(peer) ?? 1) - 1;
|
|
120
|
+
connected.set(peer, left);
|
|
121
|
+
if (left === 0) {
|
|
122
|
+
const gone = setTimeout(() => {
|
|
123
|
+
goneTimers.delete(peer);
|
|
124
|
+
if ((connected.get(peer) ?? 0) === 0) {
|
|
125
|
+
connected.delete(peer);
|
|
126
|
+
onPeerEvent({ type: 'disconnected', key: peer });
|
|
127
|
+
}
|
|
128
|
+
}, PEER_GONE_MS);
|
|
129
|
+
gone.unref();
|
|
130
|
+
goneTimers.set(peer, gone);
|
|
131
|
+
}
|
|
132
|
+
});
|
|
133
|
+
};
|
|
134
|
+
/** Replications per watching key */
|
|
135
|
+
const watching = new Map();
|
|
136
|
+
const watchedBy = (peer, connection) => {
|
|
137
|
+
const before = watching.get(peer) ?? 0;
|
|
138
|
+
watching.set(peer, before + 1);
|
|
139
|
+
if (before === 0) {
|
|
140
|
+
onPeerEvent({ type: 'watching', key: peer });
|
|
141
|
+
}
|
|
142
|
+
connection.once('close', () => {
|
|
143
|
+
const left = (watching.get(peer) ?? 1) - 1;
|
|
144
|
+
if (left === 0) {
|
|
145
|
+
watching.delete(peer);
|
|
146
|
+
onPeerEvent({ type: 'stopped_watching', key: peer });
|
|
147
|
+
}
|
|
148
|
+
else {
|
|
149
|
+
watching.set(peer, left);
|
|
150
|
+
}
|
|
151
|
+
});
|
|
152
|
+
};
|
|
98
153
|
const accept = async (stream) => {
|
|
99
154
|
const socket = toNodeDuplex(stream);
|
|
100
155
|
sockets.add(socket);
|
|
@@ -156,6 +211,7 @@ export async function startSharing(options) {
|
|
|
156
211
|
return;
|
|
157
212
|
}
|
|
158
213
|
socket.write(encodeP2pPrefaceReply({ ok: true }));
|
|
214
|
+
connectedStream(peer, socket);
|
|
159
215
|
// From here on the stream is an HTTP/1.1 connection of the in-process server
|
|
160
216
|
watchdogs.set(socket, watchHttpConnection(socket, timeouts));
|
|
161
217
|
servers.get(chosen.name)?.emit('connection', socket);
|
|
@@ -175,11 +231,12 @@ export async function startSharing(options) {
|
|
|
175
231
|
connection.destroy();
|
|
176
232
|
return;
|
|
177
233
|
}
|
|
234
|
+
const peer = connection.remotePublicKey.toString('hex');
|
|
178
235
|
if (admission === null) {
|
|
236
|
+
watchedBy(peer, connection);
|
|
179
237
|
log.replicate(connection);
|
|
180
238
|
return;
|
|
181
239
|
}
|
|
182
|
-
const peer = connection.remotePublicKey.toString('hex');
|
|
183
240
|
void admission.admits(peer).then((admitted) => {
|
|
184
241
|
if (connection.destroyed) {
|
|
185
242
|
return;
|
|
@@ -189,6 +246,7 @@ export async function startSharing(options) {
|
|
|
189
246
|
return;
|
|
190
247
|
}
|
|
191
248
|
track(peer, connection);
|
|
249
|
+
watchedBy(peer, connection);
|
|
192
250
|
log.replicate(connection);
|
|
193
251
|
});
|
|
194
252
|
};
|
package/dist/serve.js
CHANGED
|
@@ -156,6 +156,7 @@ export async function startServing(options) {
|
|
|
156
156
|
signal: options.signal,
|
|
157
157
|
relay: relaySetup,
|
|
158
158
|
onRelayEvent: options.onRelayEvent,
|
|
159
|
+
onPeerEvent: options.onPeerEvent,
|
|
159
160
|
});
|
|
160
161
|
supervisor.add('p2p', () => sharing.close());
|
|
161
162
|
peerKey = sharing.peerKey;
|
|
@@ -0,0 +1,217 @@
|
|
|
1
|
+
import { spawn } from 'node:child_process';
|
|
2
|
+
import { mainPublicUrl } from './output.js';
|
|
3
|
+
/** The keys act on tunnels that show exchanges: http, up and watch. Connect and mcp keep the terminal as it is. */
|
|
4
|
+
export function shortcutTarget(running) {
|
|
5
|
+
switch (running.kind) {
|
|
6
|
+
case 'http':
|
|
7
|
+
return { inspectorUrl: running.inspectorUrl, publicUrl: running.publicUrl };
|
|
8
|
+
case 'up': {
|
|
9
|
+
const published = running.services.find((service) => service.publicUrl !== null);
|
|
10
|
+
return {
|
|
11
|
+
inspectorUrl: running.inspectorUrl,
|
|
12
|
+
publicUrl: published === undefined ? null : mainPublicUrl(published.publicUrl, published.customDomains),
|
|
13
|
+
};
|
|
14
|
+
}
|
|
15
|
+
case 'watch':
|
|
16
|
+
return { inspectorUrl: running.inspectorUrl, publicUrl: null };
|
|
17
|
+
default:
|
|
18
|
+
return null;
|
|
19
|
+
}
|
|
20
|
+
}
|
|
21
|
+
const CTRL_C = '\u0003';
|
|
22
|
+
/** The keys in a chunk of terminal input: an arrow arrives as one escape sequence, Escape alone as ESC. */
|
|
23
|
+
export function keysOf(chunk) {
|
|
24
|
+
const keys = [];
|
|
25
|
+
for (let index = 0; index < chunk.length;) {
|
|
26
|
+
// eslint-disable-next-line no-control-regex -- an escape sequence starts with ESC
|
|
27
|
+
const sequence = /^\u001b\[[0-9;]*[A-Za-z~]/.exec(chunk.slice(index));
|
|
28
|
+
if (sequence !== null) {
|
|
29
|
+
keys.push(sequence[0]);
|
|
30
|
+
index += sequence[0].length;
|
|
31
|
+
}
|
|
32
|
+
else {
|
|
33
|
+
keys.push(chunk[index] ?? '');
|
|
34
|
+
index += 1;
|
|
35
|
+
}
|
|
36
|
+
}
|
|
37
|
+
return keys;
|
|
38
|
+
}
|
|
39
|
+
/** What ? lists. */
|
|
40
|
+
export const KEYS_HELP = '\u2191\u2193 pick a request, enter shows it, i opens it in the inspector, r replays it, o inspector, c copy the public URL, q quit';
|
|
41
|
+
/**
|
|
42
|
+
* Reads single keys while a tunnel runs: o opens the inspector, c copies the public URL, r replays the newest
|
|
43
|
+
* request, q and Ctrl+C stop. The terminal is put in raw mode for it, so Ctrl+C reaches here as a key and is turned
|
|
44
|
+
* into the same SIGINT as before. Returns what gives the terminal back.
|
|
45
|
+
*/
|
|
46
|
+
export function startShortcuts(input, actions) {
|
|
47
|
+
if (input.isTTY !== true || input.setRawMode === undefined) {
|
|
48
|
+
return () => { };
|
|
49
|
+
}
|
|
50
|
+
const setRawMode = input.setRawMode.bind(input);
|
|
51
|
+
const { target, say } = actions;
|
|
52
|
+
const onData = (chunk) => {
|
|
53
|
+
for (const key of keysOf(chunk)) {
|
|
54
|
+
switch (key) {
|
|
55
|
+
case '\u001b[A':
|
|
56
|
+
actions.move?.(-1);
|
|
57
|
+
break;
|
|
58
|
+
case '\u001b[B':
|
|
59
|
+
actions.move?.(1);
|
|
60
|
+
break;
|
|
61
|
+
case '\u001b':
|
|
62
|
+
actions.unpick?.();
|
|
63
|
+
break;
|
|
64
|
+
case '\r':
|
|
65
|
+
case '\n':
|
|
66
|
+
if (actions.details !== undefined && !actions.details()) {
|
|
67
|
+
say('No request has come in yet.', true);
|
|
68
|
+
}
|
|
69
|
+
break;
|
|
70
|
+
case 'i': {
|
|
71
|
+
const picked = actions.lastExchange();
|
|
72
|
+
if (target.inspectorUrl === null) {
|
|
73
|
+
say('There is no inspector in this run (--no-inspect).', true);
|
|
74
|
+
}
|
|
75
|
+
else if (picked === null) {
|
|
76
|
+
say('No request has come in yet.', true);
|
|
77
|
+
}
|
|
78
|
+
else {
|
|
79
|
+
// The inspector opens the exchange named after the #; the fragment never leaves the browser
|
|
80
|
+
const url = `${target.inspectorUrl}/#exchange=${encodeURIComponent(picked.id)}`;
|
|
81
|
+
if (!actions.openBrowser(url)) {
|
|
82
|
+
say(`Open ${url} in your browser.`);
|
|
83
|
+
}
|
|
84
|
+
}
|
|
85
|
+
break;
|
|
86
|
+
}
|
|
87
|
+
case CTRL_C:
|
|
88
|
+
case 'q':
|
|
89
|
+
actions.interrupt();
|
|
90
|
+
return;
|
|
91
|
+
case 'o':
|
|
92
|
+
if (target.inspectorUrl === null) {
|
|
93
|
+
say('There is no inspector in this run (--no-inspect).', true);
|
|
94
|
+
}
|
|
95
|
+
else if (actions.openBrowser(`${target.inspectorUrl}/`)) {
|
|
96
|
+
say('Opened the inspector in your browser.');
|
|
97
|
+
}
|
|
98
|
+
else {
|
|
99
|
+
say(`Open ${target.inspectorUrl}/ in your browser.`);
|
|
100
|
+
}
|
|
101
|
+
break;
|
|
102
|
+
case 'c':
|
|
103
|
+
if (target.publicUrl === null) {
|
|
104
|
+
say('This tunnel has no public URL.', true);
|
|
105
|
+
}
|
|
106
|
+
else {
|
|
107
|
+
const url = target.publicUrl;
|
|
108
|
+
void actions
|
|
109
|
+
.copy(url)
|
|
110
|
+
.then((how) => say(how === 'copied' ? `Copied ${url}` : `Sent ${url} to the clipboard of the terminal`));
|
|
111
|
+
}
|
|
112
|
+
break;
|
|
113
|
+
case 'r': {
|
|
114
|
+
const last = actions.lastExchange();
|
|
115
|
+
if (target.inspectorUrl === null) {
|
|
116
|
+
say('Replay needs the inspector; this run has none (--no-inspect).', true);
|
|
117
|
+
}
|
|
118
|
+
else if (last === null) {
|
|
119
|
+
say('No request has come in yet.', true);
|
|
120
|
+
}
|
|
121
|
+
else {
|
|
122
|
+
void actions.replay(target.inspectorUrl, last).then((problem) => {
|
|
123
|
+
if (problem !== null) {
|
|
124
|
+
say(`Replay failed: ${problem}`, true);
|
|
125
|
+
}
|
|
126
|
+
});
|
|
127
|
+
}
|
|
128
|
+
break;
|
|
129
|
+
}
|
|
130
|
+
case '?':
|
|
131
|
+
case 'h':
|
|
132
|
+
say(KEYS_HELP);
|
|
133
|
+
break;
|
|
134
|
+
default:
|
|
135
|
+
break;
|
|
136
|
+
}
|
|
137
|
+
}
|
|
138
|
+
};
|
|
139
|
+
setRawMode(true);
|
|
140
|
+
input.setEncoding('utf8');
|
|
141
|
+
input.resume();
|
|
142
|
+
input.on('data', onData);
|
|
143
|
+
const restore = () => {
|
|
144
|
+
input.off('data', onData);
|
|
145
|
+
setRawMode(false);
|
|
146
|
+
input.pause();
|
|
147
|
+
process.off('exit', restore);
|
|
148
|
+
};
|
|
149
|
+
process.once('exit', restore);
|
|
150
|
+
return restore;
|
|
151
|
+
}
|
|
152
|
+
/**
|
|
153
|
+
* Sends a request of the log again through the inspector of this run, as its Replay button does. The new exchange
|
|
154
|
+
* shows up as a row of its own; only a refusal comes back here, as the inspector's sentence.
|
|
155
|
+
*/
|
|
156
|
+
export async function replayThroughInspector(inspectorUrl, exchange) {
|
|
157
|
+
try {
|
|
158
|
+
const response = await fetch(`${inspectorUrl}/api/replay/${encodeURIComponent(exchange.id)}`, {
|
|
159
|
+
method: 'POST',
|
|
160
|
+
headers: { 'content-type': 'application/json' },
|
|
161
|
+
body: '{}',
|
|
162
|
+
});
|
|
163
|
+
if (response.ok) {
|
|
164
|
+
await response.arrayBuffer();
|
|
165
|
+
return null;
|
|
166
|
+
}
|
|
167
|
+
const answer = await response.json().catch(() => null);
|
|
168
|
+
return typeof answer === 'object' &&
|
|
169
|
+
answer !== null &&
|
|
170
|
+
'message' in answer &&
|
|
171
|
+
typeof answer.message === 'string'
|
|
172
|
+
? answer.message
|
|
173
|
+
: `the inspector answered ${response.status}`;
|
|
174
|
+
}
|
|
175
|
+
catch {
|
|
176
|
+
return 'the inspector did not answer';
|
|
177
|
+
}
|
|
178
|
+
}
|
|
179
|
+
/**
|
|
180
|
+
* Puts a text on the clipboard with the tool of the operating system (pbcopy, clip, wl-copy, xclip). Without one, or
|
|
181
|
+
* over SSH, it asks the terminal to do it (OSC 52), which most terminals do; the answer says which way it went.
|
|
182
|
+
*/
|
|
183
|
+
export async function copyToClipboard(text, writeTerminal, env = process.env, platform = process.platform) {
|
|
184
|
+
const command = clipboardCommand(env, platform);
|
|
185
|
+
if (command !== null && (await pipeTo(command, text))) {
|
|
186
|
+
return 'copied';
|
|
187
|
+
}
|
|
188
|
+
writeTerminal(`\u001b]52;c;${Buffer.from(text).toString('base64')}\u0007`);
|
|
189
|
+
return 'terminal';
|
|
190
|
+
}
|
|
191
|
+
function clipboardCommand(env, platform) {
|
|
192
|
+
if (platform === 'darwin') {
|
|
193
|
+
return env.SSH_CONNECTION ? null : ['pbcopy', []];
|
|
194
|
+
}
|
|
195
|
+
if (platform === 'win32') {
|
|
196
|
+
return ['clip', []];
|
|
197
|
+
}
|
|
198
|
+
if (env.WAYLAND_DISPLAY) {
|
|
199
|
+
return ['wl-copy', []];
|
|
200
|
+
}
|
|
201
|
+
return env.DISPLAY ? ['xclip', ['-selection', 'clipboard']] : null;
|
|
202
|
+
}
|
|
203
|
+
/** Runs a command with the text on its standard input; true when it exited with 0. Never through a shell. */
|
|
204
|
+
function pipeTo([command, args], text) {
|
|
205
|
+
return new Promise((resolve) => {
|
|
206
|
+
try {
|
|
207
|
+
const child = spawn(command, args, { stdio: ['pipe', 'ignore', 'ignore'] });
|
|
208
|
+
child.on('error', () => resolve(false));
|
|
209
|
+
child.on('close', (code) => resolve(code === 0));
|
|
210
|
+
child.stdin.on('error', () => { });
|
|
211
|
+
child.stdin.end(text);
|
|
212
|
+
}
|
|
213
|
+
catch {
|
|
214
|
+
resolve(false);
|
|
215
|
+
}
|
|
216
|
+
});
|
|
217
|
+
}
|