Skip to content
Myr

generated-file.ts

This file

Path

packages/agent-kit/src/generated-file.ts

175 lines · 4.4 KiB · TypeScript

Last changed by

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

History of this file

Take it

The walk stopped after 200 commits: lines older than 678c8b8 point at it.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 1–28why, one step back
1import { Brand } from "@repo/brand";
2import { LandedSha } from "@repo/protocol/ids";3import { Array as Arr, Effect, Option, Schema } from "effect";45export interface GeneratedFile {6 readonly path: string;7 readonly content: string;8}910export interface Managed {11 readonly landed: Option.Option<LandedSha>;12 readonly hash: string;13 readonly body: string;14}1516const hex = (bytes: ArrayBuffer) =>17 [...new Uint8Array(bytes)]18 .map((byte) => byte.toString(16).padStart(2, "0"))19 .join("");2021export const contentHash = (text: string): Effect.Effect<string> =>22 Effect.tryPromise(() =>23 crypto.subtle.digest("SHA-256", new TextEncoder().encode(text))24 ).pipe(25 Effect.orDie,26 Effect.map((digest) => `sha256:${hex(digest)}`)27 );28

Merge build/comments-packages-rest into mainoscabrielbefore adoption38cd503

lines 29–30why, one step back
29// Values are JSON-quoted: a description has colons, and YAML would read a
30// SHA made only of digits as a number.

Merge build/614-env-service: deciders set write-only values for @sensitive items, the public sees the env shape, and checks see only placeholdersoscabrielbefore adoption678c8b8

lines 31–175why, one step back
31const quoted = (value: string) => JSON.stringify(value);
3233export const frontmatter = (input: {34 readonly name: string;35 readonly description: string;36 readonly landed: Option.Option<LandedSha>;37 readonly body: string;38}): Effect.Effect<string> =>39 contentHash(input.body).pipe(40 Effect.map((hash) =>41 [42 "---",43 `name: ${input.name}`,44 `description: ${quoted(input.description)}`,45 "metadata:",46 ` managed-by: ${quoted(Brand.slug)}`,47 ...Option.toArray(input.landed).map(48 (sha) => ` landed: ${quoted(sha)}`49 ),50 ` content-hash: ${quoted(hash)}`,51 "---",52 input.body,53 ].join("\n")54 )55 );5657const OPEN = "---\n";5859const CLOSE = "\n---\n";6061const decodeQuoted = Schema.decodeUnknownOption(62 Schema.fromJsonString(Schema.String)63);6465const valueOf = (raw: string) =>66 raw.startsWith('"') ? decodeQuoted(raw) : Option.some(raw);6768const metadataOf = (head: string) => {69 const lines = head.split("\n");70 const start = lines.indexOf("metadata:");7172 const nested =73 start === -174 ? []75 : Arr.takeWhile(lines.slice(start + 1), (line) => line.startsWith(" "));7677 return new Map(78 nested.flatMap((line) => {79 const { key, raw } =80 /^ {2}(?<key>[a-z-]+): (?<raw>.+)$/u.exec(line)?.groups ?? {};8182 return key === undefined || raw === undefined83 ? []84 : Option.toArray(valueOf(raw)).map((value) => [key, value] as const);85 })86 );87};8889const decodeLanded = Schema.decodeUnknownOption(LandedSha);9091const sections = (file: string) => {92 if (!file.startsWith(OPEN)) {93 return Option.none();94 }9596 const close = file.indexOf(CLOSE, OPEN.length - 1);9798 return close === -199 ? Option.none()100 : Option.some({101 body: file.slice(close + CLOSE.length),102 head: file.slice(OPEN.length, close),103 });104};105106const DESCRIPTION = "description: ";107108export const describedIn = (file: string): Option.Option<string> =>109 Option.flatMap(sections(file), ({ head }) =>110 Arr.findFirst(head.split("\n"), (line) =>111 line.startsWith(DESCRIPTION)112 ).pipe(113 Option.map((line) => line.slice(DESCRIPTION.length).trim()),114 Option.filter((raw) => raw !== ""),115 Option.flatMap(valueOf)116 )117 );118119export const readManaged = (file: string): Option.Option<Managed> => {120 const split = sections(file);121122 if (Option.isNone(split)) {123 return Option.none();124 }125126 const { body, head } = split.value;127 const metadata = metadataOf(head);128 const hash = metadata.get("content-hash");129130 if (metadata.get("managed-by") !== Brand.slug || hash === undefined) {131 return Option.none();132 }133134 return Option.some({135 body,136 hash,137 landed: Option.fromNullishOr(metadata.get("landed")).pipe(138 Option.flatMap(decodeLanded)139 ),140 });141};142143export const isStale = (144 onDisk: string,145 current: GeneratedFile146): Effect.Effect<147 Option.Option<{148 readonly landed: Option.Option<LandedSha>;149 readonly hash: string;150 }>151> =>152 Effect.gen(function* () {153 const copy = readManaged(onDisk);154155 if (Option.isNone(copy)) {156 return onDisk === current.content157 ? Option.none()158 : Option.some({159 hash: yield* contentHash(onDisk),160 landed: Option.none(),161 });162 }163164 const wanted = yield* Option.match(readManaged(current.content), {165 onNone: () => contentHash(current.content),166 onSome: ({ hash }) => Effect.succeed(hash),167 });168169 const { body, hash, landed } = copy.value;170 const actual = yield* contentHash(body);171172 return actual === hash && hash === wanted173 ? Option.none()174 : Option.some({ hash, landed });175 });