@fern-api/python-dynamic-snippets 4.46.10 → 4.46.12
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 +1 -1
- package/dist/index.cjs.map +1 -1
- package/dist/index.js +1 -1
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.js
CHANGED
|
@@ -12,7 +12,7 @@ ${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(et({maxFrames:15,skip:3}))),...this.formatStack(this.filterStack(this.nodeStackFrames),"node")];switch(this.nodeStackFrames.length=0,xt){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 Ia}};f();m();d();f();m();d();f();m();d();var Ve=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 $e=class{constructor(t){y(this,"context");this.context=t}async generate(t,e={}){let i=this.context.resolveEndpointLocationOrThrow(t.endpoint);if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a=new Ve;for(let l of i){let s=this.context.clone(),E=this.createSnippetGenerator(s);try{let b=await E.generateSnippet({endpoint:l,request:t,options:e});if(s.errors.empty())return{snippet:b,errors:void 0};a.update({context:s,snippet:b})}catch(b){a.err==null&&(a.err=b)}}return a.getResponseOrThrow({endpoint:t.endpoint})}async generateSnippetAst(t,e={}){let i=this.context.resolveEndpointLocationOrThrow(t.endpoint);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(),E=this.createSnippetGenerator(s);try{return await E.generateSnippetAst({endpoint:l,request:t,options:e})}catch(b){a=b}}throw a??new Error(`Failed to generate snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}generateSync(t,e={}){let i=this.context.resolveEndpointLocationOrThrow(t.endpoint);if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a=new Ve;for(let l of i){let s=this.context.clone(),E=this.createSnippetGenerator(s);try{let b=E.generateSnippetSync({endpoint:l,request:t,options:e});if(s.errors.empty())return{snippet:b,errors:void 0};a.update({context:s,snippet:b})}catch(b){a.err==null&&(a.err=b)}}return a.getResponseOrThrow({endpoint:t.endpoint})}};f();m();d();f();m();d();f();m();d();var je=class{constructor(){y(this,"REFERENCE_REGEX",/^(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[1]==null||i[2]==null))return{method:i[1],path:i[2]}}};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)){this.errors.scope(a);try{let s=t.find(b=>b.name.wireValue===a);if(s==null)throw this.newParameterNotRecognizedError(a);let E=this.isListTypeReference(s.typeReference)&&!Array.isArray(l)?[l]:l;i.push({name:s.name,typeReference:s.typeReference,value:E})}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)){this.errors.scope(l);try{let E=t.find(b=>b.name.wireValue===l);if(E==null){if(i)continue;this.errors.add({severity:P.Critical,message:this.newParameterNotRecognizedError(l).message});continue}a.push({name:E.name,typeReference:E.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]:E,...b}=i;return{singleDiscriminatedUnionType:s,discriminantValue:s.discriminantValue,value:b}}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={};Ut(x,{AccessAttribute:()=>be,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:()=>rt,TypeInstantiation:()=>fe,accessAttribute:()=>Ta,assign:()=>Ra,class_:()=>Na,codeBlock:()=>ka,comment:()=>La,decorator:()=>Ba,field:()=>Ca,file:()=>Aa,instantiateClass:()=>Sa,invokeFunction:()=>_a,invokeMethod:()=>Da,lambda:()=>Ua,lambdaParameter:()=>Ma,method:()=>Oa,methodArgument:()=>$a,operator:()=>ja,parameter:()=>Va,reference:()=>Pa,starImport:()=>Fa});f();m();d();f();m();d();f();m();d();f();m();d();var Ge=class extends De{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 be=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 tt=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 Ee=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 Ee{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(et({maxFrames:15,skip:3}))),...this.formatStack(this.filterStack(this.nodeStackFrames),"node")];switch(this.nodeStackFrames.length=0,xt){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 Ia}};f();m();d();f();m();d();f();m();d();var Ve=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 $e=class{constructor(t){y(this,"context");this.context=t}async generate(t,e={}){let i=this.context.resolveEndpointLocationOrThrow(t.endpoint);if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a=new Ve;for(let l of i){let s=this.context.clone(),E=this.createSnippetGenerator(s);try{let b=await E.generateSnippet({endpoint:l,request:t,options:e});if(s.errors.empty())return{snippet:b,errors:void 0};a.update({context:s,snippet:b})}catch(b){a.err==null&&(a.err=b)}}return a.getResponseOrThrow({endpoint:t.endpoint})}async generateSnippetAst(t,e={}){let i=this.context.resolveEndpointLocationOrThrow(t.endpoint);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(),E=this.createSnippetGenerator(s);try{return await E.generateSnippetAst({endpoint:l,request:t,options:e})}catch(b){a=b}}throw a??new Error(`Failed to generate snippet AST for endpoint: ${t.endpoint.method} ${t.endpoint.path}`)}generateSync(t,e={}){let i=this.context.resolveEndpointLocationOrThrow(t.endpoint);if(i.length===0)throw new Error(`No endpoints found that match "${t.endpoint.method} ${t.endpoint.path}"`);let a=new Ve;for(let l of i){let s=this.context.clone(),E=this.createSnippetGenerator(s);try{let b=E.generateSnippetSync({endpoint:l,request:t,options:e});if(s.errors.empty())return{snippet:b,errors:void 0};a.update({context:s,snippet:b})}catch(b){a.err==null&&(a.err=b)}}return a.getResponseOrThrow({endpoint:t.endpoint})}};f();m();d();f();m();d();f();m();d();var je=class{constructor(){y(this,"REFERENCE_REGEX",/^(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[1]==null||i[2]==null))return{method:i[1],path:i[2]}}};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(b=>b.name.wireValue===a);if(s==null)throw this.newParameterNotRecognizedError(a);let E=this.isListTypeReference(s.typeReference)&&!Array.isArray(l)?[l]:l;i.push({name:s.name,typeReference:s.typeReference,value:E})}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 E=t.find(b=>b.name.wireValue===l);if(E==null){if(i)continue;this.errors.add({severity:P.Critical,message:this.newParameterNotRecognizedError(l).message});continue}a.push({name:E.name,typeReference:E.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]:E,...b}=i;return{singleDiscriminatedUnionType:s,discriminantValue:s.discriminantValue,value:b}}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={};Ut(x,{AccessAttribute:()=>be,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:()=>rt,TypeInstantiation:()=>fe,accessAttribute:()=>Ta,assign:()=>Ra,class_:()=>Na,codeBlock:()=>ka,comment:()=>La,decorator:()=>Ba,field:()=>Ca,file:()=>Aa,instantiateClass:()=>Sa,invokeFunction:()=>_a,invokeMethod:()=>Da,lambda:()=>Ua,lambdaParameter:()=>Ma,method:()=>Oa,methodArgument:()=>$a,operator:()=>ja,parameter:()=>Va,reference:()=>Pa,starImport:()=>Fa});f();m();d();f();m();d();f();m();d();f();m();d();var Ge=class extends De{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 be=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 tt=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 Ee=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 Ee{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:E,decorators:b}){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=E,this.decorators=b??[],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(E=>{this.inheritReferences(E)})}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(E=>this.addStatement(E)),this.comments=l??[],s?.forEach(E=>this.addReference(E))}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(),E=this.path.join("."),b=i.get(E);if(b){let{references:R}=b;R.forEach(F=>{let V=F.getFullyQualifiedModulePath(),T=F.name;l[V]={name:T,isAlias:!1},s.add(F.name)}),a.delete(E)}Array.from(a.values()).flatMap(({references:R})=>R).forEach(R=>{if(R instanceof ce)return;let F=R.alias??R.name,V=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[V]={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 E=l;if(!this.isDefinedInFile(E)){if(E[0]===this.path[0]){let b=0;for(;b<this.path.length&&b<E.length&&this.path[b]===E[b];)b++;let A=this.path.length-b;this.isInitFile&&A++;let R=A>0?".".repeat(A):".";R+=E.slice(b).join("."),e.write(`from ${R} import ${s.map(F=>this.getImportName({writer:e,reference:F})).join(", ")}`)}else e.write(`from ${a} import ${s.map(b=>this.getImportName({writer:e,reference:b})).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 rt=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=It({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=It({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=It({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=ba({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=Ea({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((E,b)=>{e.writeNoIndent(this.escapeString(E)),b===s.length-1?l&&e.writeNoIndent(`\\
|