@devries-cameron20 / t3code Mirror · read-only
Fork 0

The best way to control Claude Code, Codex and more from any computer or phone

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 286 lines 11.9 KB
Raw
1 /**
2 * The body of `Generator.generate`, plus the parsed-input cache watch mode
3 * passes to it.
4 *
5 * @internal
6 */
7 import * as Data from "effect/Data"
8 import * as Effect from "effect/Effect"
9 import * as FileSystem from "effect/FileSystem"
10 import * as Path from "effect/Path"
11 import type { PlatformError } from "effect/PlatformError"
12 import * as Result from "effect/Result"
13 import type { Config } from "../Config.ts"
14 import type { Diagnostic, GenerateResult } from "../Generator.ts"
15 import type * as Ast from "./Ast.ts"
16 import { type Diagnostic as InternalDiagnostic, make, type Source } from "./Diagnostic.ts"
17 import * as Emitter from "./Emitter.ts"
18 import * as Glob from "./Glob.ts"
19 import * as IntrospectionReader from "./IntrospectionReader.ts"
20 import { parse } from "./Parser.ts"
21 import type * as SchemaModel from "./SchemaModel.ts"
22 import * as SdlReader from "./SdlReader.ts"
23 import * as Validate from "./Validate.ts"
24
25 /**
26 * Parsed inputs that {@link generate} reuses across calls in watch mode. The
27 * schema and each document are parsed again only when their path or contents
28 * change; files are still read on every call.
29 */
30 export interface Cache {
31 schema: {
32 readonly source: Source
33 readonly result: Result.Result<SchemaModel.Schema, InternalDiagnostic>
34 } | undefined
35 documents: Map<string, ParsedDocument>
36 }
37
38 interface ParsedDocument {
39 readonly source: Source
40 readonly file: Emitter.DocumentFile | undefined
41 readonly diagnostics: ReadonlyArray<InternalDiagnostic>
42 }
43
44 export const makeCache = (): Cache => ({ schema: undefined, documents: new Map() })
45
46 const sameSource = (a: Source, b: Source): boolean => a.path === b.path && a.body === b.body
47
48 export class ConfigError extends Data.TaggedError("ConfigError")<{
49 readonly message: string
50 }> {}
51
52 export const generate: (
53 config: Config,
54 options: { readonly cwd: string; readonly cache?: Cache | undefined }
55 ) => Effect.Effect<GenerateResult, ConfigError | PlatformError, FileSystem.FileSystem | Path.Path> = Effect.fnUntraced(
56 function*(config, options) {
57 const fs = yield* FileSystem.FileSystem
58 const path = yield* Path.Path
59 const cwd = path.resolve(options.cwd)
60 const display = (absolute: string): string => path.relative(cwd, absolute).split(path.sep).join("/")
61 const importExtension = config.importExtension ?? ".ts"
62 const failed = (diagnostics: ReadonlyArray<Diagnostic>): GenerateResult => ({ files: [], deletes: [], diagnostics })
63 const cache = options.cache ?? makeCache()
64
65 // Schema
66 const schemaPath = path.resolve(cwd, config.schema)
67 const schemaSource: Source = { path: display(schemaPath), body: yield* fs.readFileString(schemaPath) }
68 if (cache.schema === undefined || !sameSource(cache.schema.source, schemaSource)) {
69 cache.schema = { source: schemaSource, result: readSchema(schemaSource) }
70 }
71 const schemaResult = cache.schema.result
72 if (Result.isFailure(schemaResult)) return failed([toPublic(schemaResult.failure)])
73 const schema = schemaResult.success
74
75 // Output locations and scalar mappings
76 const sharedPath = config.shared === undefined
77 ? schemaPath.replace(/\.(?:graphql|gql|json)$/, "") + ".graphql.ts"
78 : path.resolve(cwd, config.shared)
79 // A `.ts`, `.js` or missing extension becomes `importExtension`; any other extension is kept.
80 const importSpecifier = (from: string, to: string): string => {
81 const relative = path.relative(path.dirname(from), to).split(path.sep).join("/")
82 const specifier = relative.startsWith(".") ? relative : `./${relative}`
83 const extension = path.extname(specifier)
84 return extension === "" || extension === ".ts" || extension === ".js"
85 ? specifier.slice(0, specifier.length - extension.length) + importExtension
86 : specifier
87 }
88 const scalars = yield* resolveScalars(
89 config,
90 schema,
91 (module) =>
92 module.startsWith("./") || module.startsWith("../") || path.isAbsolute(module)
93 ? importSpecifier(sharedPath, path.resolve(cwd, module))
94 : module
95 )
96
97 // Documents
98 const entries = yield* listFiles(fs, path, cwd, config.documents)
99 const documentPaths = uniqueSorted(
100 entries.filter((entry) => entry.glob.matches(entry.relative) && entry.absolute !== schemaPath)
101 )
102 const files: Array<Emitter.DocumentFile> = []
103 const diagnostics: Array<InternalDiagnostic> = []
104 const documents = new Map<string, ParsedDocument>()
105 for (const documentPath of documentPaths) {
106 const source: Source = { path: display(documentPath), body: yield* fs.readFileString(documentPath) }
107 const cached = cache.documents.get(documentPath)
108 const parsed = cached !== undefined && sameSource(cached.source, source)
109 ? cached
110 : parseDocument(path, documentPath, source)
111 documents.set(documentPath, parsed)
112 diagnostics.push(...parsed.diagnostics)
113 if (parsed.file !== undefined) files.push(parsed.file)
114 }
115 cache.documents = documents
116 if (diagnostics.length > 0) return failed(diagnostics.map(toPublic))
117 const sharedClash = (source: Source, what: string): GenerateResult =>
118 failed([toPublic(make(
119 source,
120 0,
121 `The shared module path "${display(sharedPath)}" is also ${what}; choose a different shared path.`
122 ))])
123 const overwritten = sharedPath === schemaPath ? schemaSource : documents.get(sharedPath)?.source
124 if (overwritten !== undefined) return sharedClash(overwritten, "an input file")
125 const collision = files.find((file) => file.outputPath === sharedPath)
126 if (collision !== undefined) return sharedClash(collision.source, "a document output")
127 const validation = Validate.validate(schema, files)
128 if (validation.length > 0) return failed(validation.map(toPublic))
129
130 // Emit
131 const output = Emitter.emit({
132 schema,
133 files,
134 sharedPath,
135 scalars,
136 importSpecifier
137 })
138 if (output.errors.length > 0) return failed(output.errors.map(toPublic))
139 // Only document headers name a source; shared modules are never stale outputs.
140 const outputs = new Set(output.files.map((file) => file.path))
141 const deletes = yield* Effect.filter(
142 uniqueSorted(
143 entries.filter((entry) => /\.(?:graphql|gql)\.ts$/.test(entry.absolute) && !outputs.has(entry.absolute))
144 ),
145 Effect.fnUntraced(function*(absolute) {
146 const source = absolute.slice(0, -".ts".length)
147 if (yield* fs.exists(source)) return false
148 return (yield* fs.readFileString(absolute)).split(/\r?\n/, 1)[0] === Emitter.header(path.basename(source))
149 })
150 )
151 return {
152 files: output.files,
153 deletes,
154 diagnostics: output.unmappedScalars.length === 0 ? [] : [{
155 severity: "warning",
156 path: schemaSource.path,
157 line: undefined,
158 column: undefined,
159 message: `Custom scalars without a mapping decode as Schema.Json: ${
160 output.unmappedScalars.join(", ")
161 }. Map each one to a codec with \`scalars\` in the config.`,
162 codeFrame: undefined
163 }]
164 }
165 }
166 )
167
168 /** Parses one document and keeps only its executable definitions. */
169 const parseDocument = (path: Path.Path, documentPath: string, source: Source): ParsedDocument => {
170 const parsed = parse(source)
171 if (Result.isFailure(parsed)) return { source, file: undefined, diagnostics: [parsed.failure] }
172 const executable: Array<Ast.Definition> = []
173 const diagnostics: Array<InternalDiagnostic> = []
174 for (const definition of parsed.success.definitions) {
175 if (definition._tag === "OperationDefinition" || definition._tag === "FragmentDefinition") {
176 executable.push(definition)
177 } else {
178 const name = "name" in definition ? `"${definition.name.value}"` : "schema"
179 diagnostics.push(make(source, definition.loc.start, `The ${name} definition is not executable.`))
180 }
181 }
182 return {
183 source,
184 file: {
185 source,
186 document: { ...parsed.success, definitions: executable },
187 outputPath: `${documentPath}.ts`,
188 sourceName: path.basename(documentPath)
189 },
190 diagnostics
191 }
192 }
193
194 const toPublic = (diagnostic: InternalDiagnostic): Diagnostic => ({
195 severity: "error",
196 path: diagnostic.path,
197 line: diagnostic.line,
198 column: diagnostic.column,
199 message: diagnostic.message,
200 codeFrame: diagnostic.codeFrame
201 })
202
203 const readSchema = (source: Source): Result.Result<SchemaModel.Schema, InternalDiagnostic> => {
204 if (source.path.endsWith(".json")) return IntrospectionReader.read(source)
205 const document = parse(source)
206 return Result.isFailure(document) ? Result.fail(document.failure) : SdlReader.read(source, document.success)
207 }
208
209 const identifier = /^[A-Za-z_$][A-Za-z0-9_$]*$/
210
211 /** Checks each `scalars` entry against the schema and works out the shared module's import specifier. */
212 const resolveScalars = (
213 config: Config,
214 schema: SchemaModel.Schema,
215 specifierFor: (module: string) => string
216 ): Effect.Effect<ReadonlyMap<string, Emitter.ScalarMapping>, ConfigError> => {
217 const scalars = new Map<string, Emitter.ScalarMapping>()
218 for (const [name, specifier] of Object.entries(config.scalars ?? {})) {
219 const fail = (problem: string) => Effect.fail(new ConfigError({ message: `scalars.${name}: ${problem}` }))
220 const type = schema.types.get(name)
221 if (type === undefined) return fail(`the schema has no type named "${name}".`)
222 if (type._tag !== "ScalarType") return fail(`"${name}" is not a scalar, so it can't be mapped to a codec.`)
223 if (name === "String" || name === "Boolean") return fail(`the built-in ${name} can't be overridden.`)
224 const hash = specifier.lastIndexOf("#")
225 const module = specifier.slice(0, hash)
226 const exportName = specifier.slice(hash + 1)
227 if (module === "" || !identifier.test(exportName)) {
228 return fail(`expected "<module>#<export>" with an identifier after the #, got "${specifier}".`)
229 }
230 scalars.set(name, { specifier: specifierFor(module), exportName })
231 }
232 return Effect.succeed(scalars)
233 }
234
235 interface FileEntry {
236 readonly absolute: string
237 /** The `/`-separated path from the config file. */
238 readonly relative: string
239 readonly glob: Glob.Glob
240 }
241
242 /**
243 * Every file under the `documents` glob roots, once per glob whose root holds
244 * it, skipping `node_modules` and dot-directories. Entries that can't be
245 * stat'ed, such as dangling symlinks, are skipped, and a directory symlinked
246 * inside itself is walked once. An absolute pattern is a `ConfigError`.
247 */
248 const listFiles = Effect.fnUntraced(function*(
249 fs: FileSystem.FileSystem,
250 path: Path.Path,
251 cwd: string,
252 patterns: ReadonlyArray<string>
253 ) {
254 const entries: Array<FileEntry> = []
255 /** The real paths of the directories being walked, to stop at symlink loops. */
256 const ancestors = new Set<string>()
257 const walk = (glob: Glob.Glob, directory: string, relative: string): Effect.Effect<void, PlatformError> =>
258 Effect.gen(function*() {
259 const real = yield* fs.realPath(directory)
260 if (ancestors.has(real)) return
261 ancestors.add(real)
262 for (const entry of (yield* fs.readDirectory(directory)).sort()) {
263 if (Glob.isSkipped(entry)) continue
264 const absolute = path.join(directory, entry)
265 const entryRelative = relative === "" ? entry : `${relative}/${entry}`
266 const info = yield* fs.stat(absolute).pipe(Effect.orElseSucceed(() => undefined))
267 if (info?.type === "Directory") yield* walk(glob, absolute, entryRelative)
268 else if (info?.type === "File") entries.push({ absolute, relative: entryRelative, glob })
269 }
270 ancestors.delete(real)
271 })
272 for (const pattern of patterns) {
273 if (path.isAbsolute(pattern)) {
274 return yield* new ConfigError({
275 message: `documents: "${pattern}" is an absolute path; write patterns relative to the config file.`
276 })
277 }
278 const glob = Glob.make(pattern)
279 const directory = path.join(cwd, glob.root)
280 if (!glob.skipped && (yield* fs.exists(directory))) yield* walk(glob, directory, glob.root)
281 }
282 return entries
283 })
284
285 const uniqueSorted = (entries: ReadonlyArray<FileEntry>): Array<string> =>
286 Array.from(new Set(entries.map((entry) => entry.absolute))).sort()