The best way to control Claude Code, Codex and more from any computer or phone
| 1 | /** |
| 2 | * Helpers for the `generate` contract tests: running the generator over files |
| 3 | * written to a temporary directory or over the GitHub fixture, importing the |
| 4 | * generated GitHub modules, and reading the emitted text. |
| 5 | * |
| 6 | * The text helpers read the output line by line with indentation and a |
| 7 | * trailing comma stripped, so a test pins the emitted expression for a key |
| 8 | * without pinning the surrounding layout. |
| 9 | */ |
| 10 | import type * as Config from "@effect/graphql-generator/Config" |
| 11 | import * as Generator from "@effect/graphql-generator/Generator" |
| 12 | import * as NodeServices from "@effect/platform-node/NodeServices" |
| 13 | import { assert } from "@effect/vitest" |
| 14 | import * as Effect from "effect/Effect" |
| 15 | import * as FileSystem from "effect/FileSystem" |
| 16 | import * as Path from "effect/Path" |
| 17 | import { fileURLToPath, pathToFileURL } from "node:url" |
| 18 | |
| 19 | export interface Generated { |
| 20 | readonly result: Generator.GenerateResult |
| 21 | /** Output paths relative to `cwd`, with `/` separators, sorted. */ |
| 22 | readonly paths: ReadonlyArray<string> |
| 23 | /** The contents of the output at a `cwd`-relative path. Fails the test if it wasn't emitted. */ |
| 24 | readonly file: (relative: string) => string |
| 25 | } |
| 26 | |
| 27 | const collect = Effect.fnUntraced(function*(cwd: string, config: Config.Config) { |
| 28 | const path = yield* Path.Path |
| 29 | const result = yield* Generator.generate(config, { cwd }) |
| 30 | const byPath = new Map<string, string>() |
| 31 | for (const file of result.files) { |
| 32 | byPath.set(path.relative(cwd, path.resolve(cwd, file.path)).split(path.sep).join("/"), file.contents) |
| 33 | } |
| 34 | const generated: Generated = { |
| 35 | result, |
| 36 | paths: Array.from(byPath.keys()).sort(), |
| 37 | file: (relative) => { |
| 38 | const contents = byPath.get(relative) |
| 39 | assert(contents !== undefined, `expected ${relative} among ${JSON.stringify(Array.from(byPath.keys()))}`) |
| 40 | return contents |
| 41 | } |
| 42 | } |
| 43 | return generated |
| 44 | }) |
| 45 | |
| 46 | /** Writes `inputs` (cwd-relative path to contents) to a fresh temporary directory and generates there. */ |
| 47 | export const generateIn = Effect.fnUntraced(function*(inputs: Readonly<Record<string, string>>, config: Config.Config) { |
| 48 | const fs = yield* FileSystem.FileSystem |
| 49 | const path = yield* Path.Path |
| 50 | const cwd = yield* fs.makeTempDirectoryScoped({ prefix: "graphql-generator-" }) |
| 51 | for (const [relative, body] of Object.entries(inputs)) { |
| 52 | const file = path.join(cwd, relative) |
| 53 | yield* fs.makeDirectory(path.dirname(file), { recursive: true }) |
| 54 | yield* fs.writeFileString(file, body) |
| 55 | } |
| 56 | return yield* collect(cwd, config) |
| 57 | }) |
| 58 | |
| 59 | /** The directory holding the GitHub schema subset and `documents/`. */ |
| 60 | export const githubFixtureDir = fileURLToPath(new URL("../fixtures/github", import.meta.url)) |
| 61 | |
| 62 | /** |
| 63 | * The config the GitHub snapshot set is generated with. The shared module sits |
| 64 | * beside the documents so every emitted file imports its siblings with `./`. |
| 65 | */ |
| 66 | export const githubConfig: Config.Config = { |
| 67 | schema: "./schema.graphql", |
| 68 | documents: ["documents/*.graphql"], |
| 69 | shared: "./documents/shared.graphql.ts", |
| 70 | scalars: { |
| 71 | DateTime: "./documents/scalars.ts#DateTime", |
| 72 | URI: "./documents/scalars.ts#URI", |
| 73 | GitObjectID: "./documents/scalars.ts#GitObjectID" |
| 74 | } |
| 75 | } |
| 76 | |
| 77 | export const generateGitHub = collect(githubFixtureDir, githubConfig) |
| 78 | |
| 79 | const tmpRoot = fileURLToPath(new URL("../.tmp", import.meta.url)) |
| 80 | |
| 81 | /** |
| 82 | * Writes the generated GitHub set to a fresh directory under `test/.tmp`, |
| 83 | * beside a copy of the scalar codecs it imports, and returns the directory. |
| 84 | * The directory is removed when the scope closes. |
| 85 | */ |
| 86 | export const writeGitHub = Effect.gen(function*() { |
| 87 | const fs = yield* FileSystem.FileSystem |
| 88 | const path = yield* Path.Path |
| 89 | const generated = yield* generateGitHub |
| 90 | assertNoErrors(generated) |
| 91 | yield* fs.makeDirectory(tmpRoot, { recursive: true }) |
| 92 | const dir = yield* fs.makeTempDirectoryScoped({ directory: tmpRoot, prefix: "github-" }) |
| 93 | yield* fs.copyFile(path.join(githubFixtureDir, "documents", "scalars.ts"), path.join(dir, "scalars.ts")) |
| 94 | for (const relative of generated.paths) { |
| 95 | yield* fs.writeFileString(path.join(dir, path.basename(relative)), generated.file(relative)) |
| 96 | } |
| 97 | return dir |
| 98 | }) |
| 99 | |
| 100 | /** A client built from an imported GitHub module: its methods and results are untyped. */ |
| 101 | export type UntypedClient = Readonly<Record<string, (...args: ReadonlyArray<any>) => Effect.Effect<any, unknown>>> |
| 102 | |
| 103 | /** |
| 104 | * Generates the GitHub set and imports `file` from it. The generated code is not |
| 105 | * on disk when the tests are typechecked, so the module is untyped, and clients |
| 106 | * built from it with `GraphQLClient.make<never>` are typed as |
| 107 | * {@link UntypedClient}. The snapshot test typechecks the generated code itself. |
| 108 | */ |
| 109 | export const importGitHub = (file: string) => |
| 110 | writeGitHub.pipe( |
| 111 | Effect.flatMap((dir) => Effect.promise((): Promise<any> => import(pathToFileURL(`${dir}/${file}`).href))), |
| 112 | Effect.scoped, |
| 113 | Effect.provide(NodeServices.layer) |
| 114 | ) |
| 115 | |
| 116 | /** The directory holding `sdl/subscriptions.graphql` and its documents under `subscriptions/`. */ |
| 117 | export const fixturesDir = fileURLToPath(new URL("../fixtures", import.meta.url)) |
| 118 | |
| 119 | /** |
| 120 | * The config the subscriptions snapshot set is generated with: the |
| 121 | * hand-written `sdl/subscriptions.graphql` schema, its documents under |
| 122 | * `subscriptions/`, and the shared module beside them. |
| 123 | */ |
| 124 | export const subscriptionsConfig: Config.Config = { |
| 125 | schema: "./sdl/subscriptions.graphql", |
| 126 | documents: ["subscriptions/*.graphql"], |
| 127 | shared: "./subscriptions/shared.graphql.ts" |
| 128 | } |
| 129 | |
| 130 | export const generateSubscriptions = collect(fixturesDir, subscriptionsConfig) |
| 131 | |
| 132 | export const warnings = (generated: Generated) => |
| 133 | generated.result.diagnostics.filter((diagnostic) => diagnostic.severity === "warning") |
| 134 | |
| 135 | export const assertNoErrors = (generated: Generated): void => { |
| 136 | assert.deepStrictEqual( |
| 137 | generated.result.diagnostics.flatMap(({ column, line, message, path, severity }) => |
| 138 | severity === "error" ? [`${path}:${line}:${column} ${message}`] : [] |
| 139 | ), |
| 140 | [] |
| 141 | ) |
| 142 | } |
| 143 | |
| 144 | const lines = (text: string): ReadonlyArray<string> => text.split("\n").map((line) => line.trim()) |
| 145 | |
| 146 | const escapeRegExp = (value: string): string => value.replace(/[.*+?^${}()|[\]\\]/g, "\\$&") |
| 147 | |
| 148 | const memberPattern = (key: string) => new RegExp(`^${escapeRegExp(key)}: (.*?),?$`) |
| 149 | |
| 150 | /** Every expression emitted for the struct key `key`, in file order. */ |
| 151 | export const members = (text: string, key: string): ReadonlyArray<string> => { |
| 152 | const pattern = memberPattern(key) |
| 153 | return lines(text).flatMap((line) => { |
| 154 | const match = pattern.exec(line) |
| 155 | return match === null ? [] : [match[1]!] |
| 156 | }) |
| 157 | } |
| 158 | |
| 159 | const uniqueIndex = (text: string, pattern: RegExp, what: string): number => { |
| 160 | const found = lines(text).flatMap((line, i) => pattern.test(line) ? [i] : []) |
| 161 | assert.strictEqual(found.length, 1, `expected exactly one ${what}`) |
| 162 | return found[0]! |
| 163 | } |
| 164 | |
| 165 | /** The expression emitted for the struct key `key`, which must appear once in the file. */ |
| 166 | export const member = (text: string, key: string): string => { |
| 167 | const index = uniqueIndex(text, memberPattern(key), `member ${key}`) |
| 168 | return memberPattern(key).exec(lines(text)[index]!)![1]! |
| 169 | } |
| 170 | |
| 171 | const docAbove = (text: string, index: number): ReadonlyArray<string> => { |
| 172 | const all = lines(text) |
| 173 | let end = index - 1 |
| 174 | if (end < 0 || !all[end]!.endsWith("*/")) return [] |
| 175 | let start = end |
| 176 | while (start >= 0 && !all[start]!.startsWith("/**")) start-- |
| 177 | assert(start >= 0, "unterminated JSDoc") |
| 178 | if (start === end) return [all[start]!.slice(3, -2).trim()] |
| 179 | end-- |
| 180 | return all.slice(start + 1, end + 1).map((line) => line.replace(/^\*\s?/, "")) |
| 181 | } |
| 182 | |
| 183 | /** The JSDoc lines directly above the struct key `key`, without the comment markers. */ |
| 184 | export const docOf = (text: string, key: string): ReadonlyArray<string> => |
| 185 | docAbove(text, uniqueIndex(text, memberPattern(key), `member ${key}`)) |
| 186 | |
| 187 | const declarationPattern = (name: string) => |
| 188 | new RegExp(`^export (?:const|class|type|declare namespace) ${escapeRegExp(name)}\\b`) |
| 189 | |
| 190 | /** The first line declaring the export `name`. */ |
| 191 | export const declaration = (text: string, name: string): string => { |
| 192 | const line = lines(text).find((line) => declarationPattern(name).test(line)) |
| 193 | assert(line !== undefined, `expected a declaration of ${name}`) |
| 194 | return line |
| 195 | } |
| 196 | |
| 197 | /** Fails unless every name in `names` is first declared in the given order. */ |
| 198 | export const assertDeclaredInOrder = (text: string, names: ReadonlyArray<string>): void => { |
| 199 | const all = lines(text) |
| 200 | const indexed = names.map((name) => { |
| 201 | const index = all.findIndex((line) => declarationPattern(name).test(line)) |
| 202 | assert(index >= 0, `expected a declaration of ${name}`) |
| 203 | return { name, index } |
| 204 | }) |
| 205 | assert.deepStrictEqual(indexed.slice().sort((a, b) => a.index - b.index).map(({ name }) => name), names) |
| 206 | } |
| 207 | |
| 208 | /** The trimmed lines of the file, for whole-line assertions. */ |
| 209 | export const fileLines = lines |
| 210 | |
| 211 | /** |
| 212 | * A small hand-written schema: a mapped (`Timestamp`) and an unmapped |
| 213 | * (`HTML`) custom scalar plus one no operation reaches (`Blob`), and a |
| 214 | * non-null argument with a default. |
| 215 | */ |
| 216 | export const taskSchemaSdl = ` |
| 217 | scalar Timestamp |
| 218 | scalar HTML |
| 219 | scalar Blob |
| 220 | |
| 221 | type Task { |
| 222 | id: ID! |
| 223 | title: String! |
| 224 | done: Boolean! |
| 225 | estimate: Float |
| 226 | due: Timestamp |
| 227 | bodyHTML: HTML! |
| 228 | attachment: Blob |
| 229 | } |
| 230 | |
| 231 | type Query { |
| 232 | tasks(first: Int! = 20): [Task!]! |
| 233 | task(id: ID!): Task |
| 234 | } |
| 235 | ` |
| 236 | |
| 237 | /** The usual layout for `taskSchemaSdl` tests: schema under `schema/`, documents under `src/`. */ |
| 238 | export const taskConfig: Config.Config = { |
| 239 | schema: "./schema/app.graphql", |
| 240 | documents: ["src/**/*.graphql"], |
| 241 | scalars: { |
| 242 | Timestamp: "./scalars.ts#Timestamp" |
| 243 | } |
| 244 | } |
| 245 | |
| 246 | /** Generates `documents` (paths under `src/`) against `taskSchemaSdl`. */ |
| 247 | export const generateTasks = ( |
| 248 | documents: Readonly<Record<string, string>>, |
| 249 | config: Config.Config = taskConfig |
| 250 | ) => generateIn({ "schema/app.graphql": taskSchemaSdl, ...documents }, config) |
| 251 | |
| 252 | /** |
| 253 | * Writes the generated files, in their `cwd`-relative layout, to a scratch |
| 254 | * directory inside the package (so `effect` resolves) and imports the module |
| 255 | * at `relative`. The directory is removed when the scope closes. |
| 256 | */ |
| 257 | export const importGenerated = Effect.fnUntraced(function*(generated: Generated, relative: string) { |
| 258 | const fs = yield* FileSystem.FileSystem |
| 259 | const path = yield* Path.Path |
| 260 | const root = fileURLToPath(new URL("../.tmp", import.meta.url)) |
| 261 | yield* fs.makeDirectory(root, { recursive: true }) |
| 262 | const dir = yield* fs.makeTempDirectoryScoped({ directory: root, prefix: "import-" }) |
| 263 | for (const file of generated.paths) { |
| 264 | const target = path.join(dir, file) |
| 265 | yield* fs.makeDirectory(path.dirname(target), { recursive: true }) |
| 266 | yield* fs.writeFileString(target, generated.file(file)) |
| 267 | } |
| 268 | const url = pathToFileURL(path.join(dir, relative)).href |
| 269 | return yield* Effect.promise(() => import(/* @vite-ignore */ url) as Promise<Record<string, any>>) |
| 270 | }) |