raw.ts
This file
Path
packages/project/src/code/raw.ts
176 lines · 5.1 KiB · TypeScript
Last changed by
Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd
History of this fileTake it
Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
line 1why, one step back1import { ObjectId, RepoHost } from "@repo/artifacts/repo-host";Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd
line 2why, one step back2import type { RepoNotFound } from "@repo/artifacts/repo-host";Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 3–11why, one step back3import { Rev } from "@repo/protocol/domain/code";4import { BlobSha, RepoPath } from "@repo/protocol/ids";5import type { ProjectName } from "@repo/protocol/ids";6import { Effect, Option, Schema } from "effect";78import { codeProjectOf } from "../code.ts";9import type { CodeProject } from "../code.ts";10import { Projects } from "../projects.ts";11import { isBinary, unlessTooLarge } from "./file.ts";Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd
line 12why, one step back12import { keptOnlyIfCanonical } from "./history.ts";Merge redesign into mainoscabrielbefore adoptioncaedd21
line 13why, one step back13import { commitAt, isFullSha, resolveAt } from "./revision.ts";Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd
line 14why, one step back14import type { Resolved } from "./revision.ts";Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 15–16why, one step back15import { entryAt, segmentsOf } from "./tree.ts";16Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 17why, one step back17/** Both origins hold a session cookie, so no raw file may run as script: every answer, a refusal too, carries `nosniff` and this CSP. */Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 18–72why, one step back18const SANDBOX =19 "default-src 'none'; img-src 'self' data:; style-src 'unsafe-inline'; sandbox";2021const IMAGES = new Map([22 ["avif", "image/avif"],23 ["gif", "image/gif"],24 ["ico", "image/x-icon"],25 ["jpeg", "image/jpeg"],26 ["jpg", "image/jpeg"],27 ["png", "image/png"],28 ["svg", "image/svg+xml"],29 ["webp", "image/webp"],30]);3132const TEXT = "text/plain; charset=utf-8";3334const SAFE = {35 "content-security-policy": SANDBOX,36 "x-content-type-options": "nosniff",37} as const;3839const extensionOf = (path: string) => {40 const name = path.slice(path.lastIndexOf("/") + 1);41 const dot = name.lastIndexOf(".");4243 return dot <= 0 ? "" : name.slice(dot + 1).toLowerCase();44};4546export const rawHeaders = (47 path: RepoPath,48 rev: "sha" | "ref",49 blob: BlobSha,50 binary = false51): Headers => {52 const headers = new Headers({53 ...SAFE,54 "content-type":55 IMAGES.get(extensionOf(path)) ??56 (binary ? "application/octet-stream" : TEXT),57 });5859 if (rev === "sha") {60 headers.set("cache-control", "public, max-age=31536000, immutable");61 headers.set("etag", `"${blob}"`);62 } else {63 headers.set("cache-control", "public, max-age=60");64 }6566 return headers;67};6869const notFound = () => new Response(null, { headers: SAFE, status: 404 });7071const tooLarge = () => new Response(null, { headers: SAFE, status: 413 });72Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd
lines 73–74why, one step back73const rawAt = (74 { commit, repo }: Resolved,Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 75–76why, one step back75 rev: Rev,76 path: RepoPathMerge perf/code-store into mainoscabrielbefore adoptionef0ddbd
line 77why, one step back77): Effect.Effect<Response, RepoNotFound, RepoHost> =>Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
line 78why, one step back78 Effect.gen(function* () {Merge redesign into mainoscabrielbefore adoptioncaedd21
line 79why, one step back79 const { tree } = yield* commitAt(repo, commit).pipe(Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 80–82why, one step back80 Effect.flatMap(Effect.fromOption)81 );82Merge redesign into mainoscabrielbefore adoptioncaedd21
line 83why, one step back83 const entry = yield* entryAt(repo, tree, path);Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 84–91why, one step back8485 if (Option.isNone(entry) || entry.value.type !== "blob") {86 return notFound();87 }8889 const blob = BlobSha.make(entry.value.sha);9091 const bytes = yield* RepoHost.use((host) =>Merge redesign into mainoscabrielbefore adoptioncaedd21
line 92why, one step back92 host.readBlob(repo, ObjectId.make(blob))Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 93–109why, one step back93 );9495 return Option.match(bytes, {96 onNone: notFound,97 onSome: (read) =>98 new Response(new Uint8Array(read), {99 headers: rawHeaders(100 path,101 isFullSha(rev) ? "sha" : "ref",102 blob,103 isBinary(read)104 ),105 status: 200,106 }),107 });108 }).pipe(109 (read) => unlessTooLarge(read, tooLarge),Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd
line 110why, one step back110 Effect.catchTag("NoSuchElementError", () => Effect.succeed(notFound()))Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 111–136why, one step back111 );112113const decodeRev = Schema.decodeUnknownOption(Rev);114115const decodePath = Schema.decodeUnknownOption(RepoPath);116117const decoded = Option.liftThrowable(decodeURIComponent);118119export const rawRequestOf = (120 rest: string121): Option.Option<{ readonly rev: Rev; readonly path: RepoPath }> => {122 const slash = rest.indexOf("/");123124 if (slash === -1) {125 return Option.none();126 }127128 return Option.all({129 path: decoded(rest.slice(slash + 1)).pipe(130 Option.filter((path) => Option.isSome(segmentsOf(path))),131 Option.flatMap(decodePath)132 ),133 rev: Option.flatMap(decoded(rest.slice(0, slash)), decodeRev),134 });135};136Merge build/comments-project into mainoscabrielbefore adoption49efd2a
line 137why, one step back137/** Read from the URL, not a router's parameter: a router decodes `%2F`, which would cut a tag's name in two. */Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 138–140why, one step back138export const rawRestOf = (url: string, project: ProjectName): string => {139 const segments = new URL(url, "http://raw.invalid").pathname.split("/");140 const named = project.split("/").length;Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
line 141why, one step back141Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
lines 142–147why, one step back142 if (segments[named + 1] === "raw") {143 return segments.slice(named + 2).join("/");144 }145146 return segments[2] === "raw" ? segments.slice(3).join("/") : "";147};Merge perf/code-store into mainoscabrielbefore adoptionef0ddbd
lines 148–163why, one step back148149export const rawOf = (150 project: CodeProject,151 rev: Rev,152 path: RepoPath153): Effect.Effect<Response, never, RepoHost> =>154 Effect.gen(function* () {155 const resolved = yield* resolveAt(project, Option.some(rev));156157 return yield* keptOnlyIfCanonical(resolved, rawAt(resolved, rev, path));158 }).pipe(159 Effect.catchTags({160 RepoNotFound: () => Effect.succeed(notFound()),161 UnknownRevision: () => Effect.succeed(notFound()),162 })163 );Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 164why, one step back164Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 165–168why, one step back165export const rawFor = (166 project: ProjectName,167 url: string168): Effect.Effect<Response, never, RepoHost | Projects> =>Merge build/1400-w14-foundation into mainoscabrielbefore adoption47dd2f8
line 169why, one step back169 Option.match(rawRequestOf(rawRestOf(url, project)), {Merge branch 'build/903-code-reads'oscabrielbefore adoption7608aca
lines 170–176why, one step back170 onNone: () => Effect.succeed(notFound()),171 onSome: ({ path, rev }) =>172 Projects.use((projects) => projects.get(project)).pipe(173 Effect.flatMap((api) => rawOf(codeProjectOf(api, project), rev, path)),174 Effect.catchTag("UnknownProject", () => Effect.succeed(notFound()))175 ),176 });