feat(sdk): @punktfunk/host — the Effect TypeScript SDK (M3)
apple / swift (push) Successful in 1m15s
apple / screenshots (push) Successful in 4m21s
ci / web (push) Successful in 52s
ci / docs-site (push) Successful in 1m0s
android / android (push) Has been cancelled
arch / build-publish (push) Has been cancelled
ci / rust (push) Has been cancelled
ci / bench (push) Has been cancelled
deb / build-publish (push) Has been cancelled
decky / build-publish (push) Has been cancelled
docker / build-push (--build-arg FEDORA_VERSION=44, ci, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm) (push) Successful in 18s
docker / build-push (., web/Dockerfile, punktfunk-web) (push) Successful in 15s
docker / build-push (ci, ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 14s
docker / build-push (ci, ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 16s
docker / build-push (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 13s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 14m56s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 19m42s
docker / deploy-docs (push) Successful in 26s
apple / swift (push) Successful in 1m15s
apple / screenshots (push) Successful in 4m21s
ci / web (push) Successful in 52s
ci / docs-site (push) Successful in 1m0s
android / android (push) Has been cancelled
arch / build-publish (push) Has been cancelled
ci / rust (push) Has been cancelled
ci / bench (push) Has been cancelled
deb / build-publish (push) Has been cancelled
decky / build-publish (push) Has been cancelled
docker / build-push (--build-arg FEDORA_VERSION=44, ci, ci/fedora-rpm.Dockerfile, punktfunk-fedora44-rpm) (push) Successful in 18s
docker / build-push (., web/Dockerfile, punktfunk-web) (push) Successful in 15s
docker / build-push (ci, ci/fedora-rpm.Dockerfile, punktfunk-fedora-rpm) (push) Successful in 14s
docker / build-push (ci, ci/rust-ci.Dockerfile, punktfunk-rust-ci) (push) Successful in 16s
docker / build-push (docs-site, docs-site/Dockerfile, punktfunk-docs) (push) Successful in 13s
rpm / build-publish (44, fedora-44, punktfunk-fedora44-rpm) (push) Successful in 14m56s
rpm / build-publish (43, bazzite, punktfunk-fedora-rpm) (push) Successful in 19m42s
docker / deploy-docs (push) Successful in 26s
New top-level sdk/ package (RFC §7): a typed management-API client plus the lifecycle event stream, built on Effect, two surfaces over one core: - @punktfunk/host — the Promise facade front door: connect() resolves URL/token/TLS pin from the host's own files (zero config on the box), fails fast on bad credentials, pf.events.on() with typed callbacks (exact kinds, domain.* prefixes, "*", "dropped", "unknown"), pf.request() for the REST surface. Effect never required. - @punktfunk/host/effect — the PunktfunkHost service + PunktfunkHostLive layer, Stream-based events()/eventsRaw(), typed errors (AuthError | ApiError | TransportError | VersionSkew — a 2xx that fails its schema is a typed skew, not undefined later), and every wire shape as an effect/Schema: REST generated via orval client:'effect' from api/openapi.json (S3 spike: works well; the text/event-stream payload is out of its reach), events hand-mirrored from the host's snapshot-tested wire format as a kind-discriminated union. One reconnecting SSE core under both surfaces: spec-shaped parser, exponential+jittered backoff (capped, resets after a healthy connection), Last-Event-ID resume, 401 terminal. Default is LIVE tail only — a fresh notify script must not re-fire on the host's replayed ring (since: 0 opts into full replay). TLS: the pin trusts exactly the host's self-signed identity cert (chain-verified; hostname check waived — the cert is deliberately CN-only for fingerprint pinning). Bun via fetch tls, Node via an undici dispatcher (optionalDependency). definePlugin() accepts both main shapes (async fn | Effect requiring PunktfunkHost). Examples in both styles; README carries the compat contract + systemd/Task Scheduler templates. 11 bun tests green (wire decode against the Rust snapshot strings, SSE parser/reconnect/Last-Event-ID/401, both surfaces vs a mock host). Live-verified against a real host on Bun AND Node through the pinned loopback hop: connect → REST mutate → live event received → resume cursor advanced; a wrong CA is rejected. npm publish + CI wiring deferred (npm org = RFC open question 1). Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -0,0 +1,85 @@
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { SseAuthError, SseParser, sseFrames } from "../src/sse.js";
|
||||
import type { ResolvedConfig } from "../src/config.js";
|
||||
|
||||
describe("SseParser", () => {
|
||||
test("parses frames split across arbitrary chunks, skipping comments", () => {
|
||||
const p = new SseParser();
|
||||
let frames = p.push("id: 4\nevent: library.ch");
|
||||
expect(frames.length).toBe(0);
|
||||
frames = p.push('anged\ndata: {"seq":4}\n\n: keep-alive\n\nid: 5\n');
|
||||
expect(frames.length).toBe(1);
|
||||
expect(frames[0]).toEqual({ event: "library.changed", data: '{"seq":4}', id: "4" });
|
||||
frames = p.push("data: x\n\n");
|
||||
expect(frames.length).toBe(1);
|
||||
expect(frames[0]?.id).toBe("5");
|
||||
expect(frames[0]?.event).toBe("message");
|
||||
});
|
||||
|
||||
test("joins multi-line data and handles CRLF", () => {
|
||||
const p = new SseParser();
|
||||
const frames = p.push("data: a\r\ndata: b\r\n\r\n");
|
||||
expect(frames[0]?.data).toBe("a\nb");
|
||||
});
|
||||
});
|
||||
|
||||
const cfgFor = (port: number, token = "t"): ResolvedConfig => ({
|
||||
url: `http://127.0.0.1:${port}`,
|
||||
token,
|
||||
fetch,
|
||||
});
|
||||
|
||||
describe("sseFrames", () => {
|
||||
test("reads frames, reconnects with Last-Event-ID after a server close", async () => {
|
||||
const lastEventIds: Array<string | null> = [];
|
||||
let connection = 0;
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch(req) {
|
||||
lastEventIds.push(req.headers.get("last-event-id"));
|
||||
connection += 1;
|
||||
const first = connection === 1;
|
||||
const body = new ReadableStream({
|
||||
start(controller) {
|
||||
const enc = new TextEncoder();
|
||||
if (first) {
|
||||
controller.enqueue(enc.encode('id: 1\nevent: library.changed\ndata: {"seq":1}\n\n'));
|
||||
controller.close(); // server closes → client must reconnect
|
||||
} else {
|
||||
controller.enqueue(enc.encode('id: 2\nevent: library.changed\ndata: {"seq":2}\n\n'));
|
||||
// stay open
|
||||
}
|
||||
},
|
||||
});
|
||||
return new Response(body, { headers: { "content-type": "text/event-stream" } });
|
||||
},
|
||||
});
|
||||
try {
|
||||
const gen = sseFrames(cfgFor(server.port as number), { onWarning: () => {} });
|
||||
const f1 = await gen.next();
|
||||
expect(f1.value?.id).toBe("1");
|
||||
const f2 = await gen.next(); // spans the reconnect
|
||||
expect(f2.value?.id).toBe("2");
|
||||
await gen.return(undefined);
|
||||
// No `since` = live-tail-only: the first connect carries the beyond-tip cursor,
|
||||
// the reconnect carries the last REAL id.
|
||||
expect(lastEventIds[0]).toBe(String(Number.MAX_SAFE_INTEGER));
|
||||
expect(lastEventIds[1]).toBe("1");
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("401 is terminal (no retry loop)", async () => {
|
||||
const server = Bun.serve({
|
||||
port: 0,
|
||||
fetch: () => new Response("{}", { status: 401 }),
|
||||
});
|
||||
try {
|
||||
const gen = sseFrames(cfgFor(server.port as number), { onWarning: () => {} });
|
||||
await expect(gen.next()).rejects.toBeInstanceOf(SseAuthError);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,117 @@
|
||||
// Both surfaces against one mock host: the Promise facade end to end, and the Effect surface's
|
||||
// request/get/events with typed errors.
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { Effect, Schema as S, Stream } from "effect";
|
||||
import { connect } from "../src/index.js";
|
||||
import * as pf from "../src/effect.js";
|
||||
|
||||
const TOKEN = "test-token";
|
||||
|
||||
/** A minimal mock host: auth-checked /host, /status, and an SSE /events feed. */
|
||||
const mockHost = () => {
|
||||
const emitted = new TextEncoder().encode(
|
||||
'id: 7\nevent: pairing.pending\ndata: {"seq":7,"ts_ms":3,"schema":1,"kind":"pairing.pending","device":{"name":"iPad Pro","fingerprint":"ab12","plane":"native"}}\n\n' +
|
||||
'id: 8\nevent: future.kind\ndata: {"seq":8,"ts_ms":4,"schema":1,"kind":"future.kind"}\n\n' +
|
||||
'id: 9\nevent: library.changed\ndata: {"seq":9,"ts_ms":5,"schema":1,"kind":"library.changed","source":"manual"}\n\n',
|
||||
);
|
||||
return Bun.serve({
|
||||
port: 0,
|
||||
fetch(req) {
|
||||
const url = new URL(req.url);
|
||||
if (req.headers.get("authorization") !== `Bearer ${TOKEN}`) {
|
||||
return Response.json({ error: "missing or invalid credentials" }, { status: 401 });
|
||||
}
|
||||
switch (url.pathname) {
|
||||
case "/api/v1/host":
|
||||
return Response.json({ name: "mock", version: "0.12.0" });
|
||||
case "/api/v1/status":
|
||||
return Response.json({ ok: true, sessions: 0 });
|
||||
case "/api/v1/boom":
|
||||
return Response.json({ error: "kaput" }, { status: 500 });
|
||||
case "/api/v1/events": {
|
||||
const body = new ReadableStream({
|
||||
start(c) {
|
||||
c.enqueue(emitted); // then stay open
|
||||
},
|
||||
});
|
||||
return new Response(body, { headers: { "content-type": "text/event-stream" } });
|
||||
}
|
||||
default:
|
||||
return Response.json({ error: "not found" }, { status: 404 });
|
||||
}
|
||||
},
|
||||
});
|
||||
};
|
||||
|
||||
describe("promise facade", () => {
|
||||
test("connect → request → typed events → unknown channel → close", async () => {
|
||||
const server = mockHost();
|
||||
try {
|
||||
const client = await connect({ url: `http://127.0.0.1:${server.port}`, token: TOKEN });
|
||||
const status = (await client.request("GET", "/status")) as { ok: boolean };
|
||||
expect(status.ok).toBe(true);
|
||||
|
||||
const got: string[] = [];
|
||||
const unknown: unknown[] = [];
|
||||
const done = new Promise<void>((resolve) => {
|
||||
client.events.on("pairing.pending", (e) => {
|
||||
got.push(`pending:${e.device.name}`);
|
||||
});
|
||||
client.events.on("library.*", (e) => {
|
||||
got.push(`lib:${e.kind}`);
|
||||
resolve();
|
||||
});
|
||||
client.events.on("unknown", (e) => unknown.push(e));
|
||||
});
|
||||
await done;
|
||||
expect(got).toEqual(["pending:iPad Pro", "lib:library.changed"]);
|
||||
expect(unknown.length).toBe(1);
|
||||
client.close();
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
|
||||
test("connect fails fast on a bad token", async () => {
|
||||
const server = mockHost();
|
||||
try {
|
||||
await expect(
|
||||
connect({ url: `http://127.0.0.1:${server.port}`, token: "wrong" }),
|
||||
).rejects.toThrow(/credentials/);
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
describe("effect surface", () => {
|
||||
test("request + schema get + typed errors + event stream", async () => {
|
||||
const server = mockHost();
|
||||
const live = pf.PunktfunkHostLive({ url: `http://127.0.0.1:${server.port}`, token: TOKEN });
|
||||
try {
|
||||
const program = Effect.gen(function* () {
|
||||
const status = yield* pf.get("/status", S.Struct({ ok: S.Boolean }));
|
||||
expect(status.ok).toBe(true);
|
||||
|
||||
// A wrong shape is VersionSkew, not undefined-later.
|
||||
const skew = yield* pf
|
||||
.get("/status", S.Struct({ nope: S.String }))
|
||||
.pipe(Effect.flip);
|
||||
expect(skew._tag).toBe("VersionSkew");
|
||||
|
||||
// A host error carries its ApiError envelope message.
|
||||
const boom = yield* pf.request("GET", "/boom").pipe(Effect.flip);
|
||||
expect(boom._tag).toBe("ApiError");
|
||||
if (boom._tag === "ApiError") expect(boom.message).toBe("kaput");
|
||||
|
||||
// The decoded stream skips the unknown kind and delivers the known ones.
|
||||
const events = yield* pf.events().pipe(Stream.take(2), Stream.runCollect);
|
||||
const kinds = [...events].map((e) => e.kind);
|
||||
expect(kinds).toEqual(["pairing.pending", "library.changed"]);
|
||||
});
|
||||
await Effect.runPromise(program.pipe(Effect.provide(live)));
|
||||
} finally {
|
||||
server.stop(true);
|
||||
}
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,63 @@
|
||||
// The wire schemas must decode EXACTLY what the host emits — the JSON literals here are the
|
||||
// Rust side's snapshot-test strings (crates/punktfunk-host/src/events.rs), the schema gate.
|
||||
import { describe, expect, test } from "bun:test";
|
||||
import { decodeHostEvent, kindMatches } from "../src/wire.js";
|
||||
|
||||
describe("wire", () => {
|
||||
test("decodes the host's snapshot frames", () => {
|
||||
const stream = decodeHostEvent(
|
||||
JSON.parse(
|
||||
'{"seq":4182,"ts_ms":1700000000000,"schema":1,"kind":"stream.started","stream":{"mode":"3840x2160@120","hdr":true,"client":"Living Room TV","app":"steam:570","plane":"native"}}',
|
||||
),
|
||||
);
|
||||
expect(stream._tag).toBe("Right");
|
||||
if (stream._tag === "Right" && stream.right.kind === "stream.started") {
|
||||
expect(stream.right.stream.mode).toBe("3840x2160@120");
|
||||
expect(stream.right.stream.app).toBe("steam:570");
|
||||
}
|
||||
|
||||
const disc = decodeHostEvent(
|
||||
JSON.parse(
|
||||
'{"seq":1,"ts_ms":1700000000000,"schema":1,"kind":"client.disconnected","client":{"name":"Deck","fingerprint":"b1c2","plane":"gamestream"},"reason":"timeout"}',
|
||||
),
|
||||
);
|
||||
expect(disc._tag).toBe("Right");
|
||||
if (disc._tag === "Right" && disc.right.kind === "client.disconnected") {
|
||||
expect(disc.right.reason).toBe("timeout");
|
||||
}
|
||||
|
||||
const stopping = decodeHostEvent(
|
||||
JSON.parse('{"seq":2,"ts_ms":1700000000000,"schema":1,"kind":"host.stopping"}'),
|
||||
);
|
||||
expect(stopping._tag).toBe("Right");
|
||||
});
|
||||
|
||||
test("tolerates unknown keys (additive-only wire)", () => {
|
||||
const r = decodeHostEvent({
|
||||
seq: 9,
|
||||
ts_ms: 1,
|
||||
schema: 1,
|
||||
kind: "library.changed",
|
||||
source: "manual",
|
||||
future_field: { anything: true },
|
||||
});
|
||||
expect(r._tag).toBe("Right");
|
||||
});
|
||||
|
||||
test("unknown kinds fail decode (they ride the raw channel)", () => {
|
||||
const r = decodeHostEvent({
|
||||
seq: 9,
|
||||
ts_ms: 1,
|
||||
schema: 1,
|
||||
kind: "totally.new",
|
||||
});
|
||||
expect(r._tag).toBe("Left");
|
||||
});
|
||||
|
||||
test("kindMatches mirrors the host filter semantics", () => {
|
||||
expect(kindMatches("stream.started", "stream.started")).toBe(true);
|
||||
expect(kindMatches("stream.*", "stream.stopped")).toBe(true);
|
||||
expect(kindMatches("stream.*", "streamx.started")).toBe(false);
|
||||
expect(kindMatches("stream.started", "stream.stopped")).toBe(false);
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user