render.test.ts
This file
Path
packages/drafting/test/render.test.ts
213 lines · 7.0 KiB · TypeScript
Last changed by
Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
History of this fileTake it
Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 1–134why, one step back1import { NodeServices } from "@effect/platform-node";2import { describe, expect, it } from "@effect/vitest";3import { Brand } from "@repo/brand";4import { FinishersFromChecks } from "@repo/project/project";5import { Policy } from "@repo/protocol/domain/policy";6import { AskId, LandedSha, RepoPath } from "@repo/protocol/ids";7import { EvaluationFacts, RulesEvaluator } from "@repo/rules/rules-evaluator";8import type { ConfigBundle } from "@repo/rules/rules-evaluator";9import { RulesEvaluatorBun } from "@repo/rules/rules-evaluator/bun";10import { Array, Effect, FileSystem, Layer, Path, Schema, Struct } from "effect";1112import type { DraftedAsk } from "../src/drafted.ts";13import { draftedFiles, renderAskFile } from "../src/render.ts";1415const exampleUrl = new URL("../../../examples/datekit/", import.meta.url);1617const at = LandedSha.make("a".repeat(40));1819const askFile = (id: string) => `${Brand.configDir}/asks/${id}.ask.ts`;2021const datekitModules = Effect.gen(function* () {22 const fs = yield* FileSystem.FileSystem;23 const path = yield* Path.Path;24 const root = yield* path.fromFileUrl(exampleUrl);25 const dir = path.join(root, Brand.configDir);26 const modules: Record<string, string> = {};2728 for (const file of (yield* fs.readDirectory(dir, {29 recursive: true,30 })).toSorted()) {31 const full = path.join(dir, file);3233 if ((yield* fs.stat(full)).type === "File") {34 modules[`${Brand.configDir}/${file}`] = yield* fs.readFileString(full);35 }36 }3738 return modules;39});4041const asksOf = (modules: Readonly<Record<string, string>>) =>42 Effect.gen(function* () {43 const evaluator = yield* RulesEvaluator;4445 const facts = yield* Schema.decodeEffect(EvaluationFacts)({46 ci: [],47 initializer: "ines-v",48 now: "2026-10-07T12:00:00.000Z",49 project: "datekit",50 seed: 7,51 workspaces: [],52 });5354 const bundle: ConfigBundle = {55 entry: `${Brand.configDir}/project.ts`,56 modules,57 sdkVersion: "0.0.0",58 };5960 const policy = yield* Schema.encodeEffect(Policy)(61 yield* evaluator.evaluate({ at, facts, modules: bundle })62 );6364 return new Map(policy.asks.map((ask) => [ask.id, ask]));65 });6667const evaluator = RulesEvaluatorBun.pipe(68 Layer.provide(Layer.mergeAll(FinishersFromChecks, NodeServices.layer)),69 Layer.provideMerge(NodeServices.layer)70);7172/** A template literal's hole, as text: `$` then `{x}`. */73const hole = ["$", "{x}"].join("");7475const globalHole = ["$", "{globalThis.x}"].join("");7677const test = (id: string) => ({78 path: RepoPath.make(`test/asks/${id}.test.ts`),79 source: 'import { expect, it } from "bun:test";\n',80});8182const formatOrdinal: DraftedAsk = {83 current: "The 11th, 12th and 13th of a month print as 11st, 12nd and 13rd.",84 id: AskId.make("format-ordinal"),85 kind: "fix",86 outOfScope: [87 "Ordinals in languages other than English",88 "Any token other than Do",89 ],90 rationale: "The ordinal suffix ignores the teens.",91 territory: [92 RepoPath.make("src/format.ts"),93 RepoPath.make("test/format.test.ts"),94 ],95 test: test("format-ordinal"),96 want: "The Do token of format prints the day of the month as an English ordinal: 1st, 2nd, 3rd and 4th, 11th, 12th and 13th, then 21st, 22nd, 23rd and 31st.",97};9899const addMonthsClamp: DraftedAsk = {100 context: [101 "addYears adds twelve months, so it follows: February 29 plus a year becomes February 28.",102 ],103 current:104 "addMonths runs over into the next month: January 31 plus one month is March 2 in a leap year and March 3 otherwise.",105 id: AskId.make("add-months-clamp"),106 kind: "fix",107 outOfScope: [108 "addDays and addWeeks, which count exact days",109 "diffInCalendarMonths",110 ],111 rationale: "Month arithmetic overflows short months.",112 territory: [RepoPath.make("src/add.ts"), RepoPath.make("test/add.test.ts")],113 test: test("add-months-clamp"),114 want: "addMonths ends on the last day of the target month when that month is too short for the start date's day, in either direction: January 31 plus one month is February 29 in a leap year and February 28 otherwise. The time of day is kept.",115};116117describe("the rendered ask file", () => {118 it.live(119 "states the same ask as datekit's hand-written files, for the same fields",120 () =>121 Effect.gen(function* () {122 const modules = yield* datekitModules;123 const written = yield* asksOf(modules);124125 const rendered = yield* asksOf({126 ...modules,127 [askFile("add-months-clamp")]: renderAskFile(addMonthsClamp),128 [askFile("format-ordinal")]: renderAskFile(formatOrdinal),129 });130131 expect(rendered.get("add-months-clamp")).toStrictEqual(132 written.get("add-months-clamp")133 );134Merge build/maintainer-wording into mainoscabrielbefore adoption4c1a571
line 135why, one step back135 // A draft never names a mentor or a reserve: a maintainer sets those.Merge branch 'build/908-drafter-workers-ai'oscabrielbefore adoption004e40e
lines 136–213why, one step back136 const ordinal = written.get("format-ordinal");137138 expect(ordinal?.mentor).toBe("okonkwo");139 expect(rendered.get("format-ordinal")).toStrictEqual(140 ordinal === undefined141 ? undefined142 : Struct.omit(ordinal, ["mentor", "reserve"])143 );144 }).pipe(Effect.provide(evaluator)),145 60_000146 );147148 it.live(149 "keeps quotes, backticks and template holes in a want as data",150 () =>151 Effect.gen(function* () {152 const modules = yield* datekitModules;153154 const want = `format("${hole}") prints \`${hole}\` and "quoted" text\\n, then ends; }); process.exit(1); ({`;155156 const asks = yield* asksOf({157 ...modules,158 [askFile("add-months-clamp")]: renderAskFile({159 ...addMonthsClamp,160 context: ["a `tick`", globalHole],161 want,162 }),163 });164165 expect(asks.get("add-months-clamp")?.brief).toStrictEqual({166 context: ["a `tick`", globalHole],167 current: addMonthsClamp.current,168 outOfScope: addMonthsClamp.outOfScope,169 want,170 });171 }).pipe(Effect.provide(evaluator)),172 60_000173 );174175 it("imports the rules by the CLI package's name, keys sorted, nothing the model left out", () => {176 const source = renderAskFile({177 id: AskId.make("iso-week"),178 kind: "fix",179 outOfScope: [],180 rationale: "none",181 territory: [RepoPath.make("src/parse.ts")],182 test: test("iso-week"),183 want: "Week dates parse.",184 });185186 expect(source).toBe(187 [188 `import { kinds, territory } from "${Brand.cliPackage}/rules";`,189 "",190 "export default kinds.fix.ask({",191 ' path: "test/asks/iso-week.test.ts",',192 ' territory: territory.paths("src/parse.ts"),',193 ' want: "Week dates parse.",',194 "});",195 "",196 ].join("\n")197 );198 });199200 it("gives the proposal's two files: the ask file, then the model's test", () => {201 const [ask, check] = draftedFiles(formatOrdinal);202203 expect(ask).toStrictEqual({204 content: renderAskFile(formatOrdinal),205 path: `${Brand.configDir}/asks/format-ordinal.ask.ts`,206 });207 expect(check).toStrictEqual({208 content: formatOrdinal.test.source,209 path: "test/asks/format-ordinal.test.ts",210 });211 expect(Array.length(draftedFiles(formatOrdinal))).toBe(2);212 });213});