# Testing and runtimes (TypeScript)

Test code that uses the TypeScript SDK with an injected fetch, and what to know about Node, Bun, Deno, Cloudflare Workers and browsers.

The client needs only `fetch`, so a stub is enough to test it and most runtimes run it unchanged. This page covers the runtime differences and a test with no network.

## Runtimes

The client reads three things from outside itself: the global `fetch`, environment variables (through `process.env`, or `Deno.env` when there is no `process`), and the CLI (through `process.getBuiltinModule`). Where one of them is missing the client carries on without it.

| Runtime | Notes |
| --- | --- |
| Node 20 or later | ESM and CJS. The CLI token needs 20.16 or later, or 22.3 or later; before that, set `SAILFORK_TOKEN` or pass `token` |
| Bun | Runs the TypeScript source or the package. The CLI token works |
| Deno | `import Sailfork from 'npm:sailfork'`. Environment variables need `--allow-env`, and without it they read as unset. Pass `token` explicitly if in doubt |
| Cloudflare Workers | There is no environment variable lookup and no CLI. Pass `token` from a binding, and `agent` if the Worker acts as an agent |
| Browsers | Not a supported target. A token in page code is public to every visitor, so keep calls on a server |

```ts
import Sailfork from 'sailfork';

type Env = { SAILFORK_TOKEN: string };

export default {
	async fetch(_request: Request, env: Env): Promise<Response> {
		const sf = new Sailfork({ token: env.SAILFORK_TOKEN, agent: 'pr-bot' });
		const { items } = await sf.repo('acme/api').pulls.list({ limit: 5 });
		return Response.json(items.map((pull) => ({ number: pull.number, title: pull.title })));
	},
};
```

Without `agent`, a Worker's requests carry no agent name, so the organization's [agent permissions](https://sailfork.com/docs/agent-permissions) treat them as a person's. Name the Worker when it should be held to the rules for agents.

## Test your code

Inject `fetch` to run the client against a stub, with no network and no token lookup. Pass `token` so the client does not try the CLI, `maxRetries: 0` so a failure answers at once, and `agent: false` so the environment of the machine running the test does not change the headers.

```ts
import Sailfork, { AgentPolicyError, NotFoundError } from 'sailfork';

type Seen = { url: string; method: string | undefined; headers: Record<string, string>; body: string | undefined };

function stub(answer: (seen: Seen) => Response): { fetch: typeof fetch; calls: Seen[] } {
	const calls: Seen[] = [];
	const fetchStub = (async (input: RequestInfo | URL, init?: RequestInit) => {
		const seen: Seen = {
			url: String(input),
			method: init?.method,
			headers: (init?.headers ?? {}) as Record<string, string>,
			body: typeof init?.body === 'string' ? init.body : undefined,
		};
		calls.push(seen);
		return answer(seen);
	}) as typeof fetch;
	return { fetch: fetchStub, calls };
}

const json = (status: number, body: unknown) =>
	new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });

// A merge a person must approve comes back as a held result.
const held = stub(() => json(202, { held: 'h_1', url: '/requests', message: 'HELD FOR A PERSON: merge acme/api#128' }));
const sf = new Sailfork({ token: 'test', host: 'https://sailfork.test', fetch: held.fetch, maxRetries: 0, agent: false });

const merge = await sf.repo('acme/api').pull(128).merge({ method: 'squash' });
if (merge.status !== 'held') throw new Error('expected a held merge');
if (merge.url !== 'https://sailfork.test/requests') throw new Error(merge.url);
if (held.calls[0]?.url !== 'https://sailfork.test/api/repos/acme/api/pulls/128/merge') throw new Error('wrong route');
if (held.calls[0]?.body !== '{"method":"squash"}') throw new Error('wrong body');
if (held.calls[0]?.headers['idempotency-key'] === undefined) throw new Error('writes send an idempotency key');

// An error answer becomes a typed error.
const missing = stub(() => json(404, { error: 'not found', code: 'not_found' }));
const lost = new Sailfork({ token: 'test', host: 'https://sailfork.test', fetch: missing.fetch, maxRetries: 0, agent: false });
try {
	await lost.repo('acme/api').pull(1).get();
	throw new Error('expected a 404');
} catch (error) {
	if (!(error instanceof NotFoundError)) throw error;
}

const refused = stub(() => json(403, { error: 'declined', code: 'held_declined' }));
const declined = new Sailfork({ token: 'test', host: 'https://sailfork.test', fetch: refused.fetch, maxRetries: 0, agent: false });
await declined.repo('acme/api').pull(1).merge().catch((error: unknown) => {
	if (!(error instanceof AgentPolicyError)) throw error;
});
```

To test retries, make the stub answer 503 once and then 200. The client sends the same `idempotency-key` on both attempts, and a test can assert that.

## Test a retry

The stub answers 503 once, then 200. The client sends one `idempotency-key` and reuses it for the second attempt, so a test can assert both the retry and the key.

```ts
import Sailfork from 'sailfork';

const keys: (string | undefined)[] = [];
let attempts = 0;
const flaky = (async (_input: RequestInfo | URL, init?: RequestInit) => {
	attempts++;
	keys.push((init?.headers as Record<string, string> | undefined)?.['idempotency-key']);
	return attempts === 1
		? new Response(JSON.stringify({ error: 'busy', code: 'busy' }), { status: 503, headers: { 'content-type': 'application/json' } })
		: new Response(JSON.stringify({ number: 128, state: 'merged' }), { status: 200, headers: { 'content-type': 'application/json' } });
}) as typeof fetch;

const sf = new Sailfork({ token: 'test', host: 'https://sailfork.test', fetch: flaky, agent: false });
const merge = await sf.repo('acme/api').pull(128).merge();

if (attempts !== 2) throw new Error(`expected 2 attempts, got ${attempts}`);
if (keys[0] === undefined || keys[0] !== keys[1]) throw new Error('the key changed between attempts');
if (merge.status !== 'done') throw new Error('expected a done result');
```

The retry waits 250 to 500 ms before the second attempt, so the test takes about that long.
The same topic for Python: [Python testing](https://sailfork.com/docs/sdk-python-testing).

---

Every docs page: https://sailfork.com/llms.txt
