fork of hey-api/openapi-ts because I need some additional things
1import type { AnalysisContext, NodeName, Ref } from '@hey-api/codegen-core';
2import { ref } from '@hey-api/codegen-core';
3
4import { py } from '../../py-compiler';
5import { PyDsl } from '../base';
6
7export type ParamDefaultValue = NodeName | py.Expression | undefined;
8export type ParamFn = (p: ParamPyDsl) => void;
9export type ParamName = NodeName | ParamFn;
10export type ParamType = NodeName | PyDsl<py.Expression> | undefined;
11
12export type ParamCtor = (name: ParamName, fn?: ParamFn) => ParamPyDsl;
13
14export class ParamPyDsl extends PyDsl<py.FunctionParameter> {
15 readonly '~dsl' = 'ParamPyDsl';
16
17 protected _defaultValue?: Ref<ParamDefaultValue>;
18 protected _type?: Ref<ParamType>;
19
20 constructor(name: ParamName, fn?: ParamFn) {
21 super();
22 if (typeof name === 'function') {
23 name(this);
24 } else {
25 this.name.set(name);
26 fn?.(this);
27 }
28 }
29
30 override analyze(ctx: AnalysisContext): void {
31 super.analyze(ctx);
32 ctx.analyze(this.name);
33 ctx.analyze(this._type);
34 ctx.analyze(this._defaultValue);
35 }
36
37 /** Sets the parameter default value. */
38 default(value: ParamDefaultValue): this {
39 this._defaultValue = ref(value);
40 return this;
41 }
42
43 get isValid(): boolean {
44 return !this.missingRequiredCalls().length;
45 }
46
47 /** Sets the parameter type. */
48 type(type: ParamType): this {
49 this._type = ref(type);
50 return this;
51 }
52
53 override toAst() {
54 this.$validate();
55 return py.factory.createFunctionParameter(
56 this.name.toString(),
57 this.$node(this._type),
58 this.$node(this._defaultValue),
59 );
60 }
61
62 $validate(): asserts this {
63 const missing = this.missingRequiredCalls();
64 if (!missing.length) return;
65 throw new Error(`Parameter missing ${missing.join(' and ')}`);
66 }
67
68 private missingRequiredCalls(): ReadonlyArray<string> {
69 const missing: Array<string> = [];
70 if (!this.name.toString()) missing.push('name');
71 return missing;
72 }
73}