GraphQL, WebSocket, import, runner and CLI (M5, M6) plus packaging

- GraphQL editor with schema introspection, cached schema,
  autocomplete and explorer
- WebSocket: auth and subprotocols in the handshake, text/JSON/hex/file
  messages, saved messages, live log with filter, search and export,
  reconnect with backoff
- Import from Postman (collections and environments), Bruno, Insomnia,
  OpenAPI/Swagger and cURL; imported scripts are kept as docs, never run;
  credentials move to the gitignored secrets file
- Code snippets for cURL, fetch, Python, HTTPie, Go, PowerShell;
  Postman export
- Runner for folders and collections with JSON and JUnit reports
- knock CLI: send, run, import, auth login/debug/logout
- Large JSON responses parsed off the main thread
- PKGBUILDs, desktop entry with knock:// handler, CI workflow, README
This commit is contained in:
2026-11-27 17:13:06 +01:00
parent a469697af7
commit fc253126a7
51 changed files with 8437 additions and 24 deletions
+278 -2
View File
@@ -1,5 +1,281 @@
<script lang="ts">
import type { Tab } from "$lib/state/workspace.svelte";
import { invoke } from '@tauri-apps/api/core';
import { open as openDialog, save as saveDialog } from '@tauri-apps/plugin-dialog';
import { Resizable, ResizablePanel, ResizableHandle, TagInput, Switch, toast } from '@joshicodes/cock';
import CodeEditor from '$lib/editor/CodeEditor.svelte';
import JsonBody from '$lib/json/JsonBody.svelte';
import JsonViewer from '$lib/json/JsonViewer.svelte';
import KeyValueTable from '$lib/ui/KeyValueTable.svelte';
import AuthPanel from '$lib/views/auth/AuthPanel.svelte';
import AuthDebugView from '$lib/views/auth/AuthDebugView.svelte';
import Icon from '$lib/ui/Icon.svelte';
import { ws, type Tab } from '$lib/state/workspace.svelte';
import { ui } from '$lib/state/ui.svelte';
import { wsLogs, type WsEvent } from '$lib/state/wslog.svelte';
import { errorText } from '$lib/api';
import { plain } from '$lib/plain.svelte';
import { parse } from '$lib/json/ast';
import { HEADER_NAMES, headerValues } from '$lib/headers';
import { formatBytes } from '$lib/request';
import type { Request, WsSavedMessage } from '$lib/types';
let { tab }: { tab: Tab } = $props();
void tab;
let req = $derived(tab.draft!);
let spec = $derived(req.ws!);
let format = $state<WsSavedMessage['format']>('json');
let message = $state('{\n \n}');
let section = $state<'message' | 'headers' | 'auth' | 'settings' | 'handshake'>('message');
let filter = $state<'all' | 'in' | 'out'>('all');
let search = $state('');
let expanded = $state<Set<number>>(new Set());
let follow = $state(true);
let logEl: HTMLDivElement | undefined = $state();
let connected = $derived(!!wsLogs.connected[tab.key]);
let connecting = $derived(!!wsLogs.connecting[tab.key]);
let events = $derived(wsLogs.events[tab.key] ?? []);
let shown = $derived(
events.filter(
(e) =>
(filter === 'all' || e.dir === filter || e.dir === 'sys') &&
(!search || e.data.toLowerCase().includes(search.toLowerCase()))
)
);
function scope() {
return { col: tab.col, request_id: tab.id, request: plain(req) as Request, env: ws.env(tab.col) };
}
async function connect() {
wsLogs.connecting[tab.key] = true;
try {
await invoke('ws_connect', { args: { ...scope(), tab: tab.key } });
} catch (e) {
wsLogs.connecting[tab.key] = false;
toast.error('Could not connect', { description: errorText(e) });
}
}
function disconnect() {
invoke('ws_close', { tab: tab.key });
wsLogs.connecting[tab.key] = false;
}
async function send(content = message, fmt = format, file?: string) {
if (!connected) return toast.info('Connect first');
try {
await invoke('ws_send', { tab: tab.key, format: fmt, content, file: file ?? null, scope: scope() });
} catch (e) {
toast.error('Could not send', { description: errorText(e) });
}
}
async function sendFile() {
const f = await openDialog({ title: 'Send file as binary message' });
if (typeof f === 'string') send('', 'hex', f);
}
let seenSend = ui.sendRequest;
$effect(() => {
if (ui.sendRequest !== seenSend) {
seenSend = ui.sendRequest;
if (connected) send();
else connect();
}
});
$effect(() => {
shown.length;
if (follow && logEl) queueMicrotask(() => logEl && (logEl.scrollTop = logEl.scrollHeight));
});
function saveMessage() {
const name = `Message ${(spec.messages?.length ?? 0) + 1}`;
spec.messages ??= [];
spec.messages.push({ name, format, content: message });
}
async function exportLog() {
const path = await saveDialog({ title: 'Export log', defaultPath: 'websocket-log.jsonl' });
if (!path) return;
const text = events.map((e) => JSON.stringify({ at: new Date(e.at).toISOString(), dir: e.dir, kind: e.kind, size: e.size, data: e.data })).join('\n');
await invoke('write_text_file', { path, text });
toast.success('Log exported');
}
function asJson(e: WsEvent) {
if (e.kind !== 'text') return null;
const t = e.data.trimStart();
if (!t.startsWith('{') && !t.startsWith('[')) return null;
try {
return parse(e.data);
} catch {
return null;
}
}
const time = (ms: number) => {
const d = new Date(ms);
return `${d.toLocaleTimeString([], { hour12: false })}.${String(d.getMilliseconds()).padStart(3, '0')}`;
};
const arrow = { in: '↓', out: '↑', sys: '·' };
</script>
<div class="flex h-full flex-col">
<div class="flex h-10 shrink-0 items-center gap-2 border-b border-line px-3">
{#if connected}
<button class="flex h-7 items-center gap-2 rounded border border-line bg-hover px-3 font-bold text-strong" onclick={disconnect}>
<Icon name="stop" size={11} /> Disconnect
</button>
<span class="text-[12px] text-ok">connected{wsLogs.handshake[tab.key]?.hs.protocol ? ` · ${wsLogs.handshake[tab.key].hs.protocol}` : ''}</span>
<button class="rounded px-2 py-1 text-[12px] text-fg-muted hover:bg-hover hover:text-fg" onclick={() => invoke('ws_ping', { tab: tab.key })}>Ping</button>
{:else if connecting}
<button class="flex h-7 items-center gap-2 rounded border border-line px-3 text-fg-muted" onclick={disconnect}>Cancel</button>
<span class="text-[12px] text-fg-muted">connecting…</span>
{:else}
<button class="flex h-7 items-center gap-2 rounded bg-accent px-3 font-bold text-accent-fg hover:bg-accent-hover" onclick={connect} title="Connect (Ctrl+Enter)">
<Icon name="play" size={11} /> Connect
</button>
{/if}
<span class="flex-1"></span>
<span class="text-[12px] text-fg-subtle">{events.filter((e) => e.dir === 'in').length} in · {events.filter((e) => e.dir === 'out').length} out</span>
</div>
<div class="min-h-0 flex-1">
{#key ws.layout}
<Resizable direction={ws.layout === 'columns' ? 'horizontal' : 'vertical'}>
<ResizablePanel size={45} min={20}>
<div class="flex h-full flex-col">
<nav class="flex h-9 shrink-0 items-stretch gap-0.5 border-b border-line px-2">
{#each [['message', 'Message'], ['headers', 'Headers'], ['auth', 'Auth'], ['settings', 'Settings'], ['handshake', 'Handshake']] as [id, label]}
<button class="relative px-2.5 {section === id ? 'text-strong' : 'text-fg-muted hover:text-fg'}" onclick={() => (section = id as typeof section)}>
{label}
{#if section === id}<span class="absolute inset-x-2 bottom-0 h-0.5 bg-cyan"></span>{/if}
</button>
{/each}
</nav>
<div class="min-h-0 flex-1">
{#if section === 'message'}
<div class="flex h-full flex-col">
<div class="flex shrink-0 items-center gap-1 border-b border-line px-3 py-1">
{#each ['json', 'text', 'hex'] as f}
<button class="rounded px-2 py-0.5 text-[12px] {format === f ? 'bg-hover text-strong' : 'text-fg-muted hover:text-fg'}" onclick={() => (format = f as typeof format)}>{f === 'hex' ? 'Binary (hex)' : f.toUpperCase()}</button>
{/each}
<span class="flex-1"></span>
<button class="rounded px-2 py-0.5 text-[12px] text-fg-muted hover:text-fg" onclick={saveMessage}>Save</button>
<button class="rounded px-2 py-0.5 text-[12px] text-fg-muted hover:text-fg" onclick={sendFile}>Send file…</button>
<button class="ml-1 rounded bg-accent px-3 py-0.5 text-[12px] font-bold text-accent-fg disabled:opacity-40" disabled={!connected} onclick={() => send()} title="Send (Ctrl+Enter)">Send</button>
</div>
<div class="min-h-0 flex-1">
{#if format === 'json'}
<JsonBody bind:text={message} compact />
{:else}
<CodeEditor bind:value={message} lang="text" placeholder={format === 'hex' ? '0a ff 10 20' : 'Message text'} onsubmit={() => send()} />
{/if}
</div>
{#if spec.messages?.length}
<div class="max-h-40 shrink-0 overflow-auto border-t border-line">
<div class="k-label px-3 pt-2">Saved messages</div>
{#each spec.messages as m, i (i)}
<div class="group flex items-center gap-2 px-3 py-1 hover:bg-hover/40">
<input class="k-field !w-40 !py-0.5 !font-sans" bind:value={m.name} />
<span class="mono text-[11px] text-fg-subtle">{m.format}</span>
<span class="mono min-w-0 flex-1 truncate text-[11.5px] text-fg-muted">{m.content.replace(/\s+/g, ' ')}</span>
<button class="text-[12px] text-fg-muted hover:text-fg" onclick={() => ((message = m.content), (format = m.format))}>Load</button>
<button class="text-[12px] text-accent disabled:opacity-40" disabled={!connected} onclick={() => send(m.content, m.format)}>Send</button>
<button class="text-fg-subtle opacity-0 hover:text-delete group-hover:opacity-100" onclick={() => spec.messages!.splice(i, 1)}><Icon name="x" size={12} /></button>
</div>
{/each}
</div>
{/if}
</div>
{:else if section === 'headers'}
<div class="k-scroll h-full p-3">
<KeyValueTable bind:rows={req.headers!} nameSuggestions={HEADER_NAMES} valueSuggestions={headerValues} />
<div class="k-label mb-1.5 mt-5">Subprotocols</div>
<TagInput value={spec.subprotocols ?? []} placeholder="graphql-transport-ws, mqtt, …" onchange={(t) => (spec.subprotocols = t)} />
</div>
{:else if section === 'auth'}
<div class="k-scroll h-full"><AuthPanel bind:auth={req.auth} {tab} level="request" /></div>
{:else if section === 'settings'}
<div class="flex max-w-xl flex-col gap-4 p-4">
<div class="flex items-center gap-4">
<div class="flex-1">
<div>Reconnect automatically</div>
<div class="text-[12px] text-fg-subtle">After the server closes, retry with 1, 2, 4 … 30 s pauses</div>
</div>
<Switch checked={!!spec.auto_reconnect} onchange={(v) => (spec.auto_reconnect = v || undefined)} aria-label="Reconnect" />
</div>
</div>
{:else if section === 'handshake'}
<div class="k-scroll selectable h-full p-3 text-[12.5px]">
{#if wsLogs.authFailure[tab.key]}
<AuthDebugView debug={wsLogs.authFailure[tab.key]} />
{:else if wsLogs.handshake[tab.key]}
{@const h = wsLogs.handshake[tab.key]}
<div class="mono mb-3">HTTP {h.hs.status} in {Math.round(h.hs.ms)} ms · {h.hs.url}</div>
<div class="k-label mb-1">Sent</div>
{#each h.hs.request_headers as [k, v]}<div class="mono flex gap-3 py-0.5"><span class="w-1/3 shrink-0 text-get">{k}</span><span class="break-all">{ws.maskSecrets && /authorization|cookie/i.test(k) ? '••••••' : v}</span></div>{/each}
<div class="k-label mb-1 mt-4">Received</div>
{#each h.hs.response_headers as [k, v]}<div class="mono flex gap-3 py-0.5"><span class="w-1/3 shrink-0 text-get">{k}</span><span class="break-all">{v}</span></div>{/each}
{#if h.auth.kind && h.auth.kind !== 'none'}
<div class="mt-4"><AuthDebugView debug={h.auth} /></div>
{/if}
{:else}
<p class="text-fg-subtle">Connect to see the handshake.</p>
{/if}
</div>
{/if}
</div>
</div>
</ResizablePanel>
<ResizableHandle />
<ResizablePanel min={20}>
<div class="flex h-full flex-col {ws.layout === 'columns' ? 'border-l' : 'border-t'} border-line">
<div class="flex h-9 shrink-0 items-center gap-2 border-b border-line px-2">
{#each ['all', 'in', 'out'] as f}
<button class="rounded px-2 py-0.5 text-[12px] {filter === f ? 'bg-hover text-strong' : 'text-fg-muted hover:text-fg'}" onclick={() => (filter = f as typeof filter)}>{f === 'all' ? 'All' : f === 'in' ? 'Received' : 'Sent'}</button>
{/each}
<label class="ml-1 flex h-6 min-w-0 flex-1 items-center gap-1.5 rounded border border-line bg-input px-2">
<Icon name="search" size={11} class="text-fg-subtle" />
<input class="min-w-0 flex-1 bg-transparent text-[12px] outline-none" placeholder="Search messages" bind:value={search} />
</label>
<label class="flex items-center gap-1 text-[12px] text-fg-muted"><input type="checkbox" class="size-3 accent-[var(--knock-cyan)]" bind:checked={follow} />follow</label>
<button class="rounded px-1.5 py-0.5 text-[12px] text-fg-muted hover:text-fg" onclick={exportLog}>Export</button>
<button class="rounded px-1.5 py-0.5 text-[12px] text-fg-muted hover:text-fg" onclick={() => wsLogs.clear(tab.key)}>Clear</button>
</div>
<div bind:this={logEl} class="k-scroll selectable min-h-0 flex-1 text-[12.5px]">
{#each shown as e (e.id)}
{@const json = expanded.has(e.id) ? asJson(e) : null}
<div class="border-b border-line/50 {e.dir === 'sys' ? 'bg-hover/30' : ''}">
<button
class="flex w-full items-start gap-2 px-2 py-1 text-left"
onclick={() => {
const n = new Set(expanded);
if (n.has(e.id)) n.delete(e.id);
else n.add(e.id);
expanded = n;
}}
>
<span class="mono w-4 shrink-0 text-center {e.dir === 'in' ? 'text-ok' : e.dir === 'out' ? 'text-get' : 'text-fg-subtle'}">{arrow[e.dir]}</span>
<span class="mono shrink-0 text-[11px] text-fg-subtle">{time(e.at)}</span>
{#if e.kind !== 'text'}<span class="mono shrink-0 text-[11px] {e.kind === 'error' ? 'text-delete' : 'text-put'}">{e.kind}</span>{/if}
<span class="mono min-w-0 flex-1 {expanded.has(e.id) ? 'whitespace-pre-wrap break-all' : 'truncate'} {e.kind === 'error' ? 'text-delete' : e.dir === 'sys' ? 'text-fg-muted' : 'text-fg'}">{e.data}</span>
{#if e.size}<span class="shrink-0 text-[11px] text-fg-subtle">{formatBytes(e.size)}</span>{/if}
</button>
{#if json}
<div class="h-64 border-t border-line/50"><JsonViewer root={json} /></div>
{/if}
</div>
{:else}
<p class="p-4 text-fg-subtle">{connected ? 'No messages yet.' : 'Connect, then send a message with Ctrl+Enter.'}</p>
{/each}
</div>
</div>
</ResizablePanel>
</Resizable>
{/key}
</div>
</div>