hopwire 0.4.0 → 0.5.1

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.
@@ -0,0 +1,271 @@
1
+ import { printable } from '../output.js';
2
+ import { CREDENTIAL_HEADERS, SOURCE_WORDS, bodyLines, clock, formatDuration, hidden, paint, signatureMark, signatureSentence, statusTone, } from '../terminal.js';
3
+ import { recogniseWebhook } from '../webhook.js';
4
+ import { LineBuilder, bold, muted, rule } from './chrome.js';
5
+ import { hitLine, isSplit, listWindow, sectionsOf } from './state.js';
6
+ import { after, clip, fit, onBackground, sides, width as widthOf, wrapHard } from './text.js';
7
+ /**
8
+ * The Requests tab: the live list, one request opened, and the menu of what can be done with a request.
9
+ */
10
+ /** The background of the picked row. */
11
+ function highlight(look) {
12
+ const light = look.palette.mark === null;
13
+ return look.truecolor ? (light ? '48;2;226;232;240' : '48;2;30;41;59') : light ? '48;5;254' : '48;5;237';
14
+ }
15
+ /** The list: one row per exchange, the newest at the bottom, the picked one with a bar. */
16
+ export function listLines(state, ui, width, height) {
17
+ const { look } = ui;
18
+ const { shown, top, picked } = listWindow(state, height);
19
+ if (shown.length === 0) {
20
+ return emptyList(state, ui, width, height);
21
+ }
22
+ const lines = [];
23
+ for (let row = 0; row < height; row += 1) {
24
+ const index = top + row;
25
+ const entry = shown[index];
26
+ if (entry === undefined) {
27
+ lines.push({ text: '' });
28
+ continue;
29
+ }
30
+ const text = ui.row(entry, width - 2);
31
+ lines.push({
32
+ text: index === picked
33
+ ? onBackground(`${paint(look, '▌', look.palette.green)} ${fit(text, width - 2)}`, highlight(look))
34
+ : ` ${text}`,
35
+ hits: hitLine(`row:${entry.exchange.id}`, width),
36
+ });
37
+ }
38
+ return lines;
39
+ }
40
+ /** Before the first request, or when the filter keeps nothing: where requests go, in the middle of the list. */
41
+ function emptyList(state, ui, width, height) {
42
+ const { look } = ui;
43
+ const { info } = state;
44
+ const text = [];
45
+ if (state.traffic.entries.length > 0) {
46
+ text.push('No request matches the filter.', muted(look, 'esc clears it'));
47
+ }
48
+ else if (info.kind === 'watch') {
49
+ text.push("Waiting for requests in your teammate's log.");
50
+ }
51
+ else {
52
+ text.push('Waiting for requests.', '');
53
+ for (const service of info.services) {
54
+ const name = service.name === '' ? '' : `${service.name} `;
55
+ text.push(`${muted(look, `${name}Send them to`)} ${service.url ?? ''}`);
56
+ if (service.publicUrl !== null) {
57
+ text.push(`${muted(look, `${' '.repeat(name.length)}or to`)} ${paint(look, service.publicUrl, look.palette.cyan)}`);
58
+ }
59
+ }
60
+ }
61
+ const lines = Array.from({ length: height }, () => ({ text: '' }));
62
+ const first = Math.max(Math.floor((height - text.length) / 3), 0);
63
+ text.forEach((line, index) => {
64
+ if (first + index < height) {
65
+ lines[first + index] = {
66
+ text: `${' '.repeat(Math.max(Math.floor((width - widthOf(line)) / 2), 0))}${line}`,
67
+ };
68
+ }
69
+ });
70
+ return lines;
71
+ }
72
+ export const SECTION_TITLES = {
73
+ request: 'Request',
74
+ response: 'Response',
75
+ messages: 'Messages',
76
+ logs: 'Logs',
77
+ };
78
+ /** Headers and body of one side of an exchange as lines, nothing cut: long lines are wrapped. */
79
+ function sideLines(look, headers, bodyBase64, truncated, width) {
80
+ const lines = [];
81
+ const names = Math.min(Math.max(...headers.map(([name]) => name.length), 0), 28) + 2;
82
+ for (const [name, value] of headers) {
83
+ const shown = printable(CREDENTIAL_HEADERS.has(name.toLowerCase()) ? hidden(value) : value);
84
+ const label = fit(printable(name), names);
85
+ wrapHard(shown, Math.max(width - names, 16)).forEach((part, index) => {
86
+ lines.push(`${index === 0 ? muted(look, label) : ' '.repeat(names)}${part}`);
87
+ });
88
+ }
89
+ if (headers.length === 0) {
90
+ lines.push(muted(look, 'no headers'));
91
+ }
92
+ lines.push('');
93
+ const body = Buffer.from(bodyBase64, 'base64');
94
+ if (body.byteLength === 0) {
95
+ lines.push(muted(look, 'no body'));
96
+ return lines;
97
+ }
98
+ for (const line of bodyLines(body, truncated)) {
99
+ lines.push(...wrapHard(printable(line.replaceAll('\t', ' ')), width));
100
+ }
101
+ if (truncated) {
102
+ lines.push('', paint(look, 'The body was longer than the capture limit; only its start was recorded.', look.palette.warn));
103
+ }
104
+ return lines;
105
+ }
106
+ /** The lines of the section that is shown; kept until the section or the width changes. */
107
+ function contentLines(state, ui, entry, width) {
108
+ const { detail } = state;
109
+ if (detail === null) {
110
+ return [];
111
+ }
112
+ const { look } = ui;
113
+ const { exchange } = entry;
114
+ const loaded = detail.section === 'messages' ? detail.messages : detail.section === 'logs' ? detail.logs : [];
115
+ const key = `${detail.section}:${width}:${loaded === null ? 'loading' : loaded.length}`;
116
+ if (detail.content?.key === key) {
117
+ return detail.content.lines;
118
+ }
119
+ let lines;
120
+ switch (detail.section) {
121
+ case 'request':
122
+ lines = sideLines(look, exchange.request.headers, exchange.request.bodyBase64, exchange.request.bodyTruncated, width);
123
+ break;
124
+ case 'response':
125
+ lines = sideLines(look, exchange.response.headers, exchange.response.bodyBase64, exchange.response.bodyTruncated, width);
126
+ break;
127
+ default:
128
+ lines =
129
+ loaded === null
130
+ ? [muted(look, 'Loading…')]
131
+ : loaded.flatMap((line) => (line === '' ? [''] : wrapHard(line, width)));
132
+ }
133
+ detail.content = { key, lines };
134
+ return lines;
135
+ }
136
+ /** One request, opened: a title, its sections as tabs, and the section that is shown, scrolled. */
137
+ export function detailLines(state, ui, width, height) {
138
+ const { look } = ui;
139
+ const { palette } = look;
140
+ const { detail } = state;
141
+ const entry = detail === null ? null : state.traffic.find(detail.id);
142
+ if (detail === null || entry === null) {
143
+ return Array.from({ length: height }, () => ({ text: '' }));
144
+ }
145
+ const { exchange } = entry;
146
+ const { request, response } = exchange;
147
+ const title = new LineBuilder()
148
+ .add(`${paint(look, '‹', palette.green, true)} `, 'key:esc')
149
+ .add(`${bold(look, printable(request.method))} ${printable(request.path)}`)
150
+ .line();
151
+ const facts = [
152
+ paint(look, String(response.status), statusTone(palette, response.status)),
153
+ formatDuration(response.durationMs),
154
+ SOURCE_WORDS[exchange.source] ?? exchange.source,
155
+ clock(exchange.timestamp),
156
+ ].join(muted(look, ' · '));
157
+ const webhook = recogniseWebhook(exchange);
158
+ const check = ui.signature(entry);
159
+ const mark = check === null ? null : signatureMark(check, palette);
160
+ const second = webhook === null
161
+ ? muted(look, ` id ${printable(exchange.id)}`)
162
+ : ` ${printable(`${webhook.provider}${webhook.event === null ? '' : ` ${webhook.event}`}`)}${check === null || mark === null
163
+ ? ''
164
+ : ` ${paint(look, mark.symbol, mark.tone, true)} ${muted(look, signatureSentence(check))}`}`;
165
+ const sections = new LineBuilder().add(' ');
166
+ for (const section of sectionsOf(state, entry)) {
167
+ const label = SECTION_TITLES[section];
168
+ sections.add(section === detail.section ? `\u001b[4m${bold(look, label)}\u001b[0m` : muted(look, label), `section:${section}`);
169
+ sections.add(' ');
170
+ }
171
+ const room = Math.max(height - 4, 1);
172
+ const content = contentLines(state, ui, entry, Math.max(width - 2, 20));
173
+ detail.scroll = Math.min(Math.max(detail.scroll, 0), Math.max(content.length - room, 0));
174
+ const from = detail.scroll;
175
+ const position = content.length > room
176
+ ? muted(look, `lines ${from + 1} to ${Math.min(from + room, content.length)} of ${content.length} `)
177
+ : '';
178
+ const lines = [
179
+ { text: sides(title.text, `${facts} `, width), hits: title.hits },
180
+ { text: second },
181
+ { text: sides(sections.line().text, position, width), hits: sections.line().hits },
182
+ rule(look, width),
183
+ ];
184
+ for (let row = 0; row < room; row += 1) {
185
+ lines.push({ text: ` ${content[from + row] ?? ''}` });
186
+ }
187
+ return lines.slice(0, height);
188
+ }
189
+ /** The Requests tab: the list, the opened request, or both side by side in a wide window. */
190
+ export function requestsLines(state, ui, width, height) {
191
+ const lines = state.detail === null
192
+ ? listLines(state, ui, width, height)
193
+ : isSplit(width)
194
+ ? beside(state, ui, width, height)
195
+ : detailLines(state, ui, width, height);
196
+ return state.menu === null ? lines : withMenu(state, ui, lines, width, height);
197
+ }
198
+ /** The list on the left and the opened request on the right. */
199
+ function beside(state, ui, width, height) {
200
+ const leftWidth = Math.max(Math.floor(width * 0.4), 62);
201
+ const rightWidth = width - leftWidth - 1;
202
+ // The list keeps the opened request picked and in view
203
+ const list = listLines({ ...state, selected: state.detail?.id ?? state.selected }, ui, leftWidth, height);
204
+ const detail = detailLines(state, ui, rightWidth, height);
205
+ const bar = muted(ui.look, '│');
206
+ return list.map((left, row) => {
207
+ const right = detail[row] ?? { text: '' };
208
+ return {
209
+ text: `${fit(left.text, leftWidth)}${bar}${right.text}`,
210
+ hits: [
211
+ ...(left.hits ?? []).map((hit) => ({ ...hit, to: Math.min(hit.to, leftWidth) })),
212
+ ...(right.hits ?? []).map((hit) => ({
213
+ ...hit,
214
+ from: hit.from + leftWidth + 1,
215
+ to: hit.to + leftWidth + 1,
216
+ })),
217
+ ],
218
+ };
219
+ });
220
+ }
221
+ /** What can be done with a request, in words. Replay and the inspector need the inspector of this run. */
222
+ export function menuItems(state) {
223
+ const inspector = state.info.inspectorUrl !== null;
224
+ return [
225
+ ...(inspector ? [{ id: 'replay', label: 'Replay', key: 'r' }] : []),
226
+ { id: 'fix', label: 'Fix until it passes', key: 'f' },
227
+ { id: 'curl', label: 'Copy as curl', key: 'y' },
228
+ ...(inspector ? [{ id: 'inspector', label: 'Open in the inspector', key: 'i' }] : []),
229
+ ];
230
+ }
231
+ /** The actions menu drawn over the lines of the tab, next to the picked row. */
232
+ function withMenu(state, ui, lines, width, height) {
233
+ const { look } = ui;
234
+ const items = menuItems(state);
235
+ const entry = state.detail !== null ? state.traffic.find(state.detail.id) : null;
236
+ const { shown, top, picked } = listWindow(state, height);
237
+ const of = entry ?? shown[picked] ?? shown[shown.length - 1];
238
+ const title = of === undefined ? 'Actions' : clip(printable(`${of.exchange.request.method} ${of.exchange.request.path}`), 26);
239
+ const inner = Math.max(...items.map((item) => item.label.length + 6), widthOf(title) + 2, 28);
240
+ const boxWidth = inner + 2;
241
+ const boxHeight = items.length + 2;
242
+ const x = Math.max(Math.min(4, width - boxWidth), 0);
243
+ // Under the picked row when there is room, else above it
244
+ const anchor = state.detail !== null || picked < 0 ? 1 : picked - top + 1;
245
+ const y = Math.max(anchor + boxHeight <= height ? anchor : anchor - boxHeight - 1, 0);
246
+ const box = [
247
+ { text: muted(look, `┌ ${title} ${'─'.repeat(Math.max(inner - widthOf(title) - 2, 0))}┐`) },
248
+ ...items.map((item, index) => {
249
+ const current = index === state.menu;
250
+ const label = ` ${current ? paint(look, '▸', look.palette.green, true) : ' '} ${fit(item.label, inner - 6)} ${muted(look, item.key)} `;
251
+ return {
252
+ text: `${muted(look, '│')}${current ? onBackground(label, highlight(look)) : label}${muted(look, '│')}`,
253
+ hits: [{ from: 0, to: boxWidth, id: `menu:${index}` }],
254
+ };
255
+ }),
256
+ { text: muted(look, `└${'─'.repeat(inner)}┘`) },
257
+ ];
258
+ return lines.map((line, row) => {
259
+ const part = box[row - y];
260
+ if (part === undefined) {
261
+ return line;
262
+ }
263
+ return {
264
+ text: `${fit(clip(line.text, x, false), x)}${part.text}${after(line.text, x + boxWidth)}`,
265
+ hits: [
266
+ ...(part.hits ?? []).map((hit) => ({ ...hit, from: hit.from + x, to: hit.to + x })),
267
+ ...(line.hits ?? []),
268
+ ],
269
+ };
270
+ });
271
+ }
@@ -0,0 +1,91 @@
1
+ import { clip } from './text.js';
2
+ const ENTER = [
3
+ '\u001b[?1049h', // the alternate screen
4
+ '\u001b[?25l', // no cursor
5
+ '\u001b[?7l', // no wrapping: a line that is too long is cut, never pushed to the next one
6
+ '\u001b[?1000h', // mouse buttons and the wheel
7
+ '\u001b[?1006h', // as SGR reports, which have no limit on the column
8
+ '\u001b[2J',
9
+ ].join('');
10
+ const LEAVE = ['\u001b[?1006l', '\u001b[?1000l', '\u001b[?7h', '\u001b[?25h', '\u001b[?1049l'].join('');
11
+ export class Screen {
12
+ output;
13
+ resized;
14
+ active = false;
15
+ drawn = [];
16
+ hits = [];
17
+ onResize = () => {
18
+ this.drawn = [];
19
+ this.resized();
20
+ };
21
+ constructor(output,
22
+ /** Called when the window changed its size: the view draws a frame of the new size */
23
+ resized) {
24
+ this.output = output;
25
+ this.resized = resized;
26
+ }
27
+ get width() {
28
+ return Math.max(this.output.columns ?? 80, 20);
29
+ }
30
+ get height() {
31
+ return Math.max(this.output.rows ?? 24, 8);
32
+ }
33
+ get running() {
34
+ return this.active;
35
+ }
36
+ start() {
37
+ if (this.active) {
38
+ return;
39
+ }
40
+ this.active = true;
41
+ this.drawn = [];
42
+ this.output.write(ENTER);
43
+ this.output.on('resize', this.onResize);
44
+ }
45
+ /** Gives the terminal back as it was. Safe to call twice, and from an exit handler. */
46
+ stop() {
47
+ if (!this.active) {
48
+ return;
49
+ }
50
+ this.active = false;
51
+ this.output.off('resize', this.onResize);
52
+ this.output.write(LEAVE);
53
+ }
54
+ /** Draws a frame: one line per row of the window. Only rows that differ from what is on screen are written. */
55
+ draw(lines) {
56
+ if (!this.active) {
57
+ return;
58
+ }
59
+ const { width, height } = this;
60
+ let out = '';
61
+ const hits = [];
62
+ for (let row = 0; row < height; row += 1) {
63
+ const line = lines[row];
64
+ // Cut to the window, colours ended, the rest of the row erased
65
+ const text = `${clip(line?.text ?? '', width)}\u001b[0m\u001b[K`;
66
+ hits.push(line?.hits ?? []);
67
+ if (this.drawn[row] !== text) {
68
+ out += `\u001b[${row + 1};1H${text}`;
69
+ this.drawn[row] = text;
70
+ }
71
+ }
72
+ this.hits = hits;
73
+ if (out !== '') {
74
+ // Synchronised output: a terminal that knows it shows the frame at once
75
+ this.output.write(`\u001b[?2026h${out}\u001b[?2026l`);
76
+ }
77
+ }
78
+ /** What is at a cell, for a click; null where nothing is. */
79
+ hitAt(x, y) {
80
+ for (const hit of this.hits[y] ?? []) {
81
+ if (x >= hit.from && x < hit.to) {
82
+ return hit.id;
83
+ }
84
+ }
85
+ return null;
86
+ }
87
+ /** Sends a sequence the terminal acts on without showing it (the clipboard of the terminal). */
88
+ control(sequence) {
89
+ this.output.write(sequence);
90
+ }
91
+ }
@@ -0,0 +1,88 @@
1
+ import { recogniseWebhook } from '../webhook.js';
2
+ /** The tabs of the navigation, in the order of the bar. */
3
+ export const TABS = ['requests', 'share', 'tools', 'status', 'help'];
4
+ export const TAB_TITLES = {
5
+ requests: 'Requests',
6
+ share: 'Share',
7
+ tools: 'Tools',
8
+ status: 'Status',
9
+ help: 'Help',
10
+ };
11
+ /** The key of a tab: its number, and ? for the help. */
12
+ export const TAB_KEYS = { requests: '1', share: '2', tools: '3', status: '4', help: '?' };
13
+ /** A hit over a whole line. */
14
+ export function hitLine(id, width) {
15
+ return [{ from: 0, to: width, id }];
16
+ }
17
+ const haystacks = new WeakMap();
18
+ /** What the filter is matched against: method, path, status, source, service and the webhook's name. */
19
+ function haystack(entry) {
20
+ let text = haystacks.get(entry);
21
+ if (text === undefined) {
22
+ const { exchange } = entry;
23
+ const webhook = recogniseWebhook(exchange);
24
+ text = [
25
+ exchange.request.method,
26
+ exchange.request.path,
27
+ String(exchange.response.status),
28
+ exchange.source,
29
+ entry.label.trim(),
30
+ webhook?.provider ?? '',
31
+ webhook?.event ?? '',
32
+ ]
33
+ .join(' ')
34
+ .toLowerCase();
35
+ haystacks.set(entry, text);
36
+ }
37
+ return text;
38
+ }
39
+ /** The entries the list shows: all of them, or those the filter keeps. */
40
+ export function visible(state) {
41
+ const needle = state.filter.trim().toLowerCase();
42
+ if (needle === '' && !state.failedOnly) {
43
+ return state.traffic.entries;
44
+ }
45
+ return state.traffic.entries.filter((entry) => (!state.failedOnly || entry.exchange.response.status >= 400) &&
46
+ (needle === '' || haystack(entry).includes(needle)));
47
+ }
48
+ /** The exchange the keys act on: the picked one, else the newest that is not itself a replay. */
49
+ export function target(state) {
50
+ if (state.detail !== null) {
51
+ return state.traffic.find(state.detail.id);
52
+ }
53
+ const shown = visible(state);
54
+ if (state.selected !== null) {
55
+ return shown.find((entry) => entry.exchange.id === state.selected) ?? null;
56
+ }
57
+ for (let index = shown.length - 1; index >= 0; index -= 1) {
58
+ const entry = shown[index];
59
+ if (entry !== undefined && entry.exchange.source !== 'replay') {
60
+ return entry;
61
+ }
62
+ }
63
+ return shown[shown.length - 1] ?? null;
64
+ }
65
+ /** The window of the list: which row is first, which is picked, and how many newer rows are below it. */
66
+ export function listWindow(state, height) {
67
+ const shown = visible(state);
68
+ const last = Math.max(shown.length - height, 0);
69
+ const picked = state.selected === null ? -1 : shown.findIndex((entry) => entry.exchange.id === state.selected);
70
+ let top = state.top === null ? last : Math.min(Math.max(state.top, 0), last);
71
+ if (picked >= 0) {
72
+ top = picked < top ? picked : picked >= top + height ? picked - height + 1 : top;
73
+ }
74
+ return { shown, top, picked, below: Math.max(shown.length - (top + height), 0) };
75
+ }
76
+ /** The sections a request has: Messages for a WebSocket, Logs when a log file is followed. */
77
+ export function sectionsOf(state, entry) {
78
+ return [
79
+ 'request',
80
+ 'response',
81
+ ...(entry.exchange.response.status === 101 ? ['messages'] : []),
82
+ ...(state.facts.fact('Logs') !== null ? ['logs'] : []),
83
+ ];
84
+ }
85
+ /** Whether list and request stand side by side: only in a wide window. */
86
+ export function isSplit(width) {
87
+ return width >= 140;
88
+ }
@@ -0,0 +1,239 @@
1
+ import { DOCS_URL } from '../output.js';
2
+ import { clock, paint, wrap } from '../terminal.js';
3
+ import { bold, muted } from './chrome.js';
4
+ import { hitLine } from './state.js';
5
+ import { fit, onBackground } from './text.js';
6
+ /**
7
+ * The tabs beside Requests: Share (what to send to whom), Tools (what else Hopwire does with the traffic), Status
8
+ * (the facts of the tunnel and what happened) and Help (the keys).
9
+ */
10
+ function highlight(look) {
11
+ const light = look.palette.mark === null;
12
+ return look.truecolor ? (light ? '48;2;226;232;240' : '48;2;30;41;59') : light ? '48;5;254' : '48;5;237';
13
+ }
14
+ /** What a teammate, a webhook provider or the user's own browser gets. */
15
+ export function shareItems(state) {
16
+ const { info } = state;
17
+ const items = [];
18
+ for (const service of info.services) {
19
+ if (service.publicUrl !== null) {
20
+ items.push({
21
+ title: service.name === '' ? 'Public URL' : `Public URL of ${service.name}`,
22
+ copy: service.publicUrl,
23
+ note: 'Give it to a webhook provider or a client.',
24
+ });
25
+ }
26
+ }
27
+ if (info.kind === 'watch') {
28
+ if (info.peerKey !== null) {
29
+ items.push({
30
+ title: 'The key of this machine',
31
+ copy: info.peerKey,
32
+ note: 'For a teammate who lets in only chosen keys (--allow <pubkey>).',
33
+ });
34
+ }
35
+ }
36
+ else if (info.peerKey !== null) {
37
+ items.push({
38
+ title: 'Let a teammate call your service',
39
+ copy: `hopwire connect ${info.peerKey} --port 4141`,
40
+ note: 'They run it and send requests to http://127.0.0.1:4141.',
41
+ }, {
42
+ title: 'Let a teammate watch and replay this traffic',
43
+ copy: `hopwire watch ${info.logKey} --replay-target http://127.0.0.1:3000`,
44
+ note: 'They run it with the address of the service on their machine.',
45
+ });
46
+ }
47
+ if (info.inspectorUrl !== null) {
48
+ items.push({
49
+ title: 'Inspector',
50
+ copy: info.inspectorUrl,
51
+ note: 'Every request in your browser, to read, edit and replay. Keep the address to yourself.',
52
+ });
53
+ }
54
+ return items;
55
+ }
56
+ /** A list of things to copy, the picked one with a bar; under it what does not fit a list. */
57
+ function copyList(ui, items, cursor, hit, width, below) {
58
+ const { look } = ui;
59
+ const lines = [{ text: '' }];
60
+ items.forEach((item, index) => {
61
+ const current = index === cursor;
62
+ const command = `${current ? paint(look, '▌', look.palette.green) : ' '} ${fit(paint(look, item.copy, look.palette.cyan), width - 2)}`;
63
+ lines.push({ text: ` ${bold(look, item.title)}` });
64
+ lines.push({
65
+ text: current ? onBackground(command, highlight(look)) : command,
66
+ hits: hitLine(`${hit}:${index}`, width),
67
+ });
68
+ for (const part of wrap(item.note, Math.max(width - 4, 20))) {
69
+ lines.push({ text: ` ${muted(look, part)}` });
70
+ }
71
+ lines.push({ text: '' });
72
+ });
73
+ for (const text of below) {
74
+ lines.push({ text });
75
+ }
76
+ return lines;
77
+ }
78
+ export function shareLines(state, ui, width, height) {
79
+ const { look } = ui;
80
+ const { info } = state;
81
+ const below = [];
82
+ if (info.kind !== 'watch' && info.peerKey === null) {
83
+ for (const part of wrap('This tunnel is not shared with teammates. Start it with --share and their commands appear here.', Math.max(width - 4, 20))) {
84
+ below.push(` ${muted(look, part)}`);
85
+ }
86
+ }
87
+ for (const fact of state.facts.facts) {
88
+ if (fact.label === 'Notice') {
89
+ wrap(fact.value, Math.max(width - 4, 20)).forEach((part, index) => {
90
+ below.push(` ${index === 0 ? paint(look, '!', look.palette.warn, true) : ' '} ${muted(look, part)}`);
91
+ });
92
+ }
93
+ }
94
+ return copyList(ui, shareItems(state), state.cursor.share, 'share', width, below).slice(0, height);
95
+ }
96
+ /** Where a tool sends requests: the local service of the tunnel. */
97
+ function serviceOrigin(state) {
98
+ const { info } = state;
99
+ return (info.services[0]?.target ??
100
+ state.facts.fact('Forwarding')?.split(' -> ')[1] ??
101
+ info.replayTarget ??
102
+ 'http://127.0.0.1:3000');
103
+ }
104
+ /** What else Hopwire does with the recorded traffic, each with its command filled in for this tunnel. */
105
+ export function tools(state) {
106
+ const target = serviceOrigin(state);
107
+ const args = state.extraArgs;
108
+ return [
109
+ {
110
+ title: 'Fix a failed request',
111
+ what: 'Replays it after every file change until it passes',
112
+ command: `hopwire fix${args}`,
113
+ },
114
+ {
115
+ title: 'Snapshot',
116
+ what: 'Writes the recorded requests to a file',
117
+ command: `hopwire snapshot hooks.snapshot.json${args}`,
118
+ },
119
+ {
120
+ title: 'Verify',
121
+ what: 'Sends a snapshot to your service and compares the answers (CI)',
122
+ command: `hopwire verify hooks.snapshot.json --target ${target}`,
123
+ },
124
+ {
125
+ title: 'Chaos',
126
+ what: 'Delivers webhooks twice, out of order and badly signed',
127
+ command: `hopwire chaos hooks.snapshot.json --target ${target}`,
128
+ },
129
+ {
130
+ title: 'Coding agent',
131
+ what: 'Lets your coding agent read and replay this traffic',
132
+ command: 'claude mcp add hopwire -- hopwire mcp',
133
+ },
134
+ ];
135
+ }
136
+ export function toolsLines(state, ui, width, height) {
137
+ const { look } = ui;
138
+ const list = tools(state);
139
+ const lines = [{ text: '' }];
140
+ list.forEach((tool, index) => {
141
+ const current = index === state.cursor.tools;
142
+ const text = `${current ? paint(look, '▌', look.palette.green) : ' '} ${fit(current ? bold(look, tool.title) : tool.title, 24)}${muted(look, tool.what)}`;
143
+ lines.push({
144
+ text: current ? onBackground(fit(text, width), highlight(look)) : text,
145
+ hits: hitLine(`tools:${index}`, width),
146
+ });
147
+ });
148
+ const picked = list[state.cursor.tools];
149
+ if (picked !== undefined) {
150
+ lines.push({ text: '' }, {
151
+ text: ` ${paint(look, picked.command, look.palette.cyan)}`,
152
+ hits: hitLine(`tools:${state.cursor.tools}`, width),
153
+ }, { text: ` ${muted(look, 'enter copies the command; run it in a second terminal while this tunnel runs')}` });
154
+ }
155
+ return lines.slice(0, height);
156
+ }
157
+ /** The facts of the start, a line each, and what happened since, the newest first. */
158
+ export function statusContent(state, ui, width) {
159
+ const { look } = ui;
160
+ const { palette } = look;
161
+ const lines = [''];
162
+ const room = Math.max(width - 16, 20);
163
+ for (const fact of state.facts.facts) {
164
+ wrap(fact.value, room).forEach((part, index) => {
165
+ const label = index === 0
166
+ ? paint(look, fit(fact.label, 13), fact.warning ? palette.warn : null, true)
167
+ : ' '.repeat(13);
168
+ lines.push(` ${label} ${part}`);
169
+ });
170
+ }
171
+ // Who is in right now; the list of what happened below only has the comings and goings
172
+ if (state.info.kind !== 'watch' && state.info.peerKey !== null) {
173
+ const here = state.facts.teammatesNow;
174
+ lines.push('', ` ${bold(look, 'Connected now')}`);
175
+ if (here.length === 0) {
176
+ lines.push(` ${muted(look, 'No teammate is watching or connected.')}`);
177
+ }
178
+ for (const teammate of here) {
179
+ const what = [
180
+ ...(teammate.watching ? ['watching the log'] : []),
181
+ ...(teammate.connected ? ['connected to the service'] : []),
182
+ ].join(', ');
183
+ lines.push(` ${paint(look, '●', palette.cyan)} ${fit(teammate.key, 15)}${what}`);
184
+ }
185
+ }
186
+ lines.push('', ` ${bold(look, 'Since the start')}`);
187
+ if (state.facts.happenings.length === 0) {
188
+ lines.push(` ${muted(look, 'Nothing but requests.')}`);
189
+ }
190
+ for (const happening of [...state.facts.happenings].reverse()) {
191
+ const text = `${happening.label === '' ? '' : `${happening.label}: `}${happening.text}`;
192
+ wrap(text, Math.max(width - 12, 20)).forEach((part, index) => {
193
+ const time = index === 0 ? muted(look, clock(happening.at)) : ' '.repeat(8);
194
+ lines.push(` ${time} ${happening.problem ? paint(look, part, palette.err) : part}`);
195
+ });
196
+ }
197
+ return lines;
198
+ }
199
+ /** The keys of every view, the mouse, and where to read more. */
200
+ export function helpContent(ui) {
201
+ const { look } = ui;
202
+ const key = (keys, what) => ` ${fit(bold(look, keys), 16)}${what}`;
203
+ return [
204
+ '',
205
+ ` ${bold(look, 'Everywhere')}`,
206
+ key('1 2 3 4 ?', 'Requests, Share, Tools, Status, Help'),
207
+ key('← →', 'the tab before and after'),
208
+ key('q', 'stop the tunnel and quit'),
209
+ '',
210
+ ` ${bold(look, 'Requests')}`,
211
+ key('↑ ↓', 'pick a request; the list stands still while one is picked'),
212
+ key('enter', 'open the picked request'),
213
+ key('space', 'what can be done with it: replay, fix, copy as curl, inspector'),
214
+ key('/', 'filter by text: path, status, provider'),
215
+ key('e', 'failed requests only'),
216
+ key('end, esc', 'follow the newest request again'),
217
+ key('r y i f', 'replay, copy as curl, open in the inspector, fix'),
218
+ key('o c', 'open the inspector, copy the public URL'),
219
+ '',
220
+ ` ${bold(look, 'A request')}`,
221
+ key('tab', 'the next section: Request, Response, Messages, Logs'),
222
+ key('↑ ↓', 'scroll; page up and page down for more'),
223
+ key('esc', 'back to the list'),
224
+ '',
225
+ ` ${bold(look, 'Mouse')}`,
226
+ ` ${'Click a tab, a request, a key in the last line or an address. The wheel scrolls.'}`,
227
+ ` ${muted(look, 'To select text hold Option (iTerm, Apple Terminal) or Shift (most others) while you drag.')}`,
228
+ '',
229
+ ` ${bold(look, 'More')}`,
230
+ ` ${muted(look, 'Guides')} ${paint(look, DOCS_URL, look.palette.cyan)}`,
231
+ ` ${muted(look, 'Commands')} hopwire help`,
232
+ ` ${muted(look, 'Lines instead of this view')} --plain`,
233
+ ];
234
+ }
235
+ /** A long text of lines, scrolled. */
236
+ export function scrolled(content, scroll, height) {
237
+ const at = Math.min(Math.max(scroll, 0), Math.max(content.length - height, 0));
238
+ return { lines: content.slice(at, at + height).map((text) => ({ text })), scroll: at };
239
+ }