SPB Git

Repository Public

transport.ts 2.0 KB 52 lines typescript

1import { ApiError, type Transport } from "./types"23/** Same-origin transport. The session cookie is HttpOnly; scripts never see it. */4export class BrowserTransport implements Transport {5  private async raw(method: string, path: string, init: RequestInit): Promise<Response> {6    let res: Response7    try {8      res = await fetch(path, { method, credentials: "same-origin", ...init, headers: { "x-spm": "1", ...(init.headers as object) } })9    } catch {10      throw new ApiError(0, "network", "Network unavailable")11    }12    if (!res.ok) {13      const j = await res.json().catch(() => ({}))14      throw new ApiError(res.status, j.error ?? "error", j.message)15    }16    return res17  }18  async request<T>(method: string, path: string, body?: unknown): Promise<T> {19    const res = await this.raw(method, path, body === undefined ? {} : { body: JSON.stringify(body), headers: { "content-type": "application/json" } })20    return (await res.json()) as T21  }22  async getBytes(path: string) {23    return new Uint8Array(await (await this.raw("GET", path, {})).arrayBuffer())24  }25  async putBytes(path: string, data: Uint8Array) {26    await this.raw("PUT", path, { body: data as unknown as BodyInit, headers: { "content-type": "application/octet-stream" } })27  }28  socket(onMessage: (m: any) => void, onState: (open: boolean) => void) {29    const ws = new WebSocket(`${location.protocol === "https:" ? "wss" : "ws"}://${location.host}/ws`)30    let ping: ReturnType<typeof setInterval> | undefined31    let closed = false32    const down = () => {33      if (closed) return34      closed = true35      clearInterval(ping)36      onState(false)37    }38    ws.onopen = () => {39      onState(true)40      ping = setInterval(() => ws.readyState === 1 && ws.send('{"t":"ping"}'), 20000)41    }42    ws.onmessage = (e) => {43      try {44        onMessage(JSON.parse(e.data))45      } catch {}46    }47    ws.onclose = down48    ws.onerror = () => ws.close()49    return { send: (m: unknown) => ws.readyState === 1 && ws.send(JSON.stringify(m)), close: () => ws.close() }50  }51}52
Files main
Menu

Theme