|
| 1 | +import fs from 'node:fs/promises' |
| 2 | +import path from 'node:path' |
| 3 | +import { listLambdaHandlers } from '@skyleague/esbuild-lambda' |
| 4 | +import { openapiFromHandlers } from '@skyleague/event-horizon/spec' |
| 5 | +import { globby } from 'globby' |
| 6 | +import type { Argv } from 'yargs' |
| 7 | +import { rootDirectory } from '../../lib/constants.js' |
| 8 | + |
| 9 | +export function builder(yargs: Argv) { |
| 10 | + return yargs |
| 11 | + .option('output', { |
| 12 | + type: 'string', |
| 13 | + }) |
| 14 | + .option('cwd', { |
| 15 | + type: 'string', |
| 16 | + default: rootDirectory, |
| 17 | + coerce: (cwd) => path.join(process.cwd(), cwd), |
| 18 | + }) |
| 19 | +} |
| 20 | + |
| 21 | +export async function handler(argv: ReturnType<typeof builder>['argv']): Promise<void> { |
| 22 | + const { buildDir: _buildDir, artifactDir: _artifactDir, output, cwd } = await argv |
| 23 | + const fnDirs = ['src/**/functions'] |
| 24 | + |
| 25 | + const stacks = await globby(fnDirs, { cwd: cwd, onlyDirectories: true }) |
| 26 | + const handlers = (await Promise.all(stacks.flatMap(async (fnDir) => listLambdaHandlers(path.join(cwd, fnDir))))) |
| 27 | + .flat() |
| 28 | + .map((handler) => path.join(handler, 'index.ts')) |
| 29 | + |
| 30 | + const packageJson = JSON.parse((await fs.readFile(path.join(cwd, 'package.json'))).toString()) |
| 31 | + |
| 32 | + const openapi = openapiFromHandlers( |
| 33 | + Object.fromEntries(await Promise.all(handlers.map(async (handler) => [handler, (await import(handler)).handler]))), |
| 34 | + { info: { title: packageJson.name, version: packageJson.version } }, |
| 35 | + ) |
| 36 | + |
| 37 | + const content = JSON.stringify(openapi, null, 2) |
| 38 | + if (output !== undefined) { |
| 39 | + await fs.writeFile(output, content) |
| 40 | + } else { |
| 41 | + console.log(content) |
| 42 | + } |
| 43 | +} |
| 44 | + |
| 45 | +export default { |
| 46 | + command: 'openapi', |
| 47 | + describe: 'Build OpenAPI', |
| 48 | + builder, |
| 49 | + handler, |
| 50 | +} |
0 commit comments