Skip to content
Myr

examples.ts

This file

Path

apps/web/src/dev/examples.ts

674 lines · 19.8 KiB · TypeScript

Last changed by

Integrate W5 group A: the dev world opens burrow's migrate as its family, reads the session cookie, and lists when each project last landedoscabrielbefore adoptionf9bd621

History of this file

Take it

Merge build/502-web-dev-backend: the web runs locally over a seeded in-process worldoscabrielbefore adoption4aeb23e

lines 1–26why, one step back
1/**
2 * The dev world's two fictional projects, as files: each one's first push,3 * the files a decider opens each ask with (its ask file, and its check when4 * the check is a file), and the commits its people push. The projects and5 * their people are invented; any likeness to a real one is not meant.6 *7 * `datekit` is a small date library (the people of `examples/datekit`,8 * issue 507): `ines-v` decides everything, `okonkwo` the time zones, and9 * `bram` is a vouched contributor. `burrow` is a six-package monorepo with10 * a legacy helper to migrate away from and a lint count to ratchet down11 * (`examples/burrow`, issue 508), decided by `okafor` and `lin-h`. These are12 * cut-down copies: just enough for every page of the web to have something13 * real to show.14 *15 * A project's rules are its committed `policy.json`, the config folder the16 * `/json` rules evaluator reads, with every ask it will open stated there;17 * an ask opens when a decider lands its files. Each ask file is written18 * from the ask `policy.json` states, as the SDK call a maintainer writes,19 * so the two never disagree.20 */21import { Brand } from "@repo/brand";22import { CheckSpec, RatchetMeasure } from "@repo/protocol/domain/check";23import { Command, SymbolName } from "@repo/protocol/domain/common";24import type { AskKind } from "@repo/protocol/domain/kind";25import { PolicyInput } from "@repo/protocol/domain/policy";26import { AskId, Handle, ProjectName, RepoPath } from "@repo/protocol/ids";

Integrate W5 group A: the dev world opens burrow's migrate as its family, reads the session cookie, and lists when each project last landedoscabrielbefore adoptionf9bd621

line 27why, one step back
27import { Array, Number, Predicate, Schema } from "effect";

Merge build/502-web-dev-backend: the web runs locally over a seeded in-process worldoscabrielbefore adoption4aeb23e

lines 28–482why, one step back
28
29import type { Files } from "./git.ts";3031const dir = Brand.configDir;3233const encodeCheck = Schema.encodeSync(CheckSpec);3435const decodeCheck = Schema.decodeSync(CheckSpec);3637const encodeMeasure = Schema.encodeSync(RatchetMeasure);3839/** What a project's `policy.json` states, as the file holds it. */40type Stated = typeof PolicyInput.Encoded;4142/** One ask as `policy.json` states it. */43type StatedAsk = Stated["asks"][number];4445/** A `policy.json` from what its project states, with every default written out. */46const policyJson = (stated: Stated) =>47 `${JSON.stringify(48 Schema.encodeSync(PolicyInput)(Schema.decodeSync(PolicyInput)(stated)),49 null,50 251 )}\n`;5253/** One file an ask opens with. */54interface AskFile {55 readonly content: string;56 readonly path: RepoPath;57}5859/** The files a decider opens one ask with: its ask file, then its check's file if it has one. */60export type Opening = Array.NonEmptyReadonlyArray<AskFile>;6162/** The args a kind takes for an ask's check, as its ask file passes them (`packages/sdk`'s `kinds`). */63interface KindArgs {64 readonly command?: string;65 readonly count?: string;66 readonly from?: string;67 readonly path?: string;68 readonly ratchet?: string;69 readonly rule?: string;70 readonly to?: string | undefined;71}7273/** A string, or a list of them, as TypeScript source spells it. */74const spelled = (value: string | readonly string[]): string =>75 Predicate.isString(value)76 ? JSON.stringify(value)77 : `[${value.map(spelled).join(", ")}]`;7879/**80 * The args an ask's kind takes for its check, as the ask file spells them.81 * No SDK call states a `SymbolAbsent` check (a migrate's split opens its82 * delete step, issue 506), so that file spells the nearest one: a migrate83 * with no `to`, every use gone.84 */85const checkArgs = (check: StatedAsk["check"]) =>86 CheckSpec.match(decodeCheck(check), {87 LintToZero: ({ command, rule }): KindArgs => ({ command, rule }),88 Migrate: ({ count, from, to }): KindArgs => ({ count, from, to }),89 Ratchet: ({ ratchet }): KindArgs => ({ ratchet }),90 RedThenGreen: ({ path }): KindArgs => ({ path }),91 SymbolAbsent: ({ count, symbol }): KindArgs => ({ count, from: symbol }),92 });9394/** An ask's territory as its file spells it: the repo-wide builder for `.`, else the data itself. */95const territoryOf = ({ module, paths }: StatedAsk["territory"]) =>96 module === "."97 ? `territory.paths(${paths.map(spelled).join(", ")})`98 : `{ module: ${spelled(module)}, paths: ${spelled(paths)} }`;99100/** An ask's file: the SDK call that states `stated`, as its maintainer writes it. */101const askFileOf = (stated: StatedAsk): AskFile => {102 const territory = territoryOf(stated.territory);103104 const passed = Object.entries({105 ...checkArgs(stated.check),106 blockedBy: Array.isReadonlyArrayNonEmpty(stated.blockedBy)107 ? stated.blockedBy108 : undefined,109 current: stated.brief.current,110 mentor: stated.mentor,111 parent: stated.parent,112 reserve: stated.reserve,113 want: stated.brief.want,114 }).flatMap(([key, value]) =>115 value === undefined ? [] : [`${key}: ${spelled(value)}`]116 );117118 const args = [...passed, `territory: ${territory}`].toSorted();119120 const builders = territory.startsWith("territory.")121 ? "kinds, territory"122 : "kinds";123124 return {125 content: [126 `import { ${builders} } from "${Brand.cliPackage}/rules";`,127 "",128 `export default kinds.${stated.kind}.ask({`,129 ...args.map((arg) => ` ${arg},`),130 "});",131 "",132 ].join("\n"),133 path: RepoPath.make(stated.file),134 };135};136137// ------------------------------------------------------------- datekit138139export const datekitPeople = {140 contributor: Handle.make("bram"),141 decider: Handle.make("ines-v"),142 zones: Handle.make("okonkwo"),143} as const;144145const fix = {146 checkKind: "redThenGreen",147 claimers: "vouched",148 finish: "optional",149 name: "fix",150 oneWay: false,151 race: 1,152 requires: ["want", "check", "territory"],153 strength: "assertion",154} satisfies typeof AskKind.Encoded;155156/** One datekit ask: as `policy.json` states it, and the check file it opens with. */157interface DatekitAsk {158 readonly stated: StatedAsk;159 readonly test: AskFile;160}161162/**163 * One datekit ask, from its id, the module file it fixes, its brief and its164 * check's one test (red on main, by an assertion). One held for a newcomer165 * names the maintainer who mentors them. datekit is one package, so every166 * territory is in the repo-wide module, `.`.167 */168const datekitAsk = (input: {169 readonly id: string;170 readonly file: string;171 readonly current: string;172 readonly want: string;173 readonly mentor?: Handle;174 readonly test: {175 readonly imports: readonly string[];176 readonly name: string;177 readonly assertion: string;178 };179}): DatekitAsk => {180 const path = RepoPath.make(`test/asks/${input.id}.test.ts`);181182 const stated: StatedAsk = {183 askedBy: datekitPeople.decider,184 blockedBy: [],185 brief: { current: input.current, want: input.want },186 check: encodeCheck(CheckSpec.cases.RedThenGreen.make({ path })),187 file: `${dir}/asks/${input.id}.ask.ts`,188 id: input.id,189 kind: "fix",190 territory: { module: ".", paths: [`src/${input.file}.ts`] },191 };192193 return {194 stated:195 input.mentor === undefined196 ? stated197 : { ...stated, mentor: input.mentor, reserve: "newcomers" },198 test: {199 content: [200 'import { expect, test } from "bun:test";',201 "",202 ...input.test.imports,203 "",204 `test(${spelled(input.test.name)}, () => {`,205 ` ${input.test.assertion}`,206 "});",207 "",208 ].join("\n"),209 path,210 },211 };212};213214const datekitAsks: readonly DatekitAsk[] = [215 datekitAsk({216 current: "parseISO returns an invalid date for a week date.",217 file: "parse",218 id: "parse-iso-week",219 test: {220 assertion:221 'expect(parseISO("2026-W41-3").toISOString()).toBe("2026-10-07T00:00:00.000Z");',222 imports: ['import { parseISO } from "../../src/parse.ts";'],223 name: "parses an ISO week date",224 },225 want: "parseISO accepts ISO week dates such as 2026-W41-3.",226 }),227 datekitAsk({228 current: 'format prints "11st", "12nd" and "13rd".',229 file: "format",230 id: "format-ordinal",231 // Held for a newcomer, whom its asker mentors.232 mentor: datekitPeople.decider,233 test: {234 assertion: 'expect(format(parseISO("2026-10-11"), "Do")).toBe("11th");',235 imports: [236 'import { format } from "../../src/format.ts";',237 'import { parseISO } from "../../src/parse.ts";',238 ],239 name: "prints the teens as th",240 },241 want: 'format(date, "Do") prints 1st, 2nd, 3rd, 11th, 12th, 13th and 21st.',242 }),243 datekitAsk({244 current: "addMonths(January 31, 1) overflows into March.",245 file: "add",246 id: "add-months-clamp",247 test: {248 assertion:249 'expect(addMonths(parseISO("2026-01-31"), 1).toISOString()).toBe("2026-02-28T00:00:00.000Z");',250 imports: [251 'import { addMonths } from "../../src/add.ts";',252 'import { parseISO } from "../../src/parse.ts";',253 ],254 name: "clamps to the end of February",255 },256 want: "addMonths(January 31, 1) is the last day of February, in leap and common years.",257 }),258 datekitAsk({259 current: "diffInDays counts a day short across the spring change.",260 file: "diff",261 id: "diff-in-days-dst",262 test: {263 assertion:264 'expect(diffInDays(new Date("2026-03-30T00:00:00+02:00"), new Date("2026-03-29T00:00:00+01:00"))).toBe(1);',265 imports: ['import { diffInDays } from "../../src/diff.ts";'],266 name: "counts the spring change as one day",267 },268 want: "diffInDays counts calendar days across a daylight-saving change.",269 }),270];271272const library: Files = new Map([273 [274 "README.md",275 [276 "# datekit",277 "",278 "Small, dependency-free date helpers: parse, format, add and diff.",279 "",280 "A fictional project: it and its people are invented.",281 "",282 ].join("\n"),283 ],284 [285 "package.json",286 `${JSON.stringify(287 {288 license: "MIT",289 name: "datekit",290 scripts: { test: "bun test", typecheck: "tsc --noEmit" },291 type: "module",292 version: "0.4.2",293 },294 null,295 2296 )}\n`,297 ],298 [299 "src/index.ts",300 [301 'export { addMonths } from "./add.ts";',302 'export { diffInDays } from "./diff.ts";',303 'export { format } from "./format.ts";',304 'export { parseISO } from "./parse.ts";',305 'export { inZone } from "./tz.ts";',306 "",307 ].join("\n"),308 ],309 [310 "src/parse.ts",311 [312 "/** An ISO 8601 date (`2026-10-07`) or date-time, read as UTC. */",313 "export const parseISO = (text: string): Date =>",314 ' new Date(text.length === 10 ? text + "T00:00:00Z" : text);',315 "",316 ].join("\n"),317 ],318 [319 "src/format.ts",320 [321 'const pad = (n: number) => String(n).padStart(2, "0");',322 "",323 'const ordinal = (n: number) => String(n) + (["th", "st", "nd", "rd"][n % 10] ?? "th");',324 "",325 "/** `date` in `pattern`: YYYY, MM, DD and Do (the day as an ordinal). */",326 "export const format = (date: Date, pattern: string): string =>",327 " pattern",328 ' .replaceAll("YYYY", String(date.getUTCFullYear()))',329 ' .replaceAll("MM", pad(date.getUTCMonth() + 1))',330 ' .replaceAll("Do", ordinal(date.getUTCDate()))',331 ' .replaceAll("DD", pad(date.getUTCDate()));',332 "",333 ].join("\n"),334 ],335 [336 "src/add.ts",337 [338 "/** `date` moved by whole months. */",339 "export const addMonths = (date: Date, months: number): Date => {",340 " const next = new Date(date);",341 "",342 " next.setUTCMonth(next.getUTCMonth() + months);",343 "",344 " return next;",345 "};",346 "",347 ].join("\n"),348 ],349 [350 "src/diff.ts",351 [352 "const DAY = 86_400_000;",353 "",354 "/** Whole days from `earlier` to `later`. */",355 "export const diffInDays = (later: Date, earlier: Date): number =>",356 " Math.floor((later.getTime() - earlier.getTime()) / DAY);",357 "",358 ].join("\n"),359 ],360 [361 "src/tz.ts",362 [363 "/** `date` as wall-clock parts in an IANA time zone. */",364 "export const inZone = (date: Date, zone: string) =>",365 ' new Intl.DateTimeFormat("en-CA", { dateStyle: "short", timeStyle: "short", timeZone: zone }).format(date);',366 "",367 ].join("\n"),368 ],369 [370 "test/format.test.ts",371 [372 'import { expect, test } from "bun:test";',373 "",374 'import { format } from "../src/format.ts";',375 'import { parseISO } from "../src/parse.ts";',376 "",377 'test("formats a date", () => {',378 ' expect(format(parseISO("2026-10-07"), "YYYY-MM-DD")).toBe("2026-10-07");',379 "});",380 "",381 ].join("\n"),382 ],383 [384 `${dir}/policy.json`,385 policyJson({386 asks: datekitAsks.map(({ stated }) => stated),387 deciders: [388 { handles: [datekitPeople.decider], paths: "**" },389 { handles: [datekitPeople.zones], paths: "src/tz.ts" },390 ],391 functions: { admit: false, opensAlone: false },392 kinds: [fix],393 ratchets: [],394 run: {395 checks: { types: "bun run typecheck" },396 test: "bun test {path}",397 },398 source: "config",399 weakening: { markers: [".skip(", ".only(", ".todo("] },400 }),401 ],402 [403 `${dir}/vouched.td`,404 [405 "# The people datekit's deciders vouch for.",406 datekitPeople.contributor,407 "",408 ].join("\n"),409 ],410]);411412export const datekit = {413 answer: {414 ask: AskId.make("diff-in-days-dst"),415 files: new Map([416 [417 "src/diff.ts",418 [419 "const DAY = 86_400_000;",420 "",421 "/** Whole calendar days from `earlier` to `later`, across any daylight-saving change. */",422 "export const diffInDays = (later: Date, earlier: Date): number =>",423 " Math.round((later.getTime() - earlier.getTime()) / DAY);",424 "",425 ].join("\n"),426 ],427 ]) satisfies Files,428 message: "Count calendar days across a daylight-saving change",429 },430 asks: datekitAsks.map(431 ({ stated, test }) =>432 [AskId.make(stated.id), [askFileOf(stated), test]] as const433 ),434 files: library,435 project: ProjectName.make("datekit"),436 /** A commit someone pushed straight to main, past the platform. */437 stray: {438 files: new Map([439 [440 "README.md",441 [442 "# datekit",443 "",444 "Small, dependency-free date helpers: parse, format, add, diff and time zones.",445 "",446 "A fictional project: it and its people are invented.",447 "",448 ].join("\n"),449 ],450 ]) satisfies Files,451 message: "Mention time zones in the README",452 },453} as const;454455// -------------------------------------------------------------- burrow456457export const burrowPeople = {458 decider: Handle.make("okafor"),459 second: Handle.make("lin-h"),460} as const;461462const PACKAGES = [463 "kit",464 "auth",465 "billing",466 "catalog",467 "notify",468 "search",469] as const;470471const COUNT = "bun scripts/count-callers.ts legacyFetch --json";472473const migrateCheck = encodeCheck(474 CheckSpec.cases.Migrate.make({475 count: Command.make(COUNT),476 from: SymbolName.make("legacyFetch"),477 to: SymbolName.make("http.get"),478 })479);480481const PARENT = "drop-legacy-fetch";482

Integrate W5 group A: the dev world opens burrow's migrate as its family, reads the session cookie, and lists when each project last landedoscabrielbefore adoptionf9bd621

lines 483–488why, one step back
483/**
484 * The one ask burrow's decider opens: the migrate. Its callers sit in all485 * six packages, so the platform opens it as a family (issue 506): a child486 * per package and a delete child waiting on the six, their files written487 * beside the parent's in the same landing.488 */

Merge build/502-web-dev-backend: the web runs locally over a seeded in-process worldoscabrielbefore adoption4aeb23e

lines 489–641why, one step back
489const burrowAsks: readonly StatedAsk[] = [
490 {491 askedBy: burrowPeople.decider,492 blockedBy: [],493 brief: {494 want: "Replace every call to legacyFetch with http.get, then delete legacyFetch.",495 },496 check: migrateCheck,497 file: `${dir}/asks/${PARENT}.ask.ts`,498 id: PARENT,499 kind: "migrate",500 territory: {501 module: ".",502 paths: Array.map(PACKAGES, (pkg) => `packages/${pkg}/**`),503 },504 },505];506507const packageFiles = (pkg: string): readonly (readonly [string, string])[] => [508 [509 `packages/${pkg}/package.json`,510 `${JSON.stringify(511 {512 exports: { ".": "./src/index.ts" },513 name: `@burrow/${pkg}`,514 type: "module",515 },516 null,517 2518 )}\n`,519 ],520 [521 `packages/${pkg}/src/index.ts`,522 pkg === "kit"523 ? [524 "/** The old way to fetch: kept until nothing calls it. */",525 "export const legacyFetch = (url: string) => fetch(url).then((response) => response.json());",526 "",527 "export const http = { get: (url: string) => fetch(url).then((response) => response.json()) };",528 "",529 "let calls = 0;",530 "",531 'export const ping = () => legacyFetch("/kit/ping?n=" + String((calls += 1)));',532 "",533 ].join("\n")534 : [535 'import { legacyFetch } from "@burrow/kit";',536 "",537 "let cache: unknown;",538 "",539 `export const load = async () => (cache ??= await legacyFetch("/${pkg}"));`,540 "",541 ].join("\n"),542 ],543];544545const monorepo: Files = new Map([546 [547 "README.md",548 [549 "# burrow",550 "",551 "Six packages that share a kit, a lint setup and a debt counter.",552 "",553 "A fictional project: it and its people are invented.",554 "",555 ].join("\n"),556 ],557 [558 "package.json",559 `${JSON.stringify(560 {561 name: "burrow",562 private: true,563 scripts: { lint: "oxlint", test: "bun test" },564 workspaces: ["packages/*"],565 },566 null,567 2568 )}\n`,569 ],570 [571 "scripts/count-callers.ts",572 [573 "// Prints how many times each package calls a symbol, as JSON.",574 'import { Glob } from "bun";',575 "",576 "const [symbol] = Bun.argv.slice(2);",577 "const byModule: Record<string, number> = {};",578 "",579 'for await (const path of new Glob("packages/*/src/**/*.ts").scan()) {',580 ' const name = "@burrow/" + path.split("/")[1];',581 " const text = await Bun.file(path).text();",582 "",583 ' byModule[name] = (byModule[name] ?? 0) + (text.split(symbol + "(").length - 1);',584 "}",585 "",586 "const total = Object.values(byModule).reduce((sum, n) => sum + n, 0);",587 "",588 "console.log(JSON.stringify({ byModule, total }));",589 "",590 ].join("\n"),591 ],592 ...PACKAGES.flatMap(packageFiles),593 [594 `${dir}/policy.json`,595 policyJson({596 asks: burrowAsks,597 deciders: [598 {599 handles: [burrowPeople.decider, burrowPeople.second],600 paths: "**",601 },602 ],603 functions: { admit: false, opensAlone: false },604 kinds: [605 {606 checkKind: "migrate",607 claimers: "vouched",608 finish: "never",609 name: "migrate",610 oneWay: false,611 race: 1,612 requires: ["want", "check", "territory"],613 strength: "assertion",614 },615 ],616 ratchets: [617 {618 measure: encodeMeasure(619 RatchetMeasure.cases.Count.make({620 command: Command.make("bun run lint --format json"),621 rule: "burrow/no-module-level-mutable-state",622 })623 ),624 name: "mutable-state",625 },626 ],627 run: { checks: { lint: "bun run lint" }, test: "bun test {path}" },628 source: "config",629 weakening: { markers: [".skip(", ".only(", ".todo("] },630 }),631 ],632 [`${dir}/vouched.td`, "# The people burrow's deciders vouch for.\n"],633]);634635export const burrow = {636 asks: burrowAsks.map(637 (stated) => [AskId.make(stated.id), [askFileOf(stated)]] as const638 ),639 files: monorepo,640 project: ProjectName.make("burrow"),641} as const;

Integrate W5 group A: the dev world opens burrow's migrate as its family, reads the session cookie, and lists when each project last landedoscabrielbefore adoptionf9bd621

lines 642–674why, one step back
642
643/** How many times `text` calls `symbol`, as burrow's `scripts/count-callers.ts` counts. */644const callsIn = (text: string, symbol: string) =>645 text.split(`${symbol}(`).length - 1;646647/** What burrow's count command prints on its first commit: each package's calls of `legacyFetch`. */648const burrowCallers = () => {649 const byModule = Object.fromEntries(650 PACKAGES.map((pkg) => [651 `@burrow/${pkg}`,652 Number.sumAll(653 [...monorepo].flatMap(([path, text]) =>654 path.startsWith(`packages/${pkg}/src/`)655 ? [callsIn(text, "legacyFetch")]656 : []657 )658 ),659 ])660 );661662 return JSON.stringify({663 byModule,664 total: Number.sumAll(Object.values(byModule)),665 });666};667668/**669 * What each count command of the examples prints, by the command: the dev670 * Checker runs none, so a count lane prints this wherever it runs.671 */672export const printedBy: ReadonlyMap<string, string> = new Map([673 [COUNT, burrowCallers()],674]);