fork of hey-api/openapi-ts because I need some additional things
at feat/skip-token 58 lines 1.6 kB view raw
1import type { AnalysisContext } from '@hey-api/codegen-core'; 2import type { MaybeArray } from '@hey-api/types'; 3 4import { py } from '../../ts-python'; 5import { PyDsl } from '../base'; 6import type { PyDslContext } from '../utils/context'; 7import { ctx } from '../utils/context'; 8 9type HintMaybeLazy<T> = ((ctx: PyDslContext) => T) | T; 10export type HintFn = (d: HintPyDsl) => void; 11export type HintLines = HintMaybeLazy<MaybeArray<string>>; 12 13export class HintPyDsl extends PyDsl<py.Comment> { 14 readonly '~dsl' = 'HintPyDsl'; 15 16 protected _lines: Array<HintLines> = []; 17 18 constructor(lines?: HintLines, fn?: HintFn) { 19 super(); 20 if (lines) this.add(lines); 21 fn?.(this); 22 } 23 24 override analyze(ctx: AnalysisContext): void { 25 super.analyze(ctx); 26 } 27 28 add(lines: HintLines): this { 29 this._lines.push(lines); 30 return this; 31 } 32 33 apply<T extends py.Node>(node: T): T { 34 const lines = this._resolveLines(); 35 if (!lines.length) return node; 36 37 const existing = node.leadingComments ? [...node.leadingComments] : []; 38 existing.push(...lines); 39 node.leadingComments = existing; 40 return node; 41 } 42 43 override toAst(): py.Comment { 44 // Return a dummy comment node for compliance. 45 const lines = this._resolveLines(); 46 return py.factory.createComment(lines.join('\n')); 47 } 48 49 private _resolveLines(): Array<string> { 50 return this._lines.reduce((lines: Array<string>, line: HintLines) => { 51 if (typeof line === 'function') line = line(ctx); 52 for (const l of typeof line === 'string' ? [line] : line) { 53 if (l || l === '') lines.push(l); 54 } 55 return lines; 56 }, []); 57 } 58}