@fern-api/python-dynamic-snippets 4.59.0 → 4.59.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -12,12 +12,12 @@ ${l}`);this.isAtStartOfLine()&&(s=l+s),i&&(s+=`
12
12
  `)}writeSemicolonIfLastCharacterIsNot(){this.lastCharacterIsSemicolon||this.writeInternal(";")}writeNewLineIfLastLineNot(){this.lastCharacterIsNewline||this.writeInternal(`
13
13
  `)}indent(){this.indentLevel++}dedent(){this.indentLevel--}delimit({nodes:t,delimiter:e,writeFunction:i}){if(t.length>0){let a=t[0];a!=null&&i(a);for(let l=1;l<t.length;l++){this.write(e);let s=t[l];s!=null&&i(s)}}}toString(){return this.buffer}writeInternal(t){if(t.length===0)return;let e=!this.lastCharacterIsNewline;this.hasWrittenAnything=!0,this.lastCharacterIsNewline=t.endsWith(`
14
14
  `),this.lastCharacterIsSemicolon=t.endsWith(";");let i=t.split(`
15
- `),a=K&&!this.shouldSkipTracking(i)&&this.lastCharacterIsNewline;e&&(this.lastLine=`${this.lastLine}${i.shift()||""}`),this.lastCharacterIsNewline&&i.pop(),this.lineBuffer.push(...i),a&&this.appendTrackingComment()}set lastLine(t){this.lineBuffer.length>0?this.lineBuffer[this.lineBuffer.length-1]=t:this.lineBuffer.push(t)}get lastLine(){return this.lineBuffer[this.lineBuffer.length-1]||""}shouldSkipTracking(t){return!1}formatStack(t,e=""){return t.map(i=>`${e?`(${e}) `:""} ${i.fn} - ${i.path} : ${i.position}`)}filterStack(t){return t.filter(e=>!e.fn.startsWith(`${this.constructor.name}.`))}appendTrackingComment(){let t=[...this.formatStack(this.filterStack(rt({maxFrames:15,skip:3}))),...this.formatStack(this.filterStack(this.nodeStackFrames),"node")];switch(this.nodeStackFrames.length=0,It){case"single":return this.singleLineTrackingComment(t);case"multiline":return this.multiLineTrackingComment(t);case"box":return this.boxTrackingComment(t)}}singleLineTrackingComment(t){this.lastLine=`${this.lastLine} // ${t.join(" ")}`}multiLineTrackingComment(t){this.lineBuffer.push(...t.map(e=>` // ${e}`))}boxTrackingComment(t){this.lineBuffer.push("/*",...t.map(e=>` ${e}`),"*/")}isAtStartOfLine(){return this.lastCharacterIsNewline||!this.hasWrittenAnything}getIndentString(){return" ".repeat(this.indentLevel*this.getTabSize())}getTabSize(){return Aa}};f();m();d();f();m();d();f();m();d();var $e=class{constructor(){y(this,"reporter");y(this,"snippet");y(this,"err");this.snippet=void 0,this.reporter=void 0,this.err=void 0}update({context:t,snippet:e}){this.shouldUpdate({snippet:e,reporter:t.errors})&&(this.reporter=t.errors.clone(),this.snippet=e)}getResponseOrThrow({endpoint:t}){if(this.snippet!=null&&this.reporter!=null)return{snippet:this.snippet,errors:this.reporter.toDynamicSnippetErrors()};throw this.err??new Error(`Failed to generate snippet for endpoint "${t.method} ${t.path}"`)}shouldUpdate({snippet:t,reporter:e}){return this.reporter==null||this.reporter.size()>0&&e.size()===0?!0:t.length>(this.snippet?.length??0)}};var De=class{constructor(t){y(this,"context");this.context=t}async generate(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a=new $e;for(let l of i){let s=this.context.clone(),b=this.createSnippetGenerator(s);try{let E=await b.generateSnippet({endpoint:l,request:t,options:e});if(s.errors.empty())return{snippet:E,errors:void 0};a.update({context:s,snippet:E})}catch(E){a.err==null&&(a.err=E)}}return a.getResponseOrThrow({endpoint:t.endpoint})}async generateSnippetAst(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a;for(let l of i){let s=this.context.clone(),b=this.createSnippetGenerator(s);try{return await b.generateSnippetAst({endpoint:l,request:t,options:e})}catch(E){a=E}}throw a??new Error(`Failed to generate snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}generateSync(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a=new $e;for(let l of i){let s=this.context.clone(),b=this.createSnippetGenerator(s);try{let E=b.generateSnippetSync({endpoint:l,request:t,options:e});if(s.errors.empty())return{snippet:E,errors:void 0};a.update({context:s,snippet:E})}catch(E){a.err==null&&(a.err=E)}}return a.getResponseOrThrow({endpoint:t.endpoint})}resolveEndpoints({request:t,options:e}){if(e.endpointId!=null){let i=this.context.resolveEndpointById(e.endpointId);if(i==null)throw new Error(`No endpoint found with ID "${e.endpointId}"`);return[i]}return this.context.resolveEndpointLocationOrThrow(t.endpoint)}};f();m();d();f();m();d();f();m();d();var je=class{constructor(){y(this,"REFERENCE_REGEX",/^(?:(\w+)::)?(GET|POST|PUT|DELETE|PATCH|HEAD)\s(\/\S*)$/)}validate(t){return this.REFERENCE_REGEX.test(t)?{type:"valid"}:{type:"invalid"}}tryParse(t){if(this.validate(t).type==="invalid")return;let i=t.match(this.REFERENCE_REGEX);if(!(i==null||i[2]==null||i[3]==null))return{namespace:i[1],method:i[2],path:i[3]}}};f();m();d();var P={Critical:"CRITICAL",Warning:"WARNING"},We=class p{constructor(){y(this,"errors");y(this,"path");this.errors=[],this.path=[]}add(t){this.errors.push({...t,path:[...this.path]})}scope(t){this.path.push(t)}unscope(){this.path.pop()}getBySeverity(t){return this.errors.filter(e=>e.severity===t)}empty(){return this.errors.length===0}size(){return this.errors.length}clone(){let t=new p;return t.errors=[...this.errors],t.path=[...this.path],t}reset(){this.errors=[],this.path=[]}toDynamicSnippetErrors(){return this.errors.map(t=>({severity:t.severity,path:t.path!=null?this.pathToStringArray(t.path):void 0,message:t.message}))}pathToStringArray(t){let e=[];for(let i of t){if(typeof i=="string"){e.push(i);continue}e[e.length-1]+=`[${i.index}]`}return e}};var qe=class{constructor({ir:t,config:e,options:i={}}){y(this,"config");y(this,"options");y(this,"errors");y(this,"_ir");y(this,"httpEndpointReferenceParser");this._ir=t,this.config=e,this.options=i,this.errors=new We,this.httpEndpointReferenceParser=new je}associateQueryParametersByWireValue({parameters:t,values:e}){let i=[];for(let[a,l]of Object.entries(e))if(l!==void 0){this.errors.scope(a);try{let s=t.find(E=>E.name.wireValue===a);if(s==null)throw this.newParameterNotRecognizedError(a);let b=this.isListTypeReference(s.typeReference)&&!Array.isArray(l)?[l]:l;i.push({name:s.name,typeReference:s.typeReference,value:b})}finally{this.errors.unscope()}}return i}associateByWireValueOrDefault({parameters:t,values:e}){let i=[];for(let a of t){this.errors.scope(a.name.wireValue);try{let l=e[a.name.wireValue];if(l==null)if(a.typeReference.type==="primitive"&&a.typeReference.value==="STRING")l=`<${a.name.wireValue}>`;else{this.errors.add({severity:P.Critical,message:this.newParameterNotRecognizedError(a.name.wireValue).message});continue}i.push({name:a.name,typeReference:a.typeReference,value:l})}finally{this.errors.unscope()}}return i}associateByWireValue({parameters:t,values:e,ignoreMissingParameters:i}){let a=[];for(let[l,s]of Object.entries(e))if(s!==void 0){this.errors.scope(l);try{let b=t.find(E=>E.name.wireValue===l);if(b==null){if(i)continue;this.errors.add({severity:P.Critical,message:this.newParameterNotRecognizedError(l).message});continue}a.push({name:b.name,typeReference:b.typeReference,value:s})}finally{this.errors.unscope()}}return a}getExampleObjectProperties({parameters:t,snippetObject:e}){let i=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{},a=[];for(let l of t){let s=i[l.name.wireValue];s==null?l.typeReference.type==="nullable"&&a.push({name:l.name,typeReference:l.typeReference,value:null}):a.push({name:l.name,typeReference:l.typeReference,value:s})}return a}getSingleFileValue({property:t,record:e}){let i=e[t.wireValue];if(i!=null){if(typeof i!="string"){this.errors.add({severity:P.Critical,message:`Expected file value to be a string, got ${typeof i}`});return}return i}}getFileArrayValues({property:t,record:e}){let i=e[t.wireValue];if(i==null)return;if(!Array.isArray(i)){this.errors.add({severity:P.Critical,message:`Expected file array value to be an array of strings, got ${typeof i}`});return}let a=[];for(let l of i){if(typeof l!="string"){this.errors.add({severity:P.Critical,message:`Expected file array value to be an array of strings, got ${typeof l}`});return}a.push(l)}return a}getRecord(t){if(typeof t!="object"||Array.isArray(t)){this.errors.add({severity:P.Critical,message:`Expected object with key, value pairs but got: ${Array.isArray(t)?"array":typeof t}`});return}return t??{}}resolveNamedType({typeId:t}){let e=this._ir.types[t];if(e==null){this.errors.add({severity:P.Critical,message:`Type identified by "${t}" could not be found`});return}return e}resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:e}){let i=this.getRecord(e);if(i==null)return;let a=t.discriminant.wireValue,l=i[a];if(l==null){this.errors.add({severity:P.Critical,message:this.newParameterNotRecognizedError(a).message});return}if(typeof l!="string"){this.errors.add({severity:P.Critical,message:`Expected discriminant value to be a string but got: ${typeof l}`});return}let s=t.types[l];if(s==null){this.errors.add({severity:P.Critical,message:`No type found for discriminant value "${l}"`});return}let{[a]:b,...E}=i;return{singleDiscriminatedUnionType:s,discriminantValue:s.discriminantValue,value:E}}resolveEndpointOrThrow(t){let e=this.httpEndpointReferenceParser.tryParse(t);if(e==null)throw new Error(`Failed to parse endpoint reference "${t}"`);return this.resolveEndpointLocationOrThrow(e)}resolveEndpointLocation(t){let e=[];for(let i of Object.values(this._ir.endpoints))this.parsedEndpointMatches({endpoint:i,parsedEndpoint:t})&&e.push(i);return e}resolveEndpointLocationOrThrow(t){let e=this.resolveEndpointLocation(t);if(e.length===0)throw new Error(`Failed to find endpoint identified by "${t.method} ${t.path}"`);return e}resolveEndpointById(t){return this._ir.endpoints[t]}resolveEndpointByIdOrThrow(t){let e=this.resolveEndpointById(t);if(e==null)throw new Error(`Failed to find endpoint with ID "${t}"`);return e}needsRequestParameter({request:t,inlinePathParameters:e,inlineFileProperties:i}){return this.includePathParametersInWrappedRequest({request:t,inlinePathParameters:e})||t.queryParameters!=null&&t.queryParameters.length>0||t.headers!=null&&t.headers.length>0?!0:t.body!=null?this.includeRequestBodyInWrappedRequest({body:t.body,inlineFileProperties:i}):!t.metadata?.onlyPathParameters}includePathParametersInWrappedRequest({request:t,inlinePathParameters:e}){return e&&(t.metadata?.includePathParameters??!1)}isFileUploadRequestBody(t){switch(t.type){case"fileUpload":return!0;case"properties":case"referenced":return!1;default:C(t)}}resolveEnvironmentName(t){if(this._ir.environments==null)return;let e=this._ir.environments.environments;switch(e.type){case"singleBaseUrl":{let i=e.environments.find(a=>a.id===t);return i?.name}case"multipleBaseUrls":{let i=e.environments.find(a=>a.id===t);return i?.name}default:C(e)}}isSingleEnvironmentID(t){return typeof t=="string"}isMultiEnvironmentValues(t){return typeof t=="object"}validateMultiEnvironmentUrlValues(t){if(this._ir.environments==null)return this.errors.add({severity:P.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;let e=this._ir.environments.environments;switch(e.type){case"singleBaseUrl":return this.errors.add({severity:P.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;case"multipleBaseUrls":{let i=e.environments[0];if(i==null)return this.errors.add({severity:P.Critical,message:"Multiple environments are not supported; use the baseUrl option instead"}),!1;let a=new Set(Oe(i.urls));for(let l of Oe(t))a.has(l)&&a.delete(l);return a.size>0?(this.errors.add({severity:P.Critical,message:`The provided environments are invalid; got: [${Object.keys(t).join(", ")}], expected: [${Oe(i.urls).join(", ")}]`}),!1):!0}}}getValueAsNumber({value:t}){if(typeof t!="number"){this.errors.add({severity:P.Critical,message:this.newTypeMismatchError({expected:"number",value:t}).message});return}return t}getValueAsBoolean({value:t}){if(typeof t!="boolean"){this.errors.add({severity:P.Critical,message:this.newTypeMismatchError({expected:"boolean",value:t}).message});return}return t}getValueAsString({value:t}){if(typeof t!="string"){this.errors.add({severity:P.Critical,message:this.newTypeMismatchError({expected:"string",value:t}).message});return}return t}isOptional(t){switch(t.type){case"nullable":return this.isOptional(t.value);case"optional":return!0;case"named":{let e=this.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.isNullable(e.typeReference):!1}}return!1}isNullable(t){switch(t.type){case"nullable":return!0;case"optional":return this.isNullable(t.value);case"named":{let e=this.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.isNullable(e.typeReference):!1}}return!1}newAuthMismatchError({auth:t,values:e}){return new Error(`Expected auth type ${t.type}, got ${e.type}`)}newParameterNotRecognizedError(t){return new Error(`"${t}" is not a recognized parameter for this endpoint`)}newTypeMismatchError({expected:t,value:e}){return new Error(`Expected ${t}, got ${typeof e}`)}includeRequestBodyInWrappedRequest({body:t,inlineFileProperties:e}){switch(t.type){case"properties":case"referenced":return!0;case"fileUpload":return this.includeFileUploadBodyInWrappedRequest({fileUpload:t,inlineFileProperties:e});default:C(t)}}includeFileUploadBodyInWrappedRequest({fileUpload:t,inlineFileProperties:e}){return this.fileUploadHasBodyProperties({fileUpload:t})||e&&this.fileUploadHasFileProperties({fileUpload:t})}fileUploadHasBodyProperties({fileUpload:t}){return t.properties.some(e=>{switch(e.type){case"file":case"fileArray":return!1;case"bodyProperty":return!0;default:C(e)}})}fileUploadHasFileProperties({fileUpload:t}){return t.properties.some(e=>{switch(e.type){case"file":case"fileArray":return!0;case"bodyProperty":return!1;default:C(e)}})}isListTypeReference(t){return t.type==="optional"?this.isListTypeReference(t.value):t.type==="list"||t.type==="set"}parsedEndpointMatches({endpoint:t,parsedEndpoint:e}){return t.location.method===e.method&&t.location.path===e.path}};f();m();d();var Z={PathParameters:"pathParameters",QueryParameters:"queryParameters",Headers:"headers",RequestBody:"requestBody"};f();m();d();f();m();d();var x={};dt(x,{AccessAttribute:()=>Ee,AstNode:()=>S,Class:()=>se,ClassInstantiation:()=>Te,CodeBlock:()=>ne,Comment:()=>Re,Decorator:()=>Ae,Field:()=>ue,Lambda:()=>Ne,LambdaParameter:()=>Se,Method:()=>le,MethodArgument:()=>Pe,MethodInvocation:()=>Fe,Operator:()=>Ce,Parameter:()=>pe,PythonFile:()=>ke,Reference:()=>Q,StarImport:()=>ce,Type:()=>it,TypeInstantiation:()=>fe,accessAttribute:()=>Ba,assign:()=>Pa,class_:()=>Ca,codeBlock:()=>_a,comment:()=>Va,decorator:()=>La,field:()=>Oa,file:()=>Fa,instantiateClass:()=>ka,invokeFunction:()=>Wa,invokeMethod:()=>qa,lambda:()=>$a,lambdaParameter:()=>Da,method:()=>ja,methodArgument:()=>za,operator:()=>Ha,parameter:()=>Ga,reference:()=>Ua,starImport:()=>Ma});f();m();d();f();m();d();f();m();d();f();m();d();var Ge=class extends Ve{constructor(){super(...arguments);y(this,"fullyQualifiedModulePathsToImportedNames",{})}setRefNameOverrides(e){this.fullyQualifiedModulePathsToImportedNames=e}unsetRefNameOverrides(){this.fullyQualifiedModulePathsToImportedNames={}}getRefNameOverride(e){let i=this.fullyQualifiedModulePathsToImportedNames[e.getFullyQualifiedModulePath()];return i||{name:e.alias??e.name,isAlias:!!e.alias}}toString(){return this.buffer}async toStringFormatted(e){return e.format(this.buffer)}};var S=class extends ye{constructor(){super(...arguments);y(this,"references",[])}addReference(e){this.references.push(e)}inheritReferences(e){e!==void 0&&e.references.forEach(i=>{this.references.includes(i)||this.addReference(i)})}getReferences(){return this.references}toString(){let e=new Ge;return this.write(e),e.toString()}async toStringFormatted(e){let i=new Ge;return this.write(i),i.toStringFormatted(e)}};var Ee=class extends S{constructor({lhs:e,rhs:i}){super();y(this,"lhs");y(this,"rhs");this.lhs=e,this.inheritReferences(e),this.rhs=i,this.inheritReferences(i)}write(e){this.lhs.write(e),e.write("."),this.rhs.write(e)}};f();m();d();var nt=class extends S{constructor({lhs:e,rhs:i}){super();y(this,"lhs");y(this,"rhs");this.lhs=e,this.inheritReferences(e),this.rhs=i,this.inheritReferences(i)}write(e){this.lhs.write(e),e.write(" = "),this.rhs.write(e)}};f();m();d();var be=class extends S{constructor({reference:e,arguments_:i,multiline:a}){super();y(this,"reference");y(this,"arguments");y(this,"multiline");this.reference=e,this.arguments=i,this.multiline=a??!1,this.inheritReferences(e),this.arguments.forEach(l=>{this.inheritReferences(l)})}write(e){if(this.reference.write(e),this.arguments.length===0){e.write("()");return}e.write("("),this.multiline&&(e.newLine(),e.indent()),this.arguments.forEach((i,a)=>{i.write(e),a<this.arguments.length-1&&(e.write(","),this.multiline?e.newLine():e.write(" "))}),this.multiline&&(e.newLine(),e.dedent()),e.write(")")}};f();m();d();var se=class extends S{constructor({docs:e,name:i,extends_:a,decorators:l}){super();y(this,"name");y(this,"extends_");y(this,"decorators");y(this,"fields",[]);y(this,"docs");y(this,"statements",[]);this.name=i,this.extends_=a??[],this.decorators=l??[],this.docs=e,this.extends_.forEach(s=>{this.inheritReferences(s)}),this.decorators.forEach(s=>{this.inheritReferences(s)})}write(e){this.decorators.forEach(i=>{i.write(e)}),e.write(`class ${this.name}`),this.extends_.length>0&&(e.write("("),this.extends_.forEach((i,a)=>{a>0&&e.write(", "),i.write(e)}),e.write(")")),e.write(":"),e.newLine(),e.indent(),this.docs!=null&&(e.write('"""'),e.write(this.docs),e.write('"""')),e.writeNewLineIfLastLineNot(),this.fields.forEach(i=>{i.write(e),e.writeNewLineIfLastLineNot()}),e.dedent(),e.indent(),this.statements.length?this.writeStatements({writer:e}):e.write("pass"),e.dedent()}add(e){this.statements.push(e),this.inheritReferences(e)}writeStatements({writer:e}){this.statements.forEach((i,a)=>{i.write(e),e.writeNewLineIfLastLineNot()})}addField(e){this.add(e)}};f();m();d();var Te=class extends be{constructor({classReference:t,...e}){super({reference:t,...e})}};f();m();d();var ne=class extends S{constructor(e){super();y(this,"arg");this.arg=e}write(e){return new Y(this.arg).write(e)}};f();m();d();var Re=class extends S{constructor({docs:e}){super();y(this,"docs");this.docs=e}write(e){this.docs!=null&&this.docs.split(`
15
+ `),a=K&&!this.shouldSkipTracking(i)&&this.lastCharacterIsNewline;e&&(this.lastLine=`${this.lastLine}${i.shift()||""}`),this.lastCharacterIsNewline&&i.pop(),this.lineBuffer.push(...i),a&&this.appendTrackingComment()}set lastLine(t){this.lineBuffer.length>0?this.lineBuffer[this.lineBuffer.length-1]=t:this.lineBuffer.push(t)}get lastLine(){return this.lineBuffer[this.lineBuffer.length-1]||""}shouldSkipTracking(t){return!1}formatStack(t,e=""){return t.map(i=>`${e?`(${e}) `:""} ${i.fn} - ${i.path} : ${i.position}`)}filterStack(t){return t.filter(e=>!e.fn.startsWith(`${this.constructor.name}.`))}appendTrackingComment(){let t=[...this.formatStack(this.filterStack(rt({maxFrames:15,skip:3}))),...this.formatStack(this.filterStack(this.nodeStackFrames),"node")];switch(this.nodeStackFrames.length=0,It){case"single":return this.singleLineTrackingComment(t);case"multiline":return this.multiLineTrackingComment(t);case"box":return this.boxTrackingComment(t)}}singleLineTrackingComment(t){this.lastLine=`${this.lastLine} // ${t.join(" ")}`}multiLineTrackingComment(t){this.lineBuffer.push(...t.map(e=>` // ${e}`))}boxTrackingComment(t){this.lineBuffer.push("/*",...t.map(e=>` ${e}`),"*/")}isAtStartOfLine(){return this.lastCharacterIsNewline||!this.hasWrittenAnything}getIndentString(){return" ".repeat(this.indentLevel*this.getTabSize())}getTabSize(){return Aa}};f();m();d();f();m();d();f();m();d();var $e=class{constructor(){y(this,"reporter");y(this,"snippet");y(this,"err");this.snippet=void 0,this.reporter=void 0,this.err=void 0}update({context:t,snippet:e}){this.shouldUpdate({snippet:e,reporter:t.errors})&&(this.reporter=t.errors.clone(),this.snippet=e)}getResponseOrThrow({endpoint:t}){if(this.snippet!=null&&this.reporter!=null)return{snippet:this.snippet,errors:this.reporter.toDynamicSnippetErrors()};throw this.err??new Error(`Failed to generate snippet for endpoint "${t.method} ${t.path}"`)}shouldUpdate({snippet:t,reporter:e}){return this.reporter==null||this.reporter.size()>0&&e.size()===0?!0:t.length>(this.snippet?.length??0)}};var De=class{constructor(t){y(this,"context");this.context=t}async generate(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a=new $e;for(let l of i){let s=this.context.clone(),b=this.createSnippetGenerator(s);try{let E=await b.generateSnippet({endpoint:l,request:t,options:e});if(s.errors.empty())return{snippet:E,errors:void 0};a.update({context:s,snippet:E})}catch(E){a.err==null&&(a.err=E)}}return a.getResponseOrThrow({endpoint:t.endpoint})}async generateSnippetAst(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a;for(let l of i){let s=this.context.clone(),b=this.createSnippetGenerator(s);try{return await b.generateSnippetAst({endpoint:l,request:t,options:e})}catch(E){a=E}}throw a??new Error(`Failed to generate snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}generateSync(t,e={}){let i=this.resolveEndpoints({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a=new $e;for(let l of i){let s=this.context.clone(),b=this.createSnippetGenerator(s);try{let E=b.generateSnippetSync({endpoint:l,request:t,options:e});if(s.errors.empty())return{snippet:E,errors:void 0};a.update({context:s,snippet:E})}catch(E){a.err==null&&(a.err=E)}}return a.getResponseOrThrow({endpoint:t.endpoint})}resolveEndpoints({request:t,options:e}){if(e.endpointId!=null){let i=this.context.resolveEndpointById(e.endpointId);if(i==null)throw new Error(`No endpoint found with ID "${e.endpointId}"`);return[i]}return this.context.resolveEndpointLocationOrThrow(t.endpoint)}};f();m();d();f();m();d();f();m();d();var je=class{constructor(){y(this,"REFERENCE_REGEX",/^(?:(\w+)::)?(GET|POST|PUT|DELETE|PATCH|HEAD)\s(\/\S*)$/)}validate(t){return this.REFERENCE_REGEX.test(t)?{type:"valid"}:{type:"invalid"}}tryParse(t){if(this.validate(t).type==="invalid")return;let i=t.match(this.REFERENCE_REGEX);if(!(i==null||i[2]==null||i[3]==null))return{namespace:i[1],method:i[2],path:i[3]}}};f();m();d();var P={Critical:"CRITICAL",Warning:"WARNING"},We=class p{constructor(){y(this,"errors");y(this,"path");this.errors=[],this.path=[]}add(t){this.errors.push({...t,path:[...this.path]})}scope(t){this.path.push(t)}unscope(){this.path.pop()}getBySeverity(t){return this.errors.filter(e=>e.severity===t)}empty(){return this.errors.length===0}size(){return this.errors.length}truncate(t){this.errors.length=t}clone(){let t=new p;return t.errors=[...this.errors],t.path=[...this.path],t}reset(){this.errors=[],this.path=[]}toDynamicSnippetErrors(){return this.errors.map(t=>({severity:t.severity,path:t.path!=null?this.pathToStringArray(t.path):void 0,message:t.message}))}pathToStringArray(t){let e=[];for(let i of t){if(typeof i=="string"){e.push(i);continue}e[e.length-1]+=`[${i.index}]`}return e}};var qe=class{constructor({ir:t,config:e,options:i={}}){y(this,"config");y(this,"options");y(this,"errors");y(this,"_ir");y(this,"httpEndpointReferenceParser");this._ir=t,this.config=e,this.options=i,this.errors=new We,this.httpEndpointReferenceParser=new je}associateQueryParametersByWireValue({parameters:t,values:e}){let i=[];for(let[a,l]of Object.entries(e))if(l!==void 0){this.errors.scope(a);try{let s=t.find(E=>E.name.wireValue===a);if(s==null)throw this.newParameterNotRecognizedError(a);let b=this.isListTypeReference(s.typeReference)&&!Array.isArray(l)?[l]:l;i.push({name:s.name,typeReference:s.typeReference,value:b})}finally{this.errors.unscope()}}return i}associateByWireValueOrDefault({parameters:t,values:e}){let i=[];for(let a of t){this.errors.scope(a.name.wireValue);try{let l=e[a.name.wireValue];if(l==null)if(a.typeReference.type==="primitive"&&a.typeReference.value==="STRING")l=`<${a.name.wireValue}>`;else{this.errors.add({severity:P.Critical,message:this.newParameterNotRecognizedError(a.name.wireValue).message});continue}i.push({name:a.name,typeReference:a.typeReference,value:l})}finally{this.errors.unscope()}}return i}associateByWireValue({parameters:t,values:e,ignoreMissingParameters:i}){let a=[];for(let[l,s]of Object.entries(e))if(s!==void 0){this.errors.scope(l);try{let b=t.find(E=>E.name.wireValue===l);if(b==null){if(i)continue;this.errors.add({severity:P.Critical,message:this.newParameterNotRecognizedError(l).message});continue}a.push({name:b.name,typeReference:b.typeReference,value:s})}finally{this.errors.unscope()}}return a}getExampleObjectProperties({parameters:t,snippetObject:e}){let i=typeof e=="object"&&e!==null&&!Array.isArray(e)?e:{},a=[];for(let l of t){let s=i[l.name.wireValue];s==null?l.typeReference.type==="nullable"&&a.push({name:l.name,typeReference:l.typeReference,value:null}):a.push({name:l.name,typeReference:l.typeReference,value:s})}return a}getSingleFileValue({property:t,record:e}){let i=e[t.wireValue];if(i!=null){if(typeof i!="string"){this.errors.add({severity:P.Critical,message:`Expected file value to be a string, got ${typeof i}`});return}return i}}getFileArrayValues({property:t,record:e}){let i=e[t.wireValue];if(i==null)return;if(!Array.isArray(i)){this.errors.add({severity:P.Critical,message:`Expected file array value to be an array of strings, got ${typeof i}`});return}let a=[];for(let l of i){if(typeof l!="string"){this.errors.add({severity:P.Critical,message:`Expected file array value to be an array of strings, got ${typeof l}`});return}a.push(l)}return a}getRecord(t){if(typeof t!="object"||Array.isArray(t)){this.errors.add({severity:P.Critical,message:`Expected object with key, value pairs but got: ${Array.isArray(t)?"array":typeof t}`});return}return t??{}}resolveNamedType({typeId:t}){let e=this._ir.types[t];if(e==null){this.errors.add({severity:P.Critical,message:`Type identified by "${t}" could not be found`});return}return e}resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:e}){let i=this.getRecord(e);if(i==null)return;let a=t.discriminant.wireValue,l=i[a];if(l==null){this.errors.add({severity:P.Critical,message:this.newParameterNotRecognizedError(a).message});return}if(typeof l!="string"){this.errors.add({severity:P.Critical,message:`Expected discriminant value to be a string but got: ${typeof l}`});return}let s=t.types[l];if(s==null){this.errors.add({severity:P.Critical,message:`No type found for discriminant value "${l}"`});return}let{[a]:b,...E}=i;return{singleDiscriminatedUnionType:s,discriminantValue:s.discriminantValue,value:E}}resolveEndpointOrThrow(t){let e=this.httpEndpointReferenceParser.tryParse(t);if(e==null)throw new Error(`Failed to parse endpoint reference "${t}"`);return this.resolveEndpointLocationOrThrow(e)}resolveEndpointLocation(t){let e=[];for(let i of Object.values(this._ir.endpoints))this.parsedEndpointMatches({endpoint:i,parsedEndpoint:t})&&e.push(i);return e}resolveEndpointLocationOrThrow(t){let e=this.resolveEndpointLocation(t);if(e.length===0)throw new Error(`Failed to find endpoint identified by "${t.method} ${t.path}"`);return e}resolveEndpointById(t){return this._ir.endpoints[t]}resolveEndpointByIdOrThrow(t){let e=this.resolveEndpointById(t);if(e==null)throw new Error(`Failed to find endpoint with ID "${t}"`);return e}needsRequestParameter({request:t,inlinePathParameters:e,inlineFileProperties:i}){return this.includePathParametersInWrappedRequest({request:t,inlinePathParameters:e})||t.queryParameters!=null&&t.queryParameters.length>0||t.headers!=null&&t.headers.length>0?!0:t.body!=null?this.includeRequestBodyInWrappedRequest({body:t.body,inlineFileProperties:i}):!t.metadata?.onlyPathParameters}includePathParametersInWrappedRequest({request:t,inlinePathParameters:e}){return e&&(t.metadata?.includePathParameters??!1)}isFileUploadRequestBody(t){switch(t.type){case"fileUpload":return!0;case"properties":case"referenced":return!1;default:C(t)}}resolveEnvironmentName(t){if(this._ir.environments==null)return;let e=this._ir.environments.environments;switch(e.type){case"singleBaseUrl":{let i=e.environments.find(a=>a.id===t);return i?.name}case"multipleBaseUrls":{let i=e.environments.find(a=>a.id===t);return i?.name}default:C(e)}}isSingleEnvironmentID(t){return typeof t=="string"}isMultiEnvironmentValues(t){return typeof t=="object"}validateMultiEnvironmentUrlValues(t){if(this._ir.environments==null)return this.errors.add({severity:P.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;let e=this._ir.environments.environments;switch(e.type){case"singleBaseUrl":return this.errors.add({severity:P.Critical,message:"Multiple environments are not supported for single base URL environments; use the baseUrl option instead"}),!1;case"multipleBaseUrls":{let i=e.environments[0];if(i==null)return this.errors.add({severity:P.Critical,message:"Multiple environments are not supported; use the baseUrl option instead"}),!1;let a=new Set(Oe(i.urls));for(let l of Oe(t))a.has(l)&&a.delete(l);return a.size>0?(this.errors.add({severity:P.Critical,message:`The provided environments are invalid; got: [${Object.keys(t).join(", ")}], expected: [${Oe(i.urls).join(", ")}]`}),!1):!0}}}getValueAsNumber({value:t}){if(typeof t!="number"){this.errors.add({severity:P.Critical,message:this.newTypeMismatchError({expected:"number",value:t}).message});return}return t}getValueAsBoolean({value:t}){if(typeof t!="boolean"){this.errors.add({severity:P.Critical,message:this.newTypeMismatchError({expected:"boolean",value:t}).message});return}return t}getValueAsString({value:t}){if(typeof t!="string"){this.errors.add({severity:P.Critical,message:this.newTypeMismatchError({expected:"string",value:t}).message});return}return t}isOptional(t){switch(t.type){case"nullable":return this.isOptional(t.value);case"optional":return!0;case"named":{let e=this.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.isNullable(e.typeReference):!1}}return!1}isNullable(t){switch(t.type){case"nullable":return!0;case"optional":return this.isNullable(t.value);case"named":{let e=this.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.isNullable(e.typeReference):!1}}return!1}newAuthMismatchError({auth:t,values:e}){return new Error(`Expected auth type ${t.type}, got ${e.type}`)}newParameterNotRecognizedError(t){return new Error(`"${t}" is not a recognized parameter for this endpoint`)}newTypeMismatchError({expected:t,value:e}){return new Error(`Expected ${t}, got ${typeof e}`)}includeRequestBodyInWrappedRequest({body:t,inlineFileProperties:e}){switch(t.type){case"properties":case"referenced":return!0;case"fileUpload":return this.includeFileUploadBodyInWrappedRequest({fileUpload:t,inlineFileProperties:e});default:C(t)}}includeFileUploadBodyInWrappedRequest({fileUpload:t,inlineFileProperties:e}){return this.fileUploadHasBodyProperties({fileUpload:t})||e&&this.fileUploadHasFileProperties({fileUpload:t})}fileUploadHasBodyProperties({fileUpload:t}){return t.properties.some(e=>{switch(e.type){case"file":case"fileArray":return!1;case"bodyProperty":return!0;default:C(e)}})}fileUploadHasFileProperties({fileUpload:t}){return t.properties.some(e=>{switch(e.type){case"file":case"fileArray":return!0;case"bodyProperty":return!1;default:C(e)}})}isListTypeReference(t){return t.type==="optional"?this.isListTypeReference(t.value):t.type==="list"||t.type==="set"}parsedEndpointMatches({endpoint:t,parsedEndpoint:e}){return t.location.method===e.method&&t.location.path===e.path}};f();m();d();var Z={PathParameters:"pathParameters",QueryParameters:"queryParameters",Headers:"headers",RequestBody:"requestBody"};f();m();d();f();m();d();var x={};dt(x,{AccessAttribute:()=>Ee,AstNode:()=>S,Class:()=>se,ClassInstantiation:()=>Te,CodeBlock:()=>ne,Comment:()=>Re,Decorator:()=>Ae,Field:()=>ue,Lambda:()=>Ne,LambdaParameter:()=>Se,Method:()=>le,MethodArgument:()=>Pe,MethodInvocation:()=>Fe,Operator:()=>Ce,Parameter:()=>pe,PythonFile:()=>ke,Reference:()=>Q,StarImport:()=>ce,Type:()=>it,TypeInstantiation:()=>fe,accessAttribute:()=>Ba,assign:()=>Pa,class_:()=>Ca,codeBlock:()=>_a,comment:()=>Va,decorator:()=>La,field:()=>Oa,file:()=>Fa,instantiateClass:()=>ka,invokeFunction:()=>Wa,invokeMethod:()=>qa,lambda:()=>$a,lambdaParameter:()=>Da,method:()=>ja,methodArgument:()=>za,operator:()=>Ha,parameter:()=>Ga,reference:()=>Ua,starImport:()=>Ma});f();m();d();f();m();d();f();m();d();f();m();d();var Ge=class extends Ve{constructor(){super(...arguments);y(this,"fullyQualifiedModulePathsToImportedNames",{})}setRefNameOverrides(e){this.fullyQualifiedModulePathsToImportedNames=e}unsetRefNameOverrides(){this.fullyQualifiedModulePathsToImportedNames={}}getRefNameOverride(e){let i=this.fullyQualifiedModulePathsToImportedNames[e.getFullyQualifiedModulePath()];return i||{name:e.alias??e.name,isAlias:!!e.alias}}toString(){return this.buffer}async toStringFormatted(e){return e.format(this.buffer)}};var S=class extends ye{constructor(){super(...arguments);y(this,"references",[])}addReference(e){this.references.push(e)}inheritReferences(e){e!==void 0&&e.references.forEach(i=>{this.references.includes(i)||this.addReference(i)})}getReferences(){return this.references}toString(){let e=new Ge;return this.write(e),e.toString()}async toStringFormatted(e){let i=new Ge;return this.write(i),i.toStringFormatted(e)}};var Ee=class extends S{constructor({lhs:e,rhs:i}){super();y(this,"lhs");y(this,"rhs");this.lhs=e,this.inheritReferences(e),this.rhs=i,this.inheritReferences(i)}write(e){this.lhs.write(e),e.write("."),this.rhs.write(e)}};f();m();d();var nt=class extends S{constructor({lhs:e,rhs:i}){super();y(this,"lhs");y(this,"rhs");this.lhs=e,this.inheritReferences(e),this.rhs=i,this.inheritReferences(i)}write(e){this.lhs.write(e),e.write(" = "),this.rhs.write(e)}};f();m();d();var be=class extends S{constructor({reference:e,arguments_:i,multiline:a}){super();y(this,"reference");y(this,"arguments");y(this,"multiline");this.reference=e,this.arguments=i,this.multiline=a??!1,this.inheritReferences(e),this.arguments.forEach(l=>{this.inheritReferences(l)})}write(e){if(this.reference.write(e),this.arguments.length===0){e.write("()");return}e.write("("),this.multiline&&(e.newLine(),e.indent()),this.arguments.forEach((i,a)=>{i.write(e),a<this.arguments.length-1&&(e.write(","),this.multiline?e.newLine():e.write(" "))}),this.multiline&&(e.newLine(),e.dedent()),e.write(")")}};f();m();d();var se=class extends S{constructor({docs:e,name:i,extends_:a,decorators:l}){super();y(this,"name");y(this,"extends_");y(this,"decorators");y(this,"fields",[]);y(this,"docs");y(this,"statements",[]);this.name=i,this.extends_=a??[],this.decorators=l??[],this.docs=e,this.extends_.forEach(s=>{this.inheritReferences(s)}),this.decorators.forEach(s=>{this.inheritReferences(s)})}write(e){this.decorators.forEach(i=>{i.write(e)}),e.write(`class ${this.name}`),this.extends_.length>0&&(e.write("("),this.extends_.forEach((i,a)=>{a>0&&e.write(", "),i.write(e)}),e.write(")")),e.write(":"),e.newLine(),e.indent(),this.docs!=null&&(e.write('"""'),e.write(this.docs),e.write('"""')),e.writeNewLineIfLastLineNot(),this.fields.forEach(i=>{i.write(e),e.writeNewLineIfLastLineNot()}),e.dedent(),e.indent(),this.statements.length?this.writeStatements({writer:e}):e.write("pass"),e.dedent()}add(e){this.statements.push(e),this.inheritReferences(e)}writeStatements({writer:e}){this.statements.forEach((i,a)=>{i.write(e),e.writeNewLineIfLastLineNot()})}addField(e){this.add(e)}};f();m();d();var Te=class extends be{constructor({classReference:t,...e}){super({reference:t,...e})}};f();m();d();var ne=class extends S{constructor(e){super();y(this,"arg");this.arg=e}write(e){return new Y(this.arg).write(e)}};f();m();d();var Re=class extends S{constructor({docs:e}){super();y(this,"docs");this.docs=e}write(e){this.docs!=null&&this.docs.split(`
16
16
  `).forEach(i=>{e.writeLine(`# ${i}`)})}};f();m();d();var Ae=class extends S{constructor({callable:e}){super();y(this,"callable");this.callable=e,this.inheritReferences(e)}write(e){e.write("@"),this.callable.write(e),e.newLine()}};f();m();d();var ue=class extends S{constructor({name:e,type:i,initializer:a,docs:l}){super();y(this,"name");y(this,"type");y(this,"initializer");y(this,"docs");this.name=e,this.type=i,this.initializer=a,this.docs=l,this.inheritReferences(this.type),this.inheritReferences(this.initializer)}write(e){e.write(this.name),this.type!==void 0&&(e.write(": "),this.type.write(e)),this.initializer!==void 0&&(e.write(" = "),this.initializer.write(e)),this.docs!=null&&(e.newLine(),e.write('"""'),e.newLine(),e.write(this.docs),e.newLine(),e.write('"""'))}};f();m();d();var Ne=class extends S{constructor({parameters:e,body:i}){super();y(this,"parameters");y(this,"body");this.parameters=e??[],this.body=i,this.inheritReferences(i)}write(e){e.write("lambda"),this.parameters&&this.parameters.length&&(e.write(" "),this.parameters.forEach((i,a)=>{i.write(e),a<this.parameters.length-1&&e.write(", ")})),e.write(": "),this.body.write(e)}};f();m();d();f();m();d();var pe=class extends S{constructor({name:e,type:i,initializer:a}){super();y(this,"name");y(this,"initializer");y(this,"type");this.name=e,this.type=i,this.initializer=a}write(e){e.write(this.name),this.type&&(e.write(": "),this.type.write(e)),this.initializer!==void 0&&(e.write(" = "),this.initializer.write(e))}};var Se=class extends pe{constructor({name:t,initializer:e}){super({name:t,initializer:e,type:void 0})}};f();m();d();var Be;(function(p){p[p.STATIC=0]="STATIC",p[p.INSTANCE=1]="INSTANCE",p[p.CLASS=2]="CLASS"})(Be||(Be={}));var le=class extends S{constructor({static_:e,name:i,parameters:a,return_:l,docstring:s,type:b,decorators:E}){super();y(this,"name");y(this,"return");y(this,"docstring");y(this,"type");y(this,"parameters");y(this,"decorators");y(this,"statements",[]);y(this,"static_");this.name=i,this.parameters=a??[],this.return=l,this.docstring=s,this.type=b,this.decorators=E??[],this.static_=e??!1,this.parameters.forEach(A=>{this.inheritReferences(A)}),this.inheritReferences(this.return),this.decorators.forEach(A=>{this.inheritReferences(A)}),this.statements.forEach(A=>{this.inheritReferences(A)})}addStatement(e){this.statements.push(e),this.inheritReferences(e)}write(e){this.static_&&this.decorators.push(x.decorator({callable:x.codeBlock("staticmethod")})),this.decorators.forEach(l=>{l.write(e)}),this.type===Be.CLASS?x.decorator({callable:new ne("classmethod")}).write(e):this.type===Be.STATIC&&x.decorator({callable:new ne("staticmethod")}).write(e),e.write(`def ${this.name}(`);let a=this.parameters.length>3;a&&(e.newLine(),e.indent()),this.type===Be.INSTANCE?(e.write("self"),this.parameters.length>0&&(e.write(a?",":", "),a&&e.newLine())):this.type===Be.CLASS&&(e.write("cls"),this.parameters.length>0&&(e.write(a?",":", "),a&&e.newLine())),this.parameters.forEach((l,s)=>{l.write(e),s<this.parameters.length-1&&(e.write(a?",":", "),a&&e.newLine())}),a&&(e.write(","),e.dedent(),e.newLine()),e.write(")"),this.return&&(e.write(" -> "),this.return.write(e)),e.write(":"),e.newLine(),this.docstring&&(e.indent(),e.write('"""'),e.write(this.docstring),e.write('"""'),e.newLine(),e.dedent()),this.statements.length?(e.indent(),this.statements.forEach((l,s)=>{l.write(e),s<this.statements.length-1&&e.newLine()}),e.dedent()):(e.indent(),e.write("pass"),e.dedent()),e.newLine()}};f();m();d();var Pe=class extends S{constructor({name:e,value:i}){super();y(this,"name");y(this,"value");this.name=e,this.value=i,this.inheritReferences(this.value)}write(e){this.name!==void 0&&(e.write(this.name),e.write("=")),this.value.write(e)}};f();m();d();var Fe=class extends S{constructor({on:e,method:i,arguments_:a,multiline:l}){super();y(this,"on");y(this,"method");y(this,"arguments");y(this,"multiline");this.on=e,this.method=i,this.arguments=a,this.multiline=l??!1,this.inheritReferences(e),this.arguments.forEach(s=>{this.inheritReferences(s)})}write(e){if(this.on.write(e),e.write("."),e.write(this.method),this.arguments.length===0){e.write("()");return}e.write("("),this.multiline&&(e.newLine(),e.indent()),this.arguments.forEach((i,a)=>{i.write(e),a<this.arguments.length-1&&(e.write(","),this.multiline?e.newLine():e.write(" "))}),this.multiline&&(e.newLine(),e.dedent()),e.write(")")}};f();m();d();f();m();d();var X={Or:"or",And:"and",Add:"add",Subtract:"subtract",Multiply:"multiple",Divide:"divide",Modulo:"modulo",LeftShift:"leftShift",RightShift:"rightShift"};var Ce=class extends S{constructor({operator:e,lhs:i,rhs:a}){super();y(this,"operator");y(this,"lhs");y(this,"rhs");this.operator=e,this.lhs=i,this.inheritReferences(i),this.rhs=a,this.inheritReferences(a)}getOperatorString(){switch(this.operator){case X.Or:return"or";case X.And:return"and";case X.Add:return"+";case X.Subtract:return"-";case X.Multiply:return"*";case X.Divide:return"/";case X.Modulo:return"%";case X.LeftShift:return"<<";case X.RightShift:return">>";default:C(this.operator)}}write(e){this.lhs.write(e),e.write(" "),e.write(this.getOperatorString()),e.write(" "),this.rhs.write(e)}};f();m();d();f();m();d();function ui(p){if(!p)return"Class";let t=p.replace(/[^a-zA-Z0-9\s_-]/g," ").replace(/[-_\s]+/g," ").trim();return!t||/^\d+$/.test(t)?"Class"+(t||""):(/^\d/.test(t)&&(t="Class"+t),t.split(/(?=[A-Z])|[-_\s]+/).filter(i=>i.length>0).map(i=>i.split(/(?<=\d)(?=[a-zA-Z])|(?<=[a-zA-Z])(?=\d)/).filter(a=>a.length>0)).flat().map((i,a)=>a===0&&/^\d/.test(i)?"Class"+i.charAt(0).toUpperCase()+i.slice(1).toLowerCase():i.length>1&&i===i.toUpperCase()&&!/^\d+$/.test(i)?i:i.charAt(0).toUpperCase()+i.slice(1).toLowerCase()).join(""))}f();m();d();f();m();d();var Q=class extends S{constructor({name:e,modulePath:i,genericTypes:a,alias:l,attribute:s}){super();y(this,"name");y(this,"modulePath");y(this,"genericTypes");y(this,"alias");y(this,"attribute");this.name=e,this.modulePath=i??[],this.genericTypes=a??[],this.alias=l,this.attribute=s??[],this.references.push(this),this.genericTypes.forEach(b=>{this.inheritReferences(b)})}write(e){let i=e.getRefNameOverride(this);e.write(i.name),this.genericTypes.length>0&&(e.write("["),this.genericTypes.forEach((a,l)=>{l>0&&e.write(", "),a.write(e)}),e.write("]")),this.attribute.length>0&&(e.write("."),this.attribute.forEach((a,l)=>{l>0&&e.write("."),e.write(a)}))}getFullyQualifiedPath(){return this.modulePath.join(".")}getFullyQualifiedModulePath(){return`${this.getFullyQualifiedPath()}.${this.name}`}};var ce=class extends Q{constructor({modulePath:e}){super({name:"*",modulePath:e});y(this,"docs")}write(e){throw new Error("Not intended to be written outside the context of a PythonFile.")}};var ke=class extends S{constructor({path:e,statements:i,isInitFile:a=!1,comments:l,imports:s}){super();y(this,"path");y(this,"isInitFile");y(this,"statements",[]);y(this,"comments");this.path=e,this.isInitFile=a,i?.forEach(b=>this.addStatement(b)),this.comments=l??[],s?.forEach(b=>this.addReference(b))}addStatement(e){this.statements.push(e),this.inheritReferences(e)}write(e){let i=this.deduplicateReferences();this.updateWriterRefNameOverrides({writer:e,uniqueReferences:i}),this.writeComments(e),this.writeImports({writer:e,uniqueReferences:i}),this.statements.forEach((a,l)=>{a.write(e),e.newLine(),l<this.statements.length-1&&e.newLine()}),e.unsetRefNameOverrides()}updateWriterRefNameOverrides({writer:e,uniqueReferences:i}){let a=new Map(i),l={},s=this.getInitialUsedNames(),b=this.path.join("."),E=i.get(b);if(E){let{references:R}=E;R.forEach(F=>{let $=F.getFullyQualifiedModulePath(),T=F.name;l[$]={name:T,isAlias:!1},s.add(F.name)}),a.delete(b)}Array.from(a.values()).flatMap(({references:R})=>R).forEach(R=>{if(R instanceof ce)return;let F=R.alias??R.name,$=R.getFullyQualifiedModulePath(),T=F,N=R.modulePath.length-1,k=!!R.alias;for(;s.has(T);){k=!0;let M=R.modulePath[N];N<0||!M?T=`_${T}`:T=`${ui(M)}${T}`,N--}s.add(T),l[$]={name:T,isAlias:k}}),e.setRefNameOverrides(l)}getInitialUsedNames(){let e=new Set;return this.statements.forEach(i=>{(i instanceof se||i instanceof le||i instanceof ue)&&e.add(i.name)}),e}deduplicateReferences(){let e=new Map;for(let i of this.references){let a=i.name,l=i.getFullyQualifiedPath();if(l==="")continue;let s=e.get(l);s?s.referenceNames.has(a)||(s.references.push(i),s.referenceNames.add(a)):e.set(l,{modulePath:i.modulePath,references:[i],referenceNames:new Set([a])})}return e}writeComments(e){this.comments.forEach(i=>{i.write(e)}),this.comments.length>0&&e.newLine()}getImportName({writer:e,reference:i}){let a=e.getRefNameOverride(i),l=i.name,s=a.isAlias?a.name:void 0;return`${l}${s?` as ${s}`:""}`}writeImports({writer:e,uniqueReferences:i}){if(i.size!==0){for(let[a,{modulePath:l,references:s}]of i){let b=l;if(!this.isDefinedInFile(b)){if(b[0]===this.path[0]){let E=0;for(;E<this.path.length&&E<b.length&&this.path[E]===b[E];)E++;let A=this.path.length-E;this.isInitFile&&A++;let R=A>0?".".repeat(A):".";R+=b.slice(E).join("."),e.write(`from ${R} import ${s.map(F=>this.getImportName({writer:e,reference:F})).join(", ")}`)}else e.write(`from ${a} import ${s.map(E=>this.getImportName({writer:e,reference:E})).join(", ")}`);e.newLine()}}e.newLine()}}isDefinedInFile(e){return e.length===this.path.length&&e.every((i,a)=>i===this.path[a])}};f();m();d();var it=class extends S{constructor(e){super();y(this,"internalType");this.internalType=e}write(e){switch(this.internalType.type){case"int":e.write("int");break;case"float":e.write("float");break;case"bool":e.write("bool");break;case"str":e.write("str");break;case"bytes":e.write("bytes");break;case"list":e.write("List["),this.internalType.value.write(e),e.write("]");break;case"set":e.write("Set["),this.internalType.value.write(e),e.write("]");break;case"tuple":e.write("Tuple["),this.internalType.values.forEach((i,a)=>{a>0&&e.write(", "),i.write(e)}),e.write("]");break;case"dict":e.write("Dict["),this.internalType.keyType.write(e),e.write(", "),this.internalType.valueType.write(e),e.write("]");break;case"none":e.write("None");break;case"uuid":e.write("UUID");break;case"optional":e.write("Optional["),this.internalType.value.write(e),e.write("]");break;case"union":e.write("Union["),this.internalType.values.forEach((i,a)=>{a>0&&e.write(", "),i.write(e)}),e.write("]");break;case"any":e.write("Any");break;case"reference":this.internalType.value.write(e);break;case"datetime":e.write("datetime");break;case"literal":typeof this.internalType.value=="string"?e.write(`Literal["${this.internalType.value}"]`):e.write(`Literal[${this.internalType.value}]`);break;default:C(this.internalType)}}static int(){return new this({type:"int"})}static float(){return new this({type:"float"})}static bool(){return new this({type:"bool"})}static str(){return new this({type:"str"})}static bytes(){return new this({type:"bytes"})}static list(e){let i=new this({type:"list",value:e});return i.addReference(x.reference({name:"List",modulePath:["typing"]})),i.inheritReferences(e),i}static set(e){let i=new this({type:"set",value:e});return i.addReference(x.reference({name:"Set",modulePath:["typing"]})),i.inheritReferences(e),i}static tuple(e){let i=new this({type:"tuple",values:e});return i.addReference(x.reference({name:"Tuple",modulePath:["typing"]})),e.forEach(a=>i.inheritReferences(a)),i}static dict(e,i){let a=new this({type:"dict",keyType:e,valueType:i});return a.addReference(x.reference({name:"Dict",modulePath:["typing"]})),a.inheritReferences(e),a.inheritReferences(i),a}static none(){return new this({type:"none"})}static uuid(){let e=new this({type:"uuid"});return e.addReference(x.reference({name:"UUID",modulePath:["uuid"]})),e}static optional(e){if(this.isAlreadyOptional(e))return e;let i=new this({type:"optional",value:e});return i.addReference(x.reference({name:"Optional",modulePath:["typing"]})),i.inheritReferences(e),i}static union(e){let i=new this({type:"union",values:e});return i.addReference(x.reference({name:"Union",modulePath:["typing"]})),e.forEach(a=>i.inheritReferences(a)),i}static any(){let e=new this({type:"any"});return e.addReference(x.reference({name:"Any",modulePath:["typing"]})),e}static datetime(){let e=new this({type:"datetime"});return e.addReference(x.reference({name:"datetime",modulePath:["datetime"]})),e}static reference(e){let i=new this({type:"reference",value:e});return i.addReference(e),i}static literal(e){let i=new this({type:"literal",value:e});return i.addReference(x.reference({name:"Literal",modulePath:["typing"]})),i}static isAlreadyOptional(e){return e.internalType.type==="optional"}};f();m();d();var fe=class p extends S{constructor(e){super();y(this,"internalType");this.internalType=e}static int(e){return new this({type:"int",value:e})}static float(e){return new this({type:"float",value:e})}static bool(e){return new this({type:"bool",value:e})}static str(e,i={multiline:!1,startOnNewLine:!1,endWithNewLine:!1}){return new this({type:"str",value:e,config:i})}static bytes(e){return new this({type:"bytes",value:e})}static list(e,i={endWithComma:!1}){let a=new this({type:"list",values:e,config:i});return e.forEach(l=>a.inheritReferences(l)),a}static set(e,i={endWithComma:!1}){let a=new this({type:"set",values:e,config:i});return e.forEach(l=>a.inheritReferences(l)),a}static tuple(e,i={endWithComma:!1}){let a=new this({type:"tuple",values:e,config:i});return e.forEach(l=>a.inheritReferences(l)),a}static typedDict(e,i={endWithComma:!1}){let a=new this({type:"typedDict",entries:e,config:i});return e.forEach(l=>a.inheritReferences(l.value)),a}static date(e){let i=new this({type:"date",value:e});return i.addReference(new Q({name:"date",modulePath:["datetime"]})),i}static datetime(e){let i=new this({type:"datetime",value:e});return i.addReference(new Q({name:"datetime",modulePath:["datetime"]})),i}static dict(e,i={endWithComma:!1}){let a=new this({type:"dict",entries:e,config:i});return e.forEach(l=>{a.inheritReferences(l.key),a.inheritReferences(l.value)}),a}static reference(e){let i=new this({type:"reference",value:e});return i.inheritReferences(e),i}static none(){return new this({type:"none"})}static unknown(e){return new this({type:"unknown",value:e})}static uuid(e){let i=new this({type:"uuid",value:e});return i.addReference(new Q({name:"UUID",modulePath:["uuid"]})),i}static nop(){return new this({type:"nop"})}static isNop(e){return e instanceof p&&e.internalType.type==="nop"}isTypedDict(){return this.internalType.type==="typedDict"}asTypedDictOrThrow(){if(this.isTypedDict())return this.internalType;throw new Error("Internal error; python.TypeInstantiation is not a TypedDict")}write(e){switch(this.internalType.type){case"int":e.write(this.internalType.value.toString());break;case"float":e.write(this.internalType.value.toString());break;case"bool":this.internalType.value?e.write("True"):e.write("False");break;case"str":if(this.internalType.config?.multiline){let{startOnNewLine:i,endWithNewLine:a}=this.internalType.config;this.writeStringWithTripleQuotes({writer:e,value:this.internalType.value,startOnNewLine:i,endWithNewLine:a})}else e.write(`"${this.escapeString(this.internalType.value)}"`);break;case"date":e.write(`date.fromisoformat("${this.internalType.value}")`);break;case"datetime":{let i=this.internalType.value.replace(/Z$/,"+00:00");e.write(`datetime.fromisoformat("${i}")`);break}case"bytes":e.write(`b"${this.internalType.value}"`);break;case"list":{let i=this.internalType,a=Tt({values:i.values});if(a.length===0){e.write("[]");break}e.write("["),i.config?.multiline&&(e.newLine(),e.indent()),a.forEach((l,s)=>{s>0&&(e.write(","),i.config?.multiline?e.newLine():e.write(" ")),l.write(e),s===a.length-1&&i.config?.endWithComma&&e.write(",")}),i.config?.multiline&&(e.newLine(),e.dedent()),e.write("]");break}case"set":{let i=this.internalType,a=Tt({values:i.values});if(a.length===0){e.write("{}");break}e.write("{"),i.config?.multiline&&(e.newLine(),e.indent()),a.forEach((l,s)=>{s>0&&(e.write(","),i.config?.multiline?e.newLine():e.write(" ")),l.write(e),s===a.length-1&&i.config?.endWithComma&&e.write(",")}),i.config?.multiline&&(e.newLine(),e.dedent()),e.write("}");break}case"tuple":{let i=this.internalType,a=Tt({values:i.values});if(a.length===0){e.write("()");break}e.write("("),i.config?.multiline&&(e.newLine(),e.indent()),a.forEach((l,s)=>{s>0&&(e.write(","),i.config?.multiline?e.newLine():e.write(" ")),l.write(e),(a.length===1||s===a.length-1&&i.config?.endWithComma)&&e.write(",")}),i.config?.multiline&&(e.newLine(),e.dedent()),e.write(")");break}case"dict":{let i=this.internalType,a=Na({entries:i.entries});if(a.length===0){e.write("{}");break}e.write("{"),i.config?.multiline&&(e.newLine(),e.indent()),a.forEach((l,s)=>{s>0&&(e.write(","),i.config?.multiline?e.newLine():e.write(" ")),l.key.write(e),e.write(": "),l.value.write(e),s===a.length-1&&i.config?.endWithComma&&e.write(",")}),i.config?.multiline&&(e.newLine(),e.dedent()),e.write("}");break}case"typedDict":{let i=this.internalType,a=Sa({entries:i.entries});if(a.length===0){e.write("{}");break}e.write("{"),i.config?.multiline&&(e.writeLine(),e.indent()),a.forEach((l,s)=>{s>0&&(e.write(","),i.config?.multiline?e.newLine():e.write(" ")),e.write(`"${l.name}": `),l.value.write(e)}),i.config?.multiline&&(e.newLine(),e.dedent()),e.write("}");break}case"reference":{this.internalType.value.write(e);break}case"none":e.write("None");break;case"unknown":this.writeUnknown({writer:e,value:this.internalType.value});break;case"uuid":e.write(`UUID("${this.internalType.value}")`);break;case"nop":break;default:C(this.internalType)}}writeStringWithTripleQuotes({writer:e,value:i,startOnNewLine:a,endWithNewLine:l}){e.write('"""');let s=i.split(`
17
17
  `);if(s.length<=1){e.write(this.escapeString(s[0]??"")),e.write('"""');return}a&&e.writeNoIndent(`\\
18
18
  `),s.forEach((b,E)=>{e.writeNoIndent(this.escapeString(b)),E===s.length-1?l&&e.writeNoIndent(`\\
19
19
  `):e.writeNoIndent(`
20
- `)}),e.writeNoIndent('"""')}escapeString(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r")}writeUnknown({writer:e,value:i}){switch(typeof i){case"boolean":e.write(i?"True":"False");return;case"string":e.write(`"${this.escapeString(i)}"`);return;case"number":e.write(i.toString());return;case"object":if(i==null){e.write("None");return}if(Array.isArray(i)){this.writeUnknownArray({writer:e,value:i});return}this.writeUnknownObject({writer:e,value:i});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof i}`)}}writeUnknownArray({writer:e,value:i}){if(i.length===0){e.write("[]");return}e.writeLine("["),e.indent();for(let a of i)e.writeNode(p.unknown(a)),e.writeLine(",");e.dedent(),e.write("]")}writeUnknownObject({writer:e,value:i}){let a=Object.entries(i);if(a.length===0){e.write("{}");return}e.writeLine("{"),e.indent();for(let[l,s]of a)e.write(`"${l}": `),e.writeNode(p.unknown(s)),e.writeLine(",");e.dedent(),e.write("}")}};function Na({entries:p}){return p.filter(t=>!fe.isNop(t.key)&&!fe.isNop(t.value))}function Sa({entries:p}){return p.filter(t=>!fe.isNop(t.value))}function Tt({values:p}){return p.filter(t=>!fe.isNop(t))}function Ba(p){return new Ee(p)}function Pa(p){return new nt(p)}function Fa(p){return new ke(p)}function Ca(p){return new se(p)}function ka(p){return new Te(p)}function La(p){return new Ae(p)}function Ua(p){return new Q(p)}function Ma(p){return new ce(p)}function Oa(p){return new ue(p)}function _a(p){return new ne(p)}function Va(p){return new Re(p)}function $a(p){return new Ne(p)}function Da(p){return new Se(p)}function ja(p){return new le(p)}function Wa(p){return new be(p)}function qa(p){return new Fe(p)}function Ga(p){return new pe(p)}function za(p){return new Pe(p)}function Ha(p){return new Ce(p)}f();m();d();var Qa="value",ot=class{constructor({context:t}){y(this,"context");this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?x.TypeInstantiation.none():(this.context.errors.add({severity:P.Critical,message:"Expected non-null value, but got null"}),x.TypeInstantiation.nop());if(t.value===void 0)return x.TypeInstantiation.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let e=this.context.resolveNamedType({typeId:t.typeReference.value});return e==null?x.TypeInstantiation.nop():this.convertNamed({named:e,value:t.value,as:t.as})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value});case"unknown":return x.TypeInstantiation.unknown(t.value);default:C(t.typeReference)}}convertLiteral({literalType:t,value:e}){switch(t.type){case"boolean":{let i=this.context.getValueAsBoolean({value:e});return i==null?x.TypeInstantiation.nop():x.TypeInstantiation.bool(i)}case"string":{let i=this.context.getValueAsString({value:e});return i==null?x.TypeInstantiation.nop():x.TypeInstantiation.str(i)}default:C(t)}}convertList({list:t,value:e}){return Array.isArray(e)?x.TypeInstantiation.list(e.map((i,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}}),{multiline:!0}):(this.context.errors.add({severity:P.Critical,message:`Expected array but got: ${typeof e}`}),x.TypeInstantiation.nop())}convertSet({set:t,value:e}){return Array.isArray(e)?x.TypeInstantiation.list(e.map((i,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}}),{multiline:!0}):(this.context.errors.add({severity:P.Critical,message:`Expected array but got: ${typeof e}`}),x.TypeInstantiation.nop())}convertMap({map:t,value:e}){return typeof e!="object"||e==null?(this.context.errors.add({severity:P.Critical,message:`Expected object but got: ${e==null?"null":typeof e}`}),x.TypeInstantiation.nop()):x.TypeInstantiation.dict(Object.entries(e).map(([i,a])=>{this.context.errors.scope(i);try{return{key:this.convert({typeReference:t.key,value:i,as:"key"}),value:this.convert({typeReference:t.value,value:a})}}finally{this.context.errors.unscope()}}),{multiline:!0})}convertNamed({named:t,value:e,as:i}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:e,as:i});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:e});case"enum":return this.convertEnum({enum_:t,value:e});case"object":return this.convertObject({object_:t,value:e});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:e});default:C(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:e}){let i=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:e});if(i==null)return x.TypeInstantiation.nop();let a=i.singleDiscriminatedUnionType,l=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:i,unionVariant:a});if(l==null)return x.TypeInstantiation.nop();let s={name:this.context.getPropertyName(t.discriminant.name),value:x.TypeInstantiation.str(a.discriminantValue.wireValue)};return x.TypeInstantiation.typedDict([s,...l],{multiline:!0})}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:e}){let i=this.getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:e});switch(e.type){case"samePropertiesAsObject":{let a=this.context.resolveNamedType({typeId:e.typeId});if(a==null)return;let l=this.convertNamed({named:a,value:t.value});if(!l.isTypedDict()){this.context.errors.add({severity:P.Critical,message:"Internal error; expected union value to be an object"});return}let s=l.asTypedDictOrThrow();return[...i,...s.entries]}case"singleProperty":try{this.context.errors.scope(e.discriminantValue.wireValue);let a=this.context.getRecord(t.value);return a==null?[...i,{name:Qa,value:this.convert({typeReference:e.typeReference,value:t.value})}]:[...i,{name:this.context.getPropertyName(e.discriminantValue.name),value:this.convert({typeReference:e.typeReference,value:a[e.discriminantValue.wireValue]})}]}finally{this.context.errors.unscope()}case"noProperties":return i;default:C(e)}}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:e}){return this.context.associateByWireValue({parameters:e.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert(a)}}finally{this.context.errors.unscope()}})}convertObject({object_:t,value:e}){let i=this.context.associateByWireValue({parameters:t.properties,values:this.context.getRecord(e)??{}});return x.TypeInstantiation.typedDict(i.map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert(a)}}finally{this.context.errors.unscope()}}),{multiline:!0})}convertEnum({enum_:t,value:e}){let i=this.getEnumValue({enum_:t,value:e});return i==null?x.TypeInstantiation.nop():x.TypeInstantiation.str(i)}getEnumValue({enum_:t,value:e}){if(typeof e!="string"){this.context.errors.add({severity:P.Critical,message:`Expected enum value string, got: ${typeof e}`});return}if(t.values.find(a=>a.wireValue===e)==null){this.context.errors.add({severity:P.Critical,message:`An enum value named "${e}" does not exist in this context`});return}return e}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:e}){let i=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:e});return i??x.TypeInstantiation.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:e}){for(let i of t.types)try{let a=this.convert({typeReference:i,value:e});if(x.TypeInstantiation.isNop(a))continue;return a}catch{continue}this.context.errors.add({severity:P.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof e}" value`})}convertPrimitive({primitive:t,value:e,as:i}){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":{let a=this.getValueAsNumber({value:e,as:i});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.int(a)}case"FLOAT":case"DOUBLE":{let a=this.getValueAsNumber({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.float(a)}case"BOOLEAN":{let a=this.getValueAsBoolean({value:e,as:i});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.bool(a)}case"BASE_64":case"BIG_INTEGER":case"STRING":{let a=this.context.getValueAsString({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.str(a)}case"UUID":{let a=this.context.getValueAsString({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.uuid(a)}case"DATE":{let a=this.context.getValueAsString({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.date(a)}case"DATE_TIME":{let a=this.context.getValueAsString({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.datetime(a)}default:C(t)}}getValueAsNumber({value:t,as:e}){let i=e==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:i})}getValueAsBoolean({value:t,as:e}){let i=e==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:i})}};f();m();d();var at=class{constructor({context:t}){y(this,"context");this.context=t}getFilePropertyInfo({body:t,value:e}){let i={fileFields:[],bodyPropertyFields:[]},a=this.context.getRecord(e)??{};for(let l of t.properties)switch(l.type){case"file":{let s=this.getSingleFileProperty({property:l,record:a});if(x.TypeInstantiation.isNop(s))break;i.fileFields.push({name:this.context.getPropertyName(l.name),value:s});break}case"fileArray":{let s=this.getArrayFileProperty({property:l,record:a});if(x.TypeInstantiation.isNop(s))break;i.fileFields.push({name:this.context.getPropertyName(l.name),value:s});break}case"bodyProperty":{let s=this.getBodyProperty({property:l,record:a});if(x.TypeInstantiation.isNop(s))break;i.bodyPropertyFields.push({name:this.context.getPropertyName(l.name.name),value:s});break}default:C(l)}return i}getSingleFileProperty({property:t,record:e}){let i=this.context.getSingleFileValue({property:t,record:e});return i==null&&(i=`example_${t.wireValue??"file"}`),this.context.getFileFromString(i)}getArrayFileProperty({property:t,record:e}){let i=this.context.getFileArrayValues({property:t,record:e});if(i==null){let a=`example_${t.wireValue??"files"}`;return x.TypeInstantiation.list([this.context.getFileFromString(a)])}return x.TypeInstantiation.list(i.map(a=>this.context.getFileFromString(a)))}getBodyProperty({property:t,record:e}){let i=e[t.name.wireValue];return i==null?x.TypeInstantiation.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:i})}};var Ya=["list","set"],st=class p extends qe{constructor({ir:e,config:i}){super({ir:e,config:i});y(this,"ir");y(this,"customConfig");y(this,"dynamicTypeLiteralMapper");y(this,"filePropertyMapper");this.ir=e,this.customConfig=i.customConfig??{},this.dynamicTypeLiteralMapper=new ot({context:this}),this.filePropertyMapper=new at({context:this})}clone(){return new p({ir:this.ir,config:this.config})}getClassName(e){let i=e.pascalCase.safeName,a=this.getRootClientClassName();return i===a?`${a}Model`:i}getTypedDictClassName(e){return`${this.getClassName(e)}Params`}getPropertyName(e){let i=e.snakeCase.safeName;return i.startsWith("_")?"f_"+i.substring(i.lastIndexOf("_")+1):i}getMethodName(e){return Ya.includes(e.snakeCase.unsafeName)?e.snakeCase.unsafeName:e.snakeCase.safeName}getRootClientClassReference(){return x.reference({name:this.getRootClientClassName(),modulePath:this.getRootModulePath()})}getRootClientClassName(){return this.customConfig.client?.exported_class_name!=null?this.customConfig.client.exported_class_name:this.customConfig.client_class_name!=null?this.customConfig.client_class_name:this.customConfig.client?.class_name!=null?this.customConfig.client.class_name:this.pascalCase(this.config.organization)+this.pascalCase(this.config.workspaceName)}getEnvironmentClassName(){return`${this.getRootClientClassName()}Environment`}getEnvironmentTypeReferenceFromID(e){let i=this.resolveEnvironmentName(e);if(i!=null)return x.accessAttribute({lhs:this.getEnvironmentClassReference(),rhs:x.codeBlock(this.getEnvironmentEnumName(i))})}getEnvironmentClassReference(){return x.reference({name:this.getEnvironmentClassName(),modulePath:this.getEnvironmentModulePath()})}getEnvironmentEnumName(e){return e.screamingSnakeCase.safeName}isPrimitive(e){switch(e.type){case"primitive":return!0;case"optional":case"nullable":return this.isPrimitive(e.value);case"named":{let i=this.resolveNamedType({typeId:e.value});if(i==null)return!1;switch(i.type){case"alias":return this.isPrimitive(i.typeReference);case"discriminatedUnion":case"undiscriminatedUnion":case"object":case"enum":return!1;default:C(i)}break}case"list":case"set":case"map":case"literal":case"unknown":return!1;default:C(e)}}getFileFromString(e){return x.TypeInstantiation.str(e)}getRootModulePath(){if(this.customConfig.package_name!=null)return[this.customConfig.package_name];let e=this.cleanOrganizationName();return this.customConfig.use_api_name_in_package?[e,this.getApiName()]:[e]}getCoreModulePath(){return this.getRootModulePath().concat("core")}getEnvironmentModulePath(){return this.getRootModulePath().concat("environment")}shouldInlinePathParameters(){return!0}cleanOrganizationName(){return this.config.organization.replace(/[^a-zA-Z0-9]/g,"_")}getApiName(){return vt(this.config.workspaceName)}pascalCase(e){let i=wt(e);return i.charAt(0).toUpperCase()+i.slice(1)}};f();m();d();var Za={type:"primitive",value:"STRING"},Ja=["example"],pi="client",ze="request",ut=class{constructor({context:t}){y(this,"context");this.context=t}async generateSnippet({endpoint:t,request:e}){return this.buildPythonFile({endpoint:t,snippet:e}).toString()}generateSnippetSync({endpoint:t,request:e}){return this.buildPythonFile({endpoint:t,snippet:e}).toString()}async generateSnippetAst({endpoint:t,request:e}){return this.buildPythonFile({endpoint:t,snippet:e})}generateMethodCallSnippetAst({endpoint:t,request:e}){return this.callMethod({endpoint:t,snippet:e})}buildPythonFile({endpoint:t,snippet:e}){return x.file({path:Ja,statements:[this.constructClient({endpoint:t,snippet:e}),this.callMethod({endpoint:t,snippet:e})]})}constructClient({endpoint:t,snippet:e}){return x.assign({lhs:x.reference({name:pi}),rhs:x.instantiateClass({classReference:this.context.getRootClientClassReference(),arguments_:this.getConstructorArgs({endpoint:t,snippet:e}).map(i=>x.methodArgument({name:i.name,value:i.value})),multiline:!0})})}getConstructorArgs({endpoint:t,snippet:e}){let i=[],a=this.getConstructorEnvironmentArgs({baseUrl:e.baseURL,environment:e.environment});return a.length>0&&i.push(...a),t.auth!=null&&(e.auth!=null?i.push(...this.getConstructorAuthArgs({auth:t.auth,values:e.auth})):this.context.errors.add({severity:P.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(Z.PathParameters),this.context.ir.pathParameters!=null&&i.push(...this.getPathParameters({namedParameters:this.context.ir.pathParameters,snippet:e})),this.context.errors.unscope(),this.context.errors.scope(Z.Headers),this.context.ir.headers!=null&&e.headers!=null&&i.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:e.headers})),this.context.errors.unscope(),i}getConstructorEnvironmentArgs({baseUrl:t,environment:e}){let i=this.getEnvironmentValue({baseUrl:t,environment:e});return i==null?[]:e!=null&&this.context.isMultiEnvironmentValues(e)?[{name:"environment",value:i}]:[{name:this.getEnvironmentOptionName({environment:e}),value:i}]}getEnvironmentValue({baseUrl:t,environment:e}){if(t!=null&&e!=null){this.context.errors.add({severity:P.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return x.TypeInstantiation.str(t);if(e!=null){if(this.context.isSingleEnvironmentID(e)){let i=this.context.getEnvironmentTypeReferenceFromID(e);if(i==null){this.context.errors.add({severity:P.Warning,message:`Environment ${JSON.stringify(e)} was not found`});return}return x.TypeInstantiation.reference(i)}if(this.context.isMultiEnvironmentValues(e))return this.context.validateMultiEnvironmentUrlValues(e)?x.TypeInstantiation.reference(x.instantiateClass({classReference:this.context.getEnvironmentClassReference(),arguments_:Object.entries(e).map(([i,a])=>({name:i,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:Za,value:a})})).map(i=>x.methodArgument({name:i.name,value:i.value})),multiline:!0})):void 0}}getConstructorAuthArgs({auth:t,values:e}){switch(t.type){case"basic":return e.type!=="basic"?(this.addAuthMismatchError(t,e),[]):this.getConstructorBasicAuthArg({auth:t,values:e});case"bearer":return e.type!=="bearer"?(this.addAuthMismatchError(t,e),[]):this.getConstructorBearerAuthArgs({auth:t,values:e});case"header":return e.type!=="header"?(this.addAuthMismatchError(t,e),[]):this.getConstructorHeaderAuthArgs({auth:t,values:e});case"oauth":return e.type!=="oauth"?(this.addAuthMismatchError(t,e),[]):this.getConstructorOAuthArgs({auth:t,values:e});case"inferred":return e.type!=="inferred"?(this.addAuthMismatchError(t,e),[]):this.getConstructorInferredAuthArgs({auth:t,values:e});default:C(t)}}addAuthMismatchError(t,e){this.context.errors.add({severity:P.Critical,message:this.context.newAuthMismatchError({auth:t,values:e}).message})}addWarning(t){this.context.errors.add({severity:P.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:e}){return[{name:this.context.getPropertyName(t.username),value:x.TypeInstantiation.str(e.username)},{name:this.context.getPropertyName(t.password),value:x.TypeInstantiation.str(e.password)}]}getConstructorBearerAuthArgs({auth:t,values:e}){return[{name:this.context.getPropertyName(t.token),value:x.TypeInstantiation.str(e.token)}]}getConstructorHeaderAuthArgs({auth:t,values:e}){return[{name:this.context.getPropertyName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:e.value})}]}getConstructorOAuthArgs({auth:t,values:e}){return[{name:this.context.getPropertyName(t.clientId),value:x.TypeInstantiation.str(e.clientId)},{name:this.context.getPropertyName(t.clientSecret),value:x.TypeInstantiation.str(e.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:e}){let i=t.parameters??[];if(i.length===0)return this.addWarning("Inferred auth scheme is missing parameters; cannot generate constructor arguments."),[];let a=e.values;if(a==null)return this.addWarning("Inferred auth values were not provided; cannot generate constructor arguments."),[];let l=[];for(let s of i){let b=s.name.wireValue;if(!Object.hasOwn(a,b)){this.addWarning(`Missing inferred auth value for ${b}`);continue}let E=a[b],A=this.context.dynamicTypeLiteralMapper.convert({typeReference:s.typeReference,value:E});x.TypeInstantiation.isNop(A)||l.push({name:this.context.getPropertyName(s.name.name),value:A})}return l}getConstructorHeaderArgs({headers:t,values:e}){let i=[];for(let a of t){let l=this.getConstructorHeaderArg({header:a,value:e.value});l!=null&&i.push(l)}return i}getConstructorHeaderArg({header:t,value:e}){let i=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:e});if(!x.TypeInstantiation.isNop(i))return{name:this.context.getPropertyName(t.name.name),value:i}}callMethod({endpoint:t,snippet:e}){return x.invokeMethod({on:x.reference({name:pi}),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:e}).filter(i=>!x.TypeInstantiation.isNop(i.value)).map(i=>x.methodArgument({name:i.name,value:i.value})),multiline:!0})}getMethodArgs({endpoint:t,snippet:e}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:e});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:e});default:C(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:e}){let i=[];this.context.errors.scope(Z.PathParameters);let a=[...this.context.ir.pathParameters??[],...t.pathParameters??[]],l=new Set;if(t.body!=null){let s=this.getBodyRequestArgs({body:t.body,value:e.requestBody});if(l=new Set(s.map(b=>b.name)),t.body.type==="typeReference"){let b=t.body.value;if(b.type==="named"){let E=this.context.resolveNamedType({typeId:b.value});if(E!=null&&E.type==="object")for(let A of E.properties)this.resolvesToLiteralType(A.typeReference)||l.add(this.context.getPropertyName(A.name.name))}}}if(a.length>0){let b=this.getPathParameters({namedParameters:a,snippet:e}).map(E=>l.has(E.name)?{...E,name:E.name+"_"}:E);i.push(...b)}return this.context.errors.unscope(),this.context.errors.scope(Z.RequestBody),t.body!=null&&i.push(...this.getBodyRequestArgs({body:t.body,value:e.requestBody})),this.context.errors.unscope(),i}getBodyRequestArgs({body:t,value:e}){switch(t.type){case"bytes":return[{name:ze,value:this.getBytesBodyRequestTypeInstantiation({value:e})}];case"typeReference":return this.getBodyRequestArgsForTypeReference({typeReference:t.value,value:e});default:C(t)}}getBodyRequestArgsForTypeReference({typeReference:t,value:e}){switch(t.type){case"named":{let i=this.context.resolveNamedType({typeId:t.value});return i==null?[]:this.getBodyRequestArgsForNamedTypeReference({typeReference:t,named:i,value:e})}case"nullable":case"optional":{let i=t.value;return i.type==="named"&&this.context.resolveNamedType({typeId:i.value})?.type==="object"?[{name:ze,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:i,value:e})}]:this.getBodyRequestArgsForTypeReference({typeReference:t.value,value:e})}case"list":case"map":case"set":case"literal":case"primitive":case"unknown":return[{name:ze,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:e})}];default:C(t)}}getBodyRequestArgsForNamedTypeReference({typeReference:t,named:e,value:i}){switch(e.type){case"alias":return this.getBodyRequestArgsForTypeReference({typeReference:e.typeReference,value:i});case"enum":case"discriminatedUnion":case"undiscriminatedUnion":return[{name:ze,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:i})}];case"object":return this.context.customConfig.inline_request_params===!1?[{name:ze,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:i})}]:this.context.associateByWireValue({parameters:e.properties,values:this.context.getRecord(i)??{}}).filter(s=>!this.resolvesToLiteralType(s.typeReference)).map(s=>({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)}));default:C(e)}}resolvesToLiteralType(t){switch(t.type){case"literal":return!0;case"optional":case"nullable":return this.resolvesToLiteralType(t.value);case"named":{let e=this.context.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.resolvesToLiteralType(e.typeReference):!1}case"list":case"map":case"set":case"primitive":case"unknown":return!1;default:C(t)}}getBodyRequestArgsForBytes({body:t,value:e}){let i=this.getBytesBodyRequestTypeInstantiation({value:e});return x.TypeInstantiation.isNop(i)?[]:[{name:this.context.getPropertyName(t.bodyKey),value:i}]}getBytesBodyRequestTypeInstantiation({value:t}){return typeof t!="string"?(this.context.errors.add({severity:P.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),x.TypeInstantiation.nop()):x.TypeInstantiation.bytes(t)}getBodyPropertyNamesForInlinedRequest(t){if(t.body==null)return new Set;switch(t.body.type){case"referenced":{let e=t.body.bodyType;if(e.type!=="typeReference")return new Set;let i=e.value;if(i.type!=="named")return new Set;let a=this.context.resolveNamedType({typeId:i.value});if(a==null||a.type!=="object")return new Set;let l=new Set;for(let s of a.properties)this.resolvesToLiteralType(s.typeReference)||l.add(this.context.getPropertyName(s.name.name));return l}case"properties":return new Set(t.body.value.filter(e=>!this.resolvesToLiteralType(e.typeReference)).map(e=>this.context.getPropertyName(e.name.name)));case"fileUpload":return new Set(t.body.properties.filter(e=>e.type==="bodyProperty").map(e=>this.context.getPropertyName(e.name.name)));default:C(t.body)}}getMethodArgsForInlinedRequest({request:t,snippet:e}){let i=[],a=this.context.shouldInlinePathParameters();this.context.errors.scope(Z.PathParameters);let l=[];t.pathParameters!=null&&l.push(...this.getPathParameters({namedParameters:t.pathParameters,snippet:e})),this.context.errors.unscope(),this.context.errors.scope(Z.RequestBody);let s=this.getFilePropertyInfo({request:t,snippet:e});this.context.errors.unscope();let b=this.getBodyPropertyNamesForInlinedRequest(t),E=l.map(A=>b.has(A.name)?{...A,name:`${A.name}_`}:A);return this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:a})||i.push(...E),this.context.needsRequestParameter({request:t,inlinePathParameters:a,inlineFileProperties:!0})&&i.push(...this.getInlinedRequestArgs({request:t,snippet:e,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:a})?E:[],filePropertyInfo:s})),i}getFilePropertyInfo({request:t,snippet:e}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:e.requestBody})}getInlinedRequestArgs({request:t,snippet:e,pathParameterFields:i,filePropertyInfo:a}){this.context.errors.scope(Z.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:e.queryParameters??{}}).map(R=>({name:this.context.getPropertyName(R.name.name),value:this.context.dynamicTypeLiteralMapper.convert(R)}));this.context.errors.unscope(),this.context.errors.scope(Z.Headers);let E=this.context.associateByWireValue({parameters:t.headers??[],values:e.headers??{}}).map(R=>({name:this.context.getPropertyName(R.name.name),value:this.context.dynamicTypeLiteralMapper.convert(R)}));this.context.errors.unscope(),this.context.errors.scope(Z.RequestBody);let A=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:e.requestBody,filePropertyInfo:a}):[];return this.context.errors.unscope(),[...i,...s,...E,...A]}getInlinedRequestBodyObjectFields({body:t,value:e,filePropertyInfo:i}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:e});case"referenced":return this.getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:e});case"fileUpload":return this.getFileUploadRequestBodyObjectFields({filePropertyInfo:i});default:C(t)}}getFileUploadRequestBodyObjectFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:e}){let i=t.bodyType;switch(i.type){case"bytes":return this.getBodyRequestArgsForBytes({body:t,value:e});case"typeReference":return this.getBodyRequestArgsForTypeReference({typeReference:i.value,value:e});default:C(i)}}getInlinedRequestBodyPropertyObjectFields({parameters:t,value:e}){let i=[],l=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(e)??{}}).filter(s=>!this.resolvesToLiteralType(s.typeReference));for(let s of l)i.push({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)});return i}getPathParameters({namedParameters:t,snippet:e}){let i=[],a=t.filter(s=>!this.resolvesToLiteralType(s.typeReference)),l=this.context.associateByWireValue({parameters:a,values:e.pathParameters??{},ignoreMissingParameters:!0});for(let s of l)i.push({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)});return i}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(e=>this.context.getMethodName(e)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getEnvironmentOptionName({environment:t}){return t!=null?"environment":"base_url"}};var pt=class extends De{constructor({ir:t,config:e}){super(new st({ir:t,config:e}))}async generate(t,e={}){return super.generate(t,e)}generateSync(t,e={}){return super.generateSync(t,e)}async generateSnippetAst(t,e={}){return super.generateSnippetAst(t,e)}generateMethodCallSnippetAst({request:t,options:e={}}){let i=this.resolveEndpointsForMethodCall({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a;for(let l of i){let s=this.context.clone(),b=this.createSnippetGenerator(s);try{return b.generateMethodCallSnippetAst({endpoint:l,request:t})}catch(E){a=E}}throw a??new Error(`Failed to generate method call snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}resolveEndpointsForMethodCall({request:t,options:e}){if(e.endpointId!=null){let i=this.context.resolveEndpointById(e.endpointId);if(i==null)throw new Error(`No endpoint found with ID "${e.endpointId}"`);return[i]}return this.context.resolveEndpointLocationOrThrow(t.endpoint)}createSnippetGenerator(t){return new ut({context:t})}};0&&(module.exports={DynamicSnippetsGenerator});
20
+ `)}),e.writeNoIndent('"""')}escapeString(e){return e.replace(/\\/g,"\\\\").replace(/"/g,'\\"').replace(/'/g,"\\'").replace(/\t/g,"\\t").replace(/\n/g,"\\n").replace(/\r/g,"\\r")}writeUnknown({writer:e,value:i}){switch(typeof i){case"boolean":e.write(i?"True":"False");return;case"string":e.write(`"${this.escapeString(i)}"`);return;case"number":e.write(i.toString());return;case"object":if(i==null){e.write("None");return}if(Array.isArray(i)){this.writeUnknownArray({writer:e,value:i});return}this.writeUnknownObject({writer:e,value:i});return;default:throw new Error(`Internal error; unsupported unknown type: ${typeof i}`)}}writeUnknownArray({writer:e,value:i}){if(i.length===0){e.write("[]");return}e.writeLine("["),e.indent();for(let a of i)e.writeNode(p.unknown(a)),e.writeLine(",");e.dedent(),e.write("]")}writeUnknownObject({writer:e,value:i}){let a=Object.entries(i);if(a.length===0){e.write("{}");return}e.writeLine("{"),e.indent();for(let[l,s]of a)e.write(`"${l}": `),e.writeNode(p.unknown(s)),e.writeLine(",");e.dedent(),e.write("}")}};function Na({entries:p}){return p.filter(t=>!fe.isNop(t.key)&&!fe.isNop(t.value))}function Sa({entries:p}){return p.filter(t=>!fe.isNop(t.value))}function Tt({values:p}){return p.filter(t=>!fe.isNop(t))}function Ba(p){return new Ee(p)}function Pa(p){return new nt(p)}function Fa(p){return new ke(p)}function Ca(p){return new se(p)}function ka(p){return new Te(p)}function La(p){return new Ae(p)}function Ua(p){return new Q(p)}function Ma(p){return new ce(p)}function Oa(p){return new ue(p)}function _a(p){return new ne(p)}function Va(p){return new Re(p)}function $a(p){return new Ne(p)}function Da(p){return new Se(p)}function ja(p){return new le(p)}function Wa(p){return new be(p)}function qa(p){return new Fe(p)}function Ga(p){return new pe(p)}function za(p){return new Pe(p)}function Ha(p){return new Ce(p)}f();m();d();var Qa="value",ot=class{constructor({context:t}){y(this,"context");this.context=t}convert(t){if(t.value===null)return this.context.isNullable(t.typeReference)?x.TypeInstantiation.none():(this.context.errors.add({severity:P.Critical,message:"Expected non-null value, but got null"}),x.TypeInstantiation.nop());if(t.value===void 0)return x.TypeInstantiation.nop();switch(t.typeReference.type){case"list":return this.convertList({list:t.typeReference.value,value:t.value});case"literal":return this.convertLiteral({literalType:t.typeReference.value,value:t.value});case"map":return this.convertMap({map:t.typeReference,value:t.value});case"named":{let e=this.context.resolveNamedType({typeId:t.typeReference.value});return e==null?x.TypeInstantiation.nop():this.convertNamed({named:e,value:t.value,as:t.as})}case"optional":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"nullable":return this.convert({typeReference:t.typeReference.value,value:t.value,as:t.as});case"primitive":return this.convertPrimitive({primitive:t.typeReference.value,value:t.value,as:t.as});case"set":return this.convertSet({set:t.typeReference.value,value:t.value});case"unknown":return x.TypeInstantiation.unknown(t.value);default:C(t.typeReference)}}convertLiteral({literalType:t,value:e}){switch(t.type){case"boolean":{let i=this.context.getValueAsBoolean({value:e});return i==null?x.TypeInstantiation.nop():x.TypeInstantiation.bool(i)}case"string":{let i=this.context.getValueAsString({value:e});return i==null?x.TypeInstantiation.nop():x.TypeInstantiation.str(i)}default:C(t)}}convertList({list:t,value:e}){return Array.isArray(e)?x.TypeInstantiation.list(e.map((i,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}}),{multiline:!0}):(this.context.errors.add({severity:P.Critical,message:`Expected array but got: ${typeof e}`}),x.TypeInstantiation.nop())}convertSet({set:t,value:e}){return Array.isArray(e)?x.TypeInstantiation.list(e.map((i,a)=>{this.context.errors.scope({index:a});try{return this.convert({typeReference:t,value:i})}finally{this.context.errors.unscope()}}),{multiline:!0}):(this.context.errors.add({severity:P.Critical,message:`Expected array but got: ${typeof e}`}),x.TypeInstantiation.nop())}convertMap({map:t,value:e}){return typeof e!="object"||e==null?(this.context.errors.add({severity:P.Critical,message:`Expected object but got: ${e==null?"null":typeof e}`}),x.TypeInstantiation.nop()):x.TypeInstantiation.dict(Object.entries(e).map(([i,a])=>{this.context.errors.scope(i);try{return{key:this.convert({typeReference:t.key,value:i,as:"key"}),value:this.convert({typeReference:t.value,value:a})}}finally{this.context.errors.unscope()}}),{multiline:!0})}convertNamed({named:t,value:e,as:i}){switch(t.type){case"alias":return this.convert({typeReference:t.typeReference,value:e,as:i});case"discriminatedUnion":return this.convertDiscriminatedUnion({discriminatedUnion:t,value:e});case"enum":return this.convertEnum({enum_:t,value:e});case"object":return this.convertObject({object_:t,value:e});case"undiscriminatedUnion":return this.convertUndiscriminatedUnion({undiscriminatedUnion:t,value:e});default:C(t)}}convertDiscriminatedUnion({discriminatedUnion:t,value:e}){let i=this.context.resolveDiscriminatedUnionTypeInstance({discriminatedUnion:t,value:e});if(i==null)return x.TypeInstantiation.nop();let a=i.singleDiscriminatedUnionType,l=this.convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:i,unionVariant:a});if(l==null)return x.TypeInstantiation.nop();let s={name:this.context.getPropertyName(t.discriminant.name),value:x.TypeInstantiation.str(a.discriminantValue.wireValue)};return x.TypeInstantiation.typedDict([s,...l],{multiline:!0})}convertDiscriminatedUnionProperties({discriminatedUnionTypeInstance:t,unionVariant:e}){let i=this.getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:e});switch(e.type){case"samePropertiesAsObject":{let a=this.context.resolveNamedType({typeId:e.typeId});if(a==null)return;let l=this.convertNamed({named:a,value:t.value});if(!l.isTypedDict()){this.context.errors.add({severity:P.Critical,message:"Internal error; expected union value to be an object"});return}let s=l.asTypedDictOrThrow();return[...i,...s.entries]}case"singleProperty":try{this.context.errors.scope(e.discriminantValue.wireValue);let a=this.context.getRecord(t.value);return a==null?[...i,{name:Qa,value:this.convert({typeReference:e.typeReference,value:t.value})}]:[...i,{name:this.context.getPropertyName(e.discriminantValue.name),value:this.convert({typeReference:e.typeReference,value:a[e.discriminantValue.wireValue]})}]}finally{this.context.errors.unscope()}case"noProperties":return i;default:C(e)}}getBaseFields({discriminatedUnionTypeInstance:t,singleDiscriminatedUnionType:e}){return this.context.associateByWireValue({parameters:e.properties??[],values:this.context.getRecord(t.value)??{},ignoreMissingParameters:!0}).map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert(a)}}finally{this.context.errors.unscope()}})}convertObject({object_:t,value:e}){let i=this.context.associateByWireValue({parameters:t.properties,values:this.context.getRecord(e)??{}});return x.TypeInstantiation.typedDict(i.map(a=>{this.context.errors.scope(a.name.wireValue);try{return{name:this.context.getPropertyName(a.name.name),value:this.convert(a)}}finally{this.context.errors.unscope()}}),{multiline:!0})}convertEnum({enum_:t,value:e}){let i=this.getEnumValue({enum_:t,value:e});return i==null?x.TypeInstantiation.nop():x.TypeInstantiation.str(i)}getEnumValue({enum_:t,value:e}){if(typeof e!="string"){this.context.errors.add({severity:P.Critical,message:`Expected enum value string, got: ${typeof e}`});return}if(t.values.find(a=>a.wireValue===e)==null){this.context.errors.add({severity:P.Critical,message:`An enum value named "${e}" does not exist in this context`});return}return e}convertUndiscriminatedUnion({undiscriminatedUnion:t,value:e}){let i=this.findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:e});return i??x.TypeInstantiation.nop()}findMatchingUndiscriminatedUnionType({undiscriminatedUnion:t,value:e}){for(let i of t.types){let a=this.context.errors.size();try{let l=this.convert({typeReference:i,value:e});if(x.TypeInstantiation.isNop(l)){this.context.errors.truncate(a);continue}return l}catch{this.context.errors.truncate(a);continue}}this.context.errors.add({severity:P.Critical,message:`None of the types in the undiscriminated union matched the given "${typeof e}" value`})}convertPrimitive({primitive:t,value:e,as:i}){switch(t){case"INTEGER":case"LONG":case"UINT":case"UINT_64":{let a=this.getValueAsNumber({value:e,as:i});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.int(a)}case"FLOAT":case"DOUBLE":{let a=this.getValueAsNumber({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.float(a)}case"BOOLEAN":{let a=this.getValueAsBoolean({value:e,as:i});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.bool(a)}case"BASE_64":case"BIG_INTEGER":case"STRING":{let a=this.context.getValueAsString({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.str(a)}case"UUID":{let a=this.context.getValueAsString({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.uuid(a)}case"DATE":{let a=this.context.getValueAsString({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.date(a)}case"DATE_TIME":{let a=this.context.getValueAsString({value:e});return a==null?x.TypeInstantiation.nop():x.TypeInstantiation.datetime(a)}default:C(t)}}getValueAsNumber({value:t,as:e}){let i=e==="key"&&typeof t=="string"?Number(t):t;return this.context.getValueAsNumber({value:i})}getValueAsBoolean({value:t,as:e}){let i=e==="key"?typeof t=="string"?t==="true":t==="false"?!1:t:t;return this.context.getValueAsBoolean({value:i})}};f();m();d();var at=class{constructor({context:t}){y(this,"context");this.context=t}getFilePropertyInfo({body:t,value:e}){let i={fileFields:[],bodyPropertyFields:[]},a=this.context.getRecord(e)??{};for(let l of t.properties)switch(l.type){case"file":{let s=this.getSingleFileProperty({property:l,record:a});if(x.TypeInstantiation.isNop(s))break;i.fileFields.push({name:this.context.getPropertyName(l.name),value:s});break}case"fileArray":{let s=this.getArrayFileProperty({property:l,record:a});if(x.TypeInstantiation.isNop(s))break;i.fileFields.push({name:this.context.getPropertyName(l.name),value:s});break}case"bodyProperty":{let s=this.getBodyProperty({property:l,record:a});if(x.TypeInstantiation.isNop(s))break;i.bodyPropertyFields.push({name:this.context.getPropertyName(l.name.name),value:s});break}default:C(l)}return i}getSingleFileProperty({property:t,record:e}){let i=this.context.getSingleFileValue({property:t,record:e});return i==null&&(i=`example_${t.wireValue??"file"}`),this.context.getFileFromString(i)}getArrayFileProperty({property:t,record:e}){let i=this.context.getFileArrayValues({property:t,record:e});if(i==null){let a=`example_${t.wireValue??"files"}`;return x.TypeInstantiation.list([this.context.getFileFromString(a)])}return x.TypeInstantiation.list(i.map(a=>this.context.getFileFromString(a)))}getBodyProperty({property:t,record:e}){let i=e[t.name.wireValue];return i==null?x.TypeInstantiation.nop():this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:i})}};var Ya=["list","set"],st=class p extends qe{constructor({ir:e,config:i}){super({ir:e,config:i});y(this,"ir");y(this,"customConfig");y(this,"dynamicTypeLiteralMapper");y(this,"filePropertyMapper");this.ir=e,this.customConfig=i.customConfig??{},this.dynamicTypeLiteralMapper=new ot({context:this}),this.filePropertyMapper=new at({context:this})}clone(){return new p({ir:this.ir,config:this.config})}getClassName(e){let i=e.pascalCase.safeName,a=this.getRootClientClassName();return i===a?`${a}Model`:i}getTypedDictClassName(e){return`${this.getClassName(e)}Params`}getPropertyName(e){let i=e.snakeCase.safeName;return i.startsWith("_")?"f_"+i.substring(i.lastIndexOf("_")+1):i}getMethodName(e){return Ya.includes(e.snakeCase.unsafeName)?e.snakeCase.unsafeName:e.snakeCase.safeName}getRootClientClassReference(){return x.reference({name:this.getRootClientClassName(),modulePath:this.getRootModulePath()})}getRootClientClassName(){return this.customConfig.client?.exported_class_name!=null?this.customConfig.client.exported_class_name:this.customConfig.client_class_name!=null?this.customConfig.client_class_name:this.customConfig.client?.class_name!=null?this.customConfig.client.class_name:this.pascalCase(this.config.organization)+this.pascalCase(this.config.workspaceName)}getEnvironmentClassName(){return`${this.getRootClientClassName()}Environment`}getEnvironmentTypeReferenceFromID(e){let i=this.resolveEnvironmentName(e);if(i!=null)return x.accessAttribute({lhs:this.getEnvironmentClassReference(),rhs:x.codeBlock(this.getEnvironmentEnumName(i))})}getEnvironmentClassReference(){return x.reference({name:this.getEnvironmentClassName(),modulePath:this.getEnvironmentModulePath()})}getEnvironmentEnumName(e){return e.screamingSnakeCase.safeName}isPrimitive(e){switch(e.type){case"primitive":return!0;case"optional":case"nullable":return this.isPrimitive(e.value);case"named":{let i=this.resolveNamedType({typeId:e.value});if(i==null)return!1;switch(i.type){case"alias":return this.isPrimitive(i.typeReference);case"discriminatedUnion":case"undiscriminatedUnion":case"object":case"enum":return!1;default:C(i)}break}case"list":case"set":case"map":case"literal":case"unknown":return!1;default:C(e)}}getFileFromString(e){return x.TypeInstantiation.str(e)}getRootModulePath(){if(this.customConfig.package_name!=null)return[this.customConfig.package_name];let e=this.cleanOrganizationName();return this.customConfig.use_api_name_in_package?[e,this.getApiName()]:[e]}getCoreModulePath(){return this.getRootModulePath().concat("core")}getEnvironmentModulePath(){return this.getRootModulePath().concat("environment")}shouldInlinePathParameters(){return!0}cleanOrganizationName(){return this.config.organization.replace(/[^a-zA-Z0-9]/g,"_")}getApiName(){return vt(this.config.workspaceName)}pascalCase(e){let i=wt(e);return i.charAt(0).toUpperCase()+i.slice(1)}};f();m();d();var Za={type:"primitive",value:"STRING"},Ja=["example"],pi="client",ze="request",ut=class{constructor({context:t}){y(this,"context");this.context=t}async generateSnippet({endpoint:t,request:e}){return this.buildPythonFile({endpoint:t,snippet:e}).toString()}generateSnippetSync({endpoint:t,request:e}){return this.buildPythonFile({endpoint:t,snippet:e}).toString()}async generateSnippetAst({endpoint:t,request:e}){return this.buildPythonFile({endpoint:t,snippet:e})}generateMethodCallSnippetAst({endpoint:t,request:e}){return this.callMethod({endpoint:t,snippet:e})}buildPythonFile({endpoint:t,snippet:e}){return x.file({path:Ja,statements:[this.constructClient({endpoint:t,snippet:e}),this.callMethod({endpoint:t,snippet:e})]})}constructClient({endpoint:t,snippet:e}){return x.assign({lhs:x.reference({name:pi}),rhs:x.instantiateClass({classReference:this.context.getRootClientClassReference(),arguments_:this.getConstructorArgs({endpoint:t,snippet:e}).map(i=>x.methodArgument({name:i.name,value:i.value})),multiline:!0})})}getConstructorArgs({endpoint:t,snippet:e}){let i=[],a=this.getConstructorEnvironmentArgs({baseUrl:e.baseURL,environment:e.environment});return a.length>0&&i.push(...a),t.auth!=null&&(e.auth!=null?i.push(...this.getConstructorAuthArgs({auth:t.auth,values:e.auth})):this.context.errors.add({severity:P.Warning,message:`Auth with ${t.auth.type} configuration is required for this endpoint`})),this.context.errors.scope(Z.PathParameters),this.context.ir.pathParameters!=null&&i.push(...this.getPathParameters({namedParameters:this.context.ir.pathParameters,snippet:e})),this.context.errors.unscope(),this.context.errors.scope(Z.Headers),this.context.ir.headers!=null&&e.headers!=null&&i.push(...this.getConstructorHeaderArgs({headers:this.context.ir.headers,values:e.headers})),this.context.errors.unscope(),i}getConstructorEnvironmentArgs({baseUrl:t,environment:e}){let i=this.getEnvironmentValue({baseUrl:t,environment:e});return i==null?[]:e!=null&&this.context.isMultiEnvironmentValues(e)?[{name:"environment",value:i}]:[{name:this.getEnvironmentOptionName({environment:e}),value:i}]}getEnvironmentValue({baseUrl:t,environment:e}){if(t!=null&&e!=null){this.context.errors.add({severity:P.Critical,message:"Cannot specify both baseUrl and environment options"});return}if(t!=null)return x.TypeInstantiation.str(t);if(e!=null){if(this.context.isSingleEnvironmentID(e)){let i=this.context.getEnvironmentTypeReferenceFromID(e);if(i==null){this.context.errors.add({severity:P.Warning,message:`Environment ${JSON.stringify(e)} was not found`});return}return x.TypeInstantiation.reference(i)}if(this.context.isMultiEnvironmentValues(e))return this.context.validateMultiEnvironmentUrlValues(e)?x.TypeInstantiation.reference(x.instantiateClass({classReference:this.context.getEnvironmentClassReference(),arguments_:Object.entries(e).map(([i,a])=>({name:i,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:Za,value:a})})).map(i=>x.methodArgument({name:i.name,value:i.value})),multiline:!0})):void 0}}getConstructorAuthArgs({auth:t,values:e}){switch(t.type){case"basic":return e.type!=="basic"?(this.addAuthMismatchError(t,e),[]):this.getConstructorBasicAuthArg({auth:t,values:e});case"bearer":return e.type!=="bearer"?(this.addAuthMismatchError(t,e),[]):this.getConstructorBearerAuthArgs({auth:t,values:e});case"header":return e.type!=="header"?(this.addAuthMismatchError(t,e),[]):this.getConstructorHeaderAuthArgs({auth:t,values:e});case"oauth":return e.type!=="oauth"?(this.addAuthMismatchError(t,e),[]):this.getConstructorOAuthArgs({auth:t,values:e});case"inferred":return e.type!=="inferred"?(this.addAuthMismatchError(t,e),[]):this.getConstructorInferredAuthArgs({auth:t,values:e});default:C(t)}}addAuthMismatchError(t,e){this.context.errors.add({severity:P.Critical,message:this.context.newAuthMismatchError({auth:t,values:e}).message})}addWarning(t){this.context.errors.add({severity:P.Warning,message:t})}getConstructorBasicAuthArg({auth:t,values:e}){return[{name:this.context.getPropertyName(t.username),value:x.TypeInstantiation.str(e.username)},{name:this.context.getPropertyName(t.password),value:x.TypeInstantiation.str(e.password)}]}getConstructorBearerAuthArgs({auth:t,values:e}){return[{name:this.context.getPropertyName(t.token),value:x.TypeInstantiation.str(e.token)}]}getConstructorHeaderAuthArgs({auth:t,values:e}){return[{name:this.context.getPropertyName(t.header.name.name),value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t.header.typeReference,value:e.value})}]}getConstructorOAuthArgs({auth:t,values:e}){return[{name:this.context.getPropertyName(t.clientId),value:x.TypeInstantiation.str(e.clientId)},{name:this.context.getPropertyName(t.clientSecret),value:x.TypeInstantiation.str(e.clientSecret)}]}getConstructorInferredAuthArgs({auth:t,values:e}){let i=t.parameters??[];if(i.length===0)return this.addWarning("Inferred auth scheme is missing parameters; cannot generate constructor arguments."),[];let a=e.values;if(a==null)return this.addWarning("Inferred auth values were not provided; cannot generate constructor arguments."),[];let l=[];for(let s of i){let b=s.name.wireValue;if(!Object.hasOwn(a,b)){this.addWarning(`Missing inferred auth value for ${b}`);continue}let E=a[b],A=this.context.dynamicTypeLiteralMapper.convert({typeReference:s.typeReference,value:E});x.TypeInstantiation.isNop(A)||l.push({name:this.context.getPropertyName(s.name.name),value:A})}return l}getConstructorHeaderArgs({headers:t,values:e}){let i=[];for(let a of t){let l=this.getConstructorHeaderArg({header:a,value:e.value});l!=null&&i.push(l)}return i}getConstructorHeaderArg({header:t,value:e}){let i=this.context.dynamicTypeLiteralMapper.convert({typeReference:t.typeReference,value:e});if(!x.TypeInstantiation.isNop(i))return{name:this.context.getPropertyName(t.name.name),value:i}}callMethod({endpoint:t,snippet:e}){return x.invokeMethod({on:x.reference({name:pi}),method:this.getMethod({endpoint:t}),arguments_:this.getMethodArgs({endpoint:t,snippet:e}).filter(i=>!x.TypeInstantiation.isNop(i.value)).map(i=>x.methodArgument({name:i.name,value:i.value})),multiline:!0})}getMethodArgs({endpoint:t,snippet:e}){switch(t.request.type){case"inlined":return this.getMethodArgsForInlinedRequest({request:t.request,snippet:e});case"body":return this.getMethodArgsForBodyRequest({request:t.request,snippet:e});default:C(t.request)}}getMethodArgsForBodyRequest({request:t,snippet:e}){let i=[];this.context.errors.scope(Z.PathParameters);let a=[...this.context.ir.pathParameters??[],...t.pathParameters??[]],l=new Set;if(t.body!=null){let s=this.getBodyRequestArgs({body:t.body,value:e.requestBody});if(l=new Set(s.map(b=>b.name)),t.body.type==="typeReference"){let b=t.body.value;if(b.type==="named"){let E=this.context.resolveNamedType({typeId:b.value});if(E!=null&&E.type==="object")for(let A of E.properties)this.resolvesToLiteralType(A.typeReference)||l.add(this.context.getPropertyName(A.name.name))}}}if(a.length>0){let b=this.getPathParameters({namedParameters:a,snippet:e}).map(E=>l.has(E.name)?{...E,name:E.name+"_"}:E);i.push(...b)}return this.context.errors.unscope(),this.context.errors.scope(Z.RequestBody),t.body!=null&&i.push(...this.getBodyRequestArgs({body:t.body,value:e.requestBody})),this.context.errors.unscope(),i}getBodyRequestArgs({body:t,value:e}){switch(t.type){case"bytes":return[{name:ze,value:this.getBytesBodyRequestTypeInstantiation({value:e})}];case"typeReference":return this.getBodyRequestArgsForTypeReference({typeReference:t.value,value:e});default:C(t)}}getBodyRequestArgsForTypeReference({typeReference:t,value:e}){switch(t.type){case"named":{let i=this.context.resolveNamedType({typeId:t.value});return i==null?[]:this.getBodyRequestArgsForNamedTypeReference({typeReference:t,named:i,value:e})}case"nullable":case"optional":{let i=t.value;return i.type==="named"&&this.context.resolveNamedType({typeId:i.value})?.type==="object"?[{name:ze,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:i,value:e})}]:this.getBodyRequestArgsForTypeReference({typeReference:t.value,value:e})}case"list":case"map":case"set":case"literal":case"primitive":case"unknown":return[{name:ze,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:e})}];default:C(t)}}getBodyRequestArgsForNamedTypeReference({typeReference:t,named:e,value:i}){switch(e.type){case"alias":return this.getBodyRequestArgsForTypeReference({typeReference:e.typeReference,value:i});case"enum":case"discriminatedUnion":case"undiscriminatedUnion":return[{name:ze,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:i})}];case"object":return this.context.customConfig.inline_request_params===!1?[{name:ze,value:this.context.dynamicTypeLiteralMapper.convert({typeReference:t,value:i})}]:this.context.associateByWireValue({parameters:e.properties,values:this.context.getRecord(i)??{}}).filter(s=>!this.resolvesToLiteralType(s.typeReference)).map(s=>({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)}));default:C(e)}}resolvesToLiteralType(t){switch(t.type){case"literal":return!0;case"optional":case"nullable":return this.resolvesToLiteralType(t.value);case"named":{let e=this.context.resolveNamedType({typeId:t.value});return e==null?!1:e.type==="alias"?this.resolvesToLiteralType(e.typeReference):!1}case"list":case"map":case"set":case"primitive":case"unknown":return!1;default:C(t)}}getBodyRequestArgsForBytes({body:t,value:e}){let i=this.getBytesBodyRequestTypeInstantiation({value:e});return x.TypeInstantiation.isNop(i)?[]:[{name:this.context.getPropertyName(t.bodyKey),value:i}]}getBytesBodyRequestTypeInstantiation({value:t}){return typeof t!="string"?(this.context.errors.add({severity:P.Critical,message:`Expected bytes value to be a string, got ${typeof t}`}),x.TypeInstantiation.nop()):x.TypeInstantiation.bytes(t)}getBodyPropertyNamesForInlinedRequest(t){if(t.body==null)return new Set;switch(t.body.type){case"referenced":{let e=t.body.bodyType;if(e.type!=="typeReference")return new Set;let i=e.value;if(i.type!=="named")return new Set;let a=this.context.resolveNamedType({typeId:i.value});if(a==null||a.type!=="object")return new Set;let l=new Set;for(let s of a.properties)this.resolvesToLiteralType(s.typeReference)||l.add(this.context.getPropertyName(s.name.name));return l}case"properties":return new Set(t.body.value.filter(e=>!this.resolvesToLiteralType(e.typeReference)).map(e=>this.context.getPropertyName(e.name.name)));case"fileUpload":return new Set(t.body.properties.filter(e=>e.type==="bodyProperty").map(e=>this.context.getPropertyName(e.name.name)));default:C(t.body)}}getMethodArgsForInlinedRequest({request:t,snippet:e}){let i=[],a=this.context.shouldInlinePathParameters();this.context.errors.scope(Z.PathParameters);let l=[];t.pathParameters!=null&&l.push(...this.getPathParameters({namedParameters:t.pathParameters,snippet:e})),this.context.errors.unscope(),this.context.errors.scope(Z.RequestBody);let s=this.getFilePropertyInfo({request:t,snippet:e});this.context.errors.unscope();let b=this.getBodyPropertyNamesForInlinedRequest(t),E=l.map(A=>b.has(A.name)?{...A,name:`${A.name}_`}:A);return this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:a})||i.push(...E),this.context.needsRequestParameter({request:t,inlinePathParameters:a,inlineFileProperties:!0})&&i.push(...this.getInlinedRequestArgs({request:t,snippet:e,pathParameterFields:this.context.includePathParametersInWrappedRequest({request:t,inlinePathParameters:a})?E:[],filePropertyInfo:s})),i}getFilePropertyInfo({request:t,snippet:e}){return t.body==null||!this.context.isFileUploadRequestBody(t.body)?{fileFields:[],bodyPropertyFields:[]}:this.context.filePropertyMapper.getFilePropertyInfo({body:t.body,value:e.requestBody})}getInlinedRequestArgs({request:t,snippet:e,pathParameterFields:i,filePropertyInfo:a}){this.context.errors.scope(Z.QueryParameters);let s=this.context.associateQueryParametersByWireValue({parameters:t.queryParameters??[],values:e.queryParameters??{}}).map(R=>({name:this.context.getPropertyName(R.name.name),value:this.context.dynamicTypeLiteralMapper.convert(R)}));this.context.errors.unscope(),this.context.errors.scope(Z.Headers);let E=this.context.associateByWireValue({parameters:t.headers??[],values:e.headers??{}}).map(R=>({name:this.context.getPropertyName(R.name.name),value:this.context.dynamicTypeLiteralMapper.convert(R)}));this.context.errors.unscope(),this.context.errors.scope(Z.RequestBody);let A=t.body!=null?this.getInlinedRequestBodyObjectFields({body:t.body,value:e.requestBody,filePropertyInfo:a}):[];return this.context.errors.unscope(),[...i,...s,...E,...A]}getInlinedRequestBodyObjectFields({body:t,value:e,filePropertyInfo:i}){switch(t.type){case"properties":return this.getInlinedRequestBodyPropertyObjectFields({parameters:t.value,value:e});case"referenced":return this.getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:e});case"fileUpload":return this.getFileUploadRequestBodyObjectFields({filePropertyInfo:i});default:C(t)}}getFileUploadRequestBodyObjectFields({filePropertyInfo:t}){return[...t.fileFields,...t.bodyPropertyFields]}getReferencedRequestBodyPropertyTypeInstantiation({body:t,value:e}){let i=t.bodyType;switch(i.type){case"bytes":return this.getBodyRequestArgsForBytes({body:t,value:e});case"typeReference":return this.getBodyRequestArgsForTypeReference({typeReference:i.value,value:e});default:C(i)}}getInlinedRequestBodyPropertyObjectFields({parameters:t,value:e}){let i=[],l=this.context.associateByWireValue({parameters:t,values:this.context.getRecord(e)??{}}).filter(s=>!this.resolvesToLiteralType(s.typeReference));for(let s of l)i.push({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)});return i}getPathParameters({namedParameters:t,snippet:e}){let i=[],a=t.filter(s=>!this.resolvesToLiteralType(s.typeReference)),l=this.context.associateByWireValue({parameters:a,values:e.pathParameters??{},ignoreMissingParameters:!0});for(let s of l)i.push({name:this.context.getPropertyName(s.name.name),value:this.context.dynamicTypeLiteralMapper.convert(s)});return i}getMethod({endpoint:t}){return t.declaration.fernFilepath.allParts.length>0?`${t.declaration.fernFilepath.allParts.map(e=>this.context.getMethodName(e)).join(".")}.${this.context.getMethodName(t.declaration.name)}`:this.context.getMethodName(t.declaration.name)}getEnvironmentOptionName({environment:t}){return t!=null?"environment":"base_url"}};var pt=class extends De{constructor({ir:t,config:e}){super(new st({ir:t,config:e}))}async generate(t,e={}){return super.generate(t,e)}generateSync(t,e={}){return super.generateSync(t,e)}async generateSnippetAst(t,e={}){return super.generateSnippetAst(t,e)}generateMethodCallSnippetAst({request:t,options:e={}}){let i=this.resolveEndpointsForMethodCall({request:t,options:e});if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a;for(let l of i){let s=this.context.clone(),b=this.createSnippetGenerator(s);try{return b.generateMethodCallSnippetAst({endpoint:l,request:t})}catch(E){a=E}}throw a??new Error(`Failed to generate method call snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}resolveEndpointsForMethodCall({request:t,options:e}){if(e.endpointId!=null){let i=this.context.resolveEndpointById(e.endpointId);if(i==null)throw new Error(`No endpoint found with ID "${e.endpointId}"`);return[i]}return this.context.resolveEndpointLocationOrThrow(t.endpoint)}createSnippetGenerator(t){return new ut({context:t})}};0&&(module.exports={DynamicSnippetsGenerator});
21
21
  /*! Bundled license information:
22
22
 
23
23
  @jspm/core/nodelibs/browser/chunk-DtuTasat.js: