Repository navigation
Expand file tree
/
Copy pathcodegen.ts
More file actions
349 lines (298 loc) · 14.4 KB
/
Copy pathcodegen.ts
File metadata and controls
349 lines (298 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
import { dirname, resolve } from "node:path"
import ts from "typescript"
const HTTP_DECORATORS = new Map([
["Get", "get"],
["Post", "post"],
["Put", "put"],
["Patch", "patch"],
["Delete", "delete"]
] as const)
type Route = {
httpMethod: string
path: string
result: string
body?: string
query?: string
headers?: string
params: Map<string, string>
}
type Socket = {
path: string
body: string
}
export interface GenerateContractOptions {
module: string
out: string
tsconfig?: string
}
export function generateContract(options: GenerateContractOptions) {
const modulePath = resolve(options.module)
const outPath = resolve(options.out)
const configPath = options.tsconfig
? resolve(options.tsconfig)
: ts.findConfigFile(dirname(modulePath), ts.sys.fileExists, "tsconfig.json")
if (!configPath) throw new Error(`Cannot find tsconfig.json for ${modulePath}`)
const config = ts.readConfigFile(configPath, ts.sys.readFile)
if (config.error) throw diagnosticError(config.error)
const parsed = ts.parseJsonConfigFileContent(config.config, ts.sys, dirname(configPath), undefined, configPath)
if (parsed.errors.length) throw diagnosticError(parsed.errors[0])
const program = ts.createProgram({ rootNames: parsed.fileNames, options: parsed.options })
const checker = program.getTypeChecker()
const source = program.getSourceFile(modulePath)
if (!source) throw new Error(`Module is not included by ${configPath}: ${modulePath}`)
const moduleClass = source.statements.find(
(node): node is ts.ClassDeclaration => ts.isClassDeclaration(node) && decorator(node, "Module") !== undefined
)
if (!moduleClass) throw sourceError(source, source, "No @Module class found")
const moduleDecorator = decorator(moduleClass, "Module")
if (!moduleDecorator) throw sourceError(source, moduleClass, "No @Module class found")
const controllers = moduleControllers(moduleDecorator, checker)
const routes: Route[] = []
const sockets: Socket[] = []
for (const controller of controllers) {
if (!controller.name) throw sourceError(controller.getSourceFile(), controller, "Controller must be named")
const controllerDecorator = decorator(controller, "Controller")
const websocketDecorator = decorator(controller, "Websocket")
if (controllerDecorator) {
const prefix = stringArgument(controllerDecorator.arguments[0], checker)
for (const member of controller.members) {
if (!ts.isMethodDeclaration(member) || !member.name || !ts.isIdentifier(member.name)) continue
const routeDecorator = decorators(member).map(asCall).find(isHttpDecorator)
if (!routeDecorator) continue
const httpMethod = HTTP_DECORATORS.get(decoratorName(routeDecorator) as HttpDecorator)
if (!httpMethod) continue
const route: Route = {
httpMethod,
path: joinPath(
prefix,
routeDecorator.arguments[0] ? stringArgument(routeDecorator.arguments[0], checker) : "/"
),
result: returnType(member, checker),
params: new Map()
}
member.parameters.forEach((parameter) => {
for (const parameterDecorator of decorators(parameter).map(asCall).filter(Boolean) as ts.CallExpression[]) {
switch (decoratorName(parameterDecorator)) {
case "Body":
route.body = nodeType(parameter, checker)
break
case "Query":
route.query = nodeType(parameter, checker)
break
case "Headers":
route.headers = nodeType(parameter, checker)
break
case "Param":
route.params.set(
stringArgument(parameterDecorator.arguments[0], checker),
nodeType(parameter, checker)
)
break
}
}
})
routes.push(route)
}
} else if (websocketDecorator) {
sockets.push({
path: stringArgument(websocketDecorator.arguments[0], checker),
body: nodeType(
controller.members.find(
(member): member is ts.MethodDeclaration =>
ts.isMethodDeclaration(member) && decorator(member, "Message") !== undefined
)?.parameters[1],
checker
)
})
}
}
const output = renderContract(routes, sockets)
ts.sys.createDirectory(dirname(outPath))
ts.sys.writeFile(outPath, output)
return { routes: routes.length, sockets: sockets.length, out: outPath }
}
function renderContract(routes: Route[], sockets: Socket[]) {
const lines = [
"// Generated by better-elysia. Do not edit.",
'import { Elysia, type TSchema } from "elysia"',
"",
"type Schema<T> = TSchema & { static: T }",
"const schema = <T>() => null as unknown as Schema<T>",
"",
"export const contract = new Elysia()"
]
for (const route of routes) {
const options: string[] = []
if (route.body) options.push(`body: schema<${route.body}>()`)
if (route.query) options.push(`query: schema<${route.query}>()`)
if (route.headers) options.push(`headers: schema<${route.headers}>()`)
const pathParams = [...route.path.matchAll(/:([A-Za-z0-9_]+)/g)].map((match) => match[1])
if (pathParams.length || route.path.includes("*")) {
const properties = pathParams.map((name) => {
return `${JSON.stringify(name)}: ${route.params.get(name) ?? "string"}`
})
if (route.path.includes("*")) {
properties.push(`${JSON.stringify("*")}: string`)
}
options.push(`params: schema<{ ${properties.join("; ")} }>()`)
}
lines.push(
` .${route.httpMethod}(${JSON.stringify(route.path)}, () => null as unknown as Awaited<${route.result}>${
options.length ? `, { ${options.join(", ")} }` : ""
})`
)
}
for (const socket of sockets) {
lines.push(` .ws(${JSON.stringify(socket.path)}, { body: schema<${socket.body}>() })`)
}
lines.push("", "export type App = typeof contract", "")
return lines.join("\n")
}
function nodeType(node: ts.Node | undefined, checker: ts.TypeChecker) {
if (!node) return "unknown"
return formatType(checker.typeToString(checker.getTypeAtLocation(node), node, typeFormatFlags))
}
function returnType(method: ts.MethodDeclaration, checker: ts.TypeChecker) {
const signature = checker.getSignatureFromDeclaration(method)
return signature
? formatType(checker.typeToString(checker.getReturnTypeOfSignature(signature), method, typeFormatFlags))
: "unknown"
}
const typeFormatFlags =
ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseFullyQualifiedType | ts.TypeFormatFlags.InTypeAlias
function formatType(value: string) {
const normalized = value.replace(/import\("[^"]*\/node_modules\/elysia\/dist\/[^"/]+"\)/g, 'import("elysia")')
const source = ts.createSourceFile(
"generated-type.ts",
`type Generated = ${normalized}`,
ts.ScriptTarget.Latest,
true,
ts.ScriptKind.TS
)
const declaration = source.statements[0]
if (!ts.isTypeAliasDeclaration(declaration)) return normalized
return canonicalTypeNode(declaration.type, source)
}
const STATUS_RESPONSE = "ElysiaCustomStatusResponse"
function statusName(node: ts.TypeNode, source: ts.SourceFile): string {
// TypeScript 6 LastTypeNode uses qualifier/argument instead of typeName
if (ts.isTypeReferenceNode(node)) return node.typeName.getText(source)
const qualifier = (node as { qualifier?: ts.Node }).qualifier
return qualifier ? qualifier.getText(source) : node.getText(source)
}
function isStatusResponse(node: ts.TypeNode, source: ts.SourceFile) {
return statusName(node, source) === STATUS_RESPONSE
}
function typeReferenceText(node: ts.TypeNode, source: ts.SourceFile): string {
if (ts.isTypeReferenceNode(node)) return node.typeName.getText(source)
// LastTypeNode: import("module").Identifier
const { qualifier, argument } = node as { qualifier?: ts.Node; argument?: ts.Node }
if (qualifier && argument) return `import(${argument.getText(source)}).${qualifier.getText(source)}`
return node.getText(source)
}
function statusCode(node: ts.TypeNode): number {
const typeArguments = (node as { typeArguments?: ts.NodeArray<ts.TypeNode> }).typeArguments
const status = typeArguments?.[2]
if (status && ts.isLiteralTypeNode(status) && ts.isNumericLiteral(status.literal)) {
return Number(status.literal.text)
}
return -Infinity // number | any fallback
}
// Stable-sort ElysiaCustomStatusResponse union members by status code, keeping
// non-status members (undefined, Response, ...) in their original relative position.
type StatusMember = { index: number; code: number | null }
function sortStatusUnion(union: ts.UnionTypeNode, source: ts.SourceFile) {
const members: StatusMember[] = union.types.map((member, index) => ({
index,
code: isStatusResponse(member, source) ? statusCode(member) : null
}))
if (!members.some((member) => member.code !== null)) return
const status = members
.filter((member): member is StatusMember & { code: number } => member.code !== null)
.sort((a, b) => a.code - b.code || a.index - b.index)
const others = members.filter((member) => member.code === null)
const order: number[] = []
let statusIndex = 0
for (const other of others) {
while (statusIndex < status.length && status[statusIndex].index < other.index) order.push(status[statusIndex++].index)
order.push(other.index)
}
while (statusIndex < status.length) order.push(status[statusIndex++].index)
return order.map((index) => canonicalTypeNode(union.types[index], source)).join(" | ")
}
function canonicalTypeNode(node: ts.TypeNode, source: ts.SourceFile): string {
if (ts.isUnionTypeNode(node)) {
const sorted = sortStatusUnion(node, source)
return sorted ?? node.types.map((member) => canonicalTypeNode(member, source)).join(" | ")
}
if (isStatusResponse(node, source)) return node.getText(source)
// Recurse through container generics (Promise, Awaited, ...) so the status
// union nested inside them is sorted, but not through the response body.
const typeArguments = (node as { typeArguments?: ts.NodeArray<ts.TypeNode> }).typeArguments
if (typeArguments?.length) {
return `${typeReferenceText(node, source)}<${typeArguments.map((arg) => canonicalTypeNode(arg, source)).join(", ")}>`
}
return node.getText(source)
}
function moduleControllers(call: ts.CallExpression, checker: ts.TypeChecker) {
const argument = call.arguments[0]
if (!argument || !ts.isObjectLiteralExpression(argument))
throw sourceError(call.getSourceFile(), call, "@Module requires an object literal")
const property = argument.properties.find(
(item): item is ts.PropertyAssignment => ts.isPropertyAssignment(item) && item.name.getText() === "controllers"
)
if (!property || !ts.isArrayLiteralExpression(property.initializer)) {
throw sourceError(call.getSourceFile(), call, "@Module controllers must be an array literal")
}
return property.initializer.elements.map((element) => classDeclaration(element, checker))
}
function classDeclaration(node: ts.Expression, checker: ts.TypeChecker) {
let symbol = checker.getSymbolAtLocation(node)
if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol)
const declaration = symbol?.declarations?.find(ts.isClassDeclaration)
if (!declaration) throw sourceError(node.getSourceFile(), node, "Controller must resolve to a class")
return declaration
}
function stringArgument(node: ts.Expression | undefined, checker: ts.TypeChecker): string {
if (!node) throw new Error("Missing decorator argument")
if (ts.isStringLiteralLike(node)) return node.text
if (ts.isIdentifier(node)) {
let symbol = checker.getSymbolAtLocation(node)
if (symbol && symbol.flags & ts.SymbolFlags.Alias) symbol = checker.getAliasedSymbol(symbol)
const declaration = symbol?.valueDeclaration
if (declaration && ts.isVariableDeclaration(declaration) && declaration.initializer) {
return stringArgument(declaration.initializer, checker)
}
}
throw sourceError(node.getSourceFile(), node, "Decorator path must be a string literal or a resolvable const")
}
function decorators(node: ts.Node) {
return ts.canHaveDecorators(node) ? (ts.getDecorators(node) ?? []) : []
}
function decorator(node: ts.Node, name: string) {
return decorators(node)
.map(asCall)
.find((call) => call && decoratorName(call) === name)
}
function asCall(node: ts.Decorator) {
return ts.isCallExpression(node.expression) ? node.expression : undefined
}
function decoratorName(call: ts.CallExpression) {
return ts.isIdentifier(call.expression) ? call.expression.text : ""
}
type HttpDecorator = typeof HTTP_DECORATORS extends Map<infer K, string> ? K : never
function isHttpDecorator(call: ts.CallExpression | undefined): call is ts.CallExpression {
return !!call && HTTP_DECORATORS.has(decoratorName(call) as HttpDecorator)
}
function joinPath(prefix: string, path: string) {
const normalizedPrefix = prefix === "/" ? "" : prefix.replace(/\/$/, "")
const normalizedPath = path.startsWith("/") ? path : `/${path}`
return normalizedPrefix + normalizedPath
}
function sourceError(source: ts.SourceFile, node: ts.Node, message: string) {
const { line, character } = source.getLineAndCharacterOfPosition(node.getStart(source))
return new Error(`${source.fileName}:${line + 1}:${character + 1} ${message}`)
}
function diagnosticError(diagnostic: ts.Diagnostic) {
return new Error(ts.flattenDiagnosticMessageText(diagnostic.messageText, "\n"))
}