Skip to content
Source
Sign inSign up
pingdotgg/t3code
Open History to see the last commit

OpenCode2Client.test.ts

48 lines2.0 KB

1import { assert, it } from "@effect/vitest";
2import * as Effect from "effect/Effect";
3import * as Layer from "effect/Layer";
4import * as Redacted from "effect/Redacted";
5import { HttpClient, HttpClientResponse } from "effect/http";
6import { describe } from "vite-plus/test";
7​
8import * as OpenCode2Client from "./OpenCode2Client.ts";
9​
10const INFO_BODY = '{"version":"2.0.18","pid":4242,"urls":[],"paths":{"tmp":"/tmp"}}';
11​
12/** Sends one request through the client and returns the Authorization header it carried. */
13const authorizationFor = (password: string | Redacted.Redacted) => {
14 const seen: Array<string | undefined> = [];
15 const layerCapturing = Layer.succeed(
16 HttpClient.HttpClient,
17 HttpClient.make((request) =>
18 Effect.sync(() => {
19 seen.push(request.headers.authorization);
20 return HttpClientResponse.fromWeb(
21 request,
22 new Response(INFO_BODY, { headers: { "content-type": "application/json" } }),
23 );
24 }),
25 ),
26 );
27 return Effect.gen(function* () {
28 const opencode = yield* OpenCode2Client.OpenCode2Client;
29 const { client } = yield* opencode.connect({ baseUrl: "http://127.0.0.1:4096", password });
30 yield* client.server.info();
31 return seen[0];
32 }).pipe(Effect.provide(OpenCode2Client.layer.pipe(Layer.provide(layerCapturing))));
33};
34​
35const utf8Basic = (password: string) =>
36 `Basic ${Buffer.from(`opencode:${password}`, "utf8").toString("base64")}`;
37​
38describe("OpenCode2Client authorization", () => {
39 // OpenCode decodes Basic credentials as UTF-8. Latin-1 (`btoa`) encoding gets
40 // `pässwörd` rejected with a 401 and throws on characters such as `€`.
41 it.effect("encodes non-ASCII passwords as UTF-8", () =>
42 Effect.gen(function* () {
43 assert.strictEqual(yield* authorizationFor("pässwörd"), utf8Basic("pässwörd"));
44 assert.strictEqual(yield* authorizationFor("pass€word"), utf8Basic("pass€word"));
45 assert.strictEqual(yield* authorizationFor(Redacted.make("pässwörd")), utf8Basic("pässwörd"));
46 }),
47 );
48});