@liechtenecker_development/clarity-api-client
v0.6.0
Published
Type-safe HTTP + WebSocket client for the Clarity Web Analyser API. Covers runs, templates, plugins, snapshots, AI sessions, costs, and WebSocket-driven live updates.
Readme
@clarity/api-client
Type-safe HTTP + WebSocket client for the Clarity Web Analyser API. Covers runs, templates, plugins, snapshots, AI sessions, costs, and WebSocket-driven live updates.
Published on npm as @liechtenecker_development/clarity-api-client.
Install
npm install @liechtenecker_development/clarity-api-clientQuick start
import { ClarityClient } from "@liechtenecker_development/clarity-api-client";
const client = new ClarityClient({
baseUrl: "https://your-clarity-host",
auth: { type: "credential", credential: process.env.CLARITY_API_KEY! },
});
// Trigger a run
const { run } = await client.triggerRun("your-template-slug", {
inputs: { url: "https://example.com" },
});
// Wait for completion
const { run: finalRun } = await client.waitForRun(run.id, {
onProgress: (r) => console.log(`status: ${r.status}`),
});
console.log(`score: ${finalRun.overallScore}`);Authentication
Pass one of these as auth in the constructor:
| Type | Use case |
|---|---|
| { type: "credential", credential: "clr_..." | "cla_..." } | Personal token or app token — auto-exchanges for a JWT and refreshes before expiry |
| { type: "apiKey", apiKey: "..." } | Static Authorization: Bearer … header |
| { type: "cookie" } | Browser flows that already have a session cookie |
| { type: "custom", getToken: () => Promise<string> } | Provide your own token logic |
Watching runs in real time
waitForRun(id, options) connects via WebSocket when available and falls back to polling when not. The options let you observe both transports:
import type { WsEvent } from "@liechtenecker_development/clarity-api-client";
const ac = new AbortController();
await client.waitForRun(run.id, {
// Coarse-grained — fires under both WS and polling
onProgress: (run) => updateRunSummary(run),
// Fine-grained — only fires while WS is connected
onEvent: (event: WsEvent) => dispatch(event),
// Transport visibility — fires on WS connect and on fallback to polling
onTransportChange: (t) => {
if (t === "polling") showBanner("Reconnecting…");
else hideBanner();
},
// Cancel cleanly (e.g. on component unmount)
signal: ac.signal,
});Retry on WS loss
Combine signal with onTransportChange to abort + restart on WS drop instead of silently degrading to polling:
async function waitWithWsRetry(id: string, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
const ac = new AbortController();
try {
return await client.waitForRun(id, {
signal: ac.signal,
onTransportChange: (t) => {
if (t === "polling") ac.abort("ws-lost");
},
onEvent: dispatch,
});
} catch (err) {
if (
err instanceof Error &&
err.name === "AbortError" &&
(err as { cause?: unknown }).cause === "ws-lost"
) {
await new Promise((r) => setTimeout(r, 1_000 * (i + 1)));
continue;
}
throw err;
}
}
throw new Error("WS retries exhausted");
}What's in the API
getRuns/getRun/triggerRun/cancelRun/rerunFromAlias/getRunsTreegetTemplates/getTemplate/createTemplate/updateTemplate/publishTemplate/unpublishTemplate/deleteTemplategetTemplateSnapshots/createTemplateSnapshot/restoreTemplateSnapshotgetPlugins/getPlugin/validatePluginSettings/debugPluginwatchRun(raw WS handle) andwaitForRun(promise wrapper, used above)- AI session helpers (
getAiSessions,createAiSession,updateAiSession, …) - Cost reports, app-token management, run-input schema validation, and more
All response shapes are exported as named types — see types.ts in the published bundle for the full surface.
Versioning
Semver. Breaking changes bump the major (or minor while still pre-1.0). See CHANGELOG.md for what shipped in each release.
Code generation
The package ships a small CLI (clarity-codegen) that regenerates per-plugin output types from a running API instance. Configure your plugins with Zod output schemas and run:
npx clarity-codegen --base-url https://your-clarity-host --out src/generated/plugins.tsLicense
Private package — internal use only.
