char-slop/stars.hackery.site

git clone https://git.t4t.associates/char-slop/stars.hackery.site

Charlotte Somsyntactic pass: no casts, assertions, or void92004f9

main
1.7 KiB65 linesraw
1export async function readBytes(
2  chunks: AsyncIterable<Uint8Array> | Iterable<Uint8Array>,
3  maxBytes: number,
4): Promise<Uint8Array> {
5  const parts: Uint8Array[] = [];
6  let size = 0;
7  for await (const chunk of chunks) {
8    size += chunk.byteLength;
9    if (size > maxBytes) throw new Error("Body too large");
10    parts.push(chunk);
11  }
12  const bytes = new Uint8Array(size);
13  let offset = 0;
14  for (const part of parts) {
15    bytes.set(part, offset);
16    offset += part.byteLength;
17  }
18  return bytes;
19}
20
21export const cookie = (
22  name: string,
23  value: string,
24  secure: boolean,
25  maxAge: number,
26) =>
27  `${name}=${value}; Path=/; HttpOnly; SameSite=Lax; Max-Age=${maxAge}${
28    secure ? "; Secure" : ""
29  }`;
30
31export const readCookie = (req: Request, name: string) =>
32  new RegExp(`(?:^|;\\s*)${name}=([^;]*)`)
33    .exec(req.headers.get("cookie") ?? "")?.[1];
34
35// An origin with nothing else: no credentials, path, query, or fragment.
36export const isBareOrigin = (url: URL) =>
37  ["https:", "http:"].includes(url.protocol) && !url.username &&
38  !url.password && url.pathname === "/" && !url.search && !url.hash;
39
40export class HttpError extends Error {
41  constructor(
42    readonly status: number,
43    message: string,
44    readonly headers: HeadersInit = {},
45  ) {
46    super(message);
47  }
48
49  response(): Response {
50    return new Response(this.message, {
51      status: this.status,
52      headers: this.headers,
53    });
54  }
55}
56
57export function fail(status: number, message: string): never {
58  throw new HttpError(status, message);
59}
60
61export const redirect = (path: string, ...cookies: string[]): Response => {
62  const res = new Response(null, { status: 303, headers: { location: path } });
63  for (const value of cookies) res.headers.append("set-cookie", value);
64  return res;
65};